if condition program in java
If condition in java:
“if “ is a conditional
statement is java, it is check the condition only once. If condition is true
then conditional block will be execute. If condition is false then “if” block
will be exit and execute the else block.
Syntax:
if(condition){
.........
statments ........
}
else{
...........
statmetns ........
}
public class IfCondTest {
public static void main(String args[]) {
int a=30,b=20;
if(a>b) {
System.out.println("a is greater");
}
else{
System.out.println("b is greater");
}
}
}
Output:
a is greater
Example for else if condition:
public class IfCondTest {
public static void main(String args[]) {
int a=10,b=20;
if(a>b) {
System.out.println("a is greater");
}
else if(b>a) {
System.out.println("b is greater");
}
else{
System.out.println("a and b are equal");
}
}
}
Output:
b is greater
Nested If condition (if condition inside if condition block):
public class IfCondition {
public static void main(String args[]) {
int a=10,b=20;
if(a<b) {
System.out.println("a is lessthen b");
if(b>a) {
System.out.println("b is greater");
}
}
else{
System.out.println("a and b are equal");
}
}
}
Output:
a is lessthen b
b is greater
Multiple conditions inside if:
if(a<b&&b>c) in this case both conditions should be true,
if(a<b||b>c) in this case at least one condition should be true,
public class IfCondition {
public static void main(String args[]) {
int a=10,b=20,c=30;
if(a<b&&b>c) {
System.out.println("a is lessthen b");
}
else{
System.out.println("a greaterthen b");
}
}
}
Output:
a greaterthen b