Java if else
if Statement
Use the if
statement to specify a block of Java code to be executed if a condition is true
.
if (condition) {
// block of code to be executed if the condition is true
}
Sample program with if
Write a program or WAP to find a number is greater or not.
class SampleIf
{
public static void main(String args[])
{
int a=10;
if (a > 0) {
System.out.println("a is greater than 0");
}
}
}
Output:
if-else Statement
Use the if
statement to specify a block of Java code to be executed if a condition is true
.
if (condition) {
// block of code to be executed if the condition is true
}
else{
// block of code to be executed if the condition is false
}
Sample program with if-else
Write a program or WAP to find which number is greater.
class SampleIfElse
{
public static void main(String args[])
{
int a=10;
if (a > 0) {
System.out.println("a is greater than 0");
}
else
{
System.out.println("a is smaller than 0");
}
}
}
Output:
Ladder if-else Statement
If we have multiple conditions for a program then we need to use ladder if
– else
.
if (condition) {
// block of code to be executed if the condition is true
}
else if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is true
}
Sample program with Ladder if-else
Write a program or WAP to find a number is positive (+ve), negative (-ve) or zero (0).
class SampleLadderIfElse
{
public static void main(String args[])
{
int a=10;
if (a > 0) {
System.out.println("a is +ve");
}
else if (a < 0) {
System.out.println("a is -ve");
}
else {
System.out.println("a is zero");
}
}
}
Output:
Nested if else Statement
If we use the if - else
statement within another if - else
then we use nested if - else
.
if (condition) {
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
}
else
{
if (condition) {
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
}
Sample program with Nested if-else
Write a program or WAP to find which number is greatest in three given number.
class SampleNestedIfElse
{
public static void main(String args[])
{
int a=10,b=20,c=30;
if (a>b)
{
if (a>c)
{
System.out.println("a is greatest.");
}
else
{
System.out.println("c is greatest.");
}
}
else
{
if (b>c)
{
System.out.println("b is greatest.");
}
else
{
System.out.println("c is greatest.");
}
}
}
}