Java If Else Statement
Java If-else Statement
The Java if statement is used to test the condition. It returns true or false. There are various types of if statement in java.
- if statement
- if-else statement
- nested if statement
- if-else-if ladder
Java IF Statement
The if statement tests the condition. It executes the if statement if condition is true.
Syntax:
- if(condition){
- //code to be executed
- }
- public class IfExample {
- public static void main(String[] args) {
- int age=20;
- if(age>18){
- System.out.print("Age is greater than 18");
- }
- }
- }
- Output : Age is greater than 18
Java IF-else Statement
The if-else statement also tests the condition. It executes the if block if condition is true otherwise else block.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false }
Example :
- public class IfElseExample {
- public static void main(String[] args) {
- int number=13;
- if(number%2==0){
- System.out.println("even number");
- }else{
- System.out.println("odd number");
- }
- }
- }
- Output : odd number
Java IF-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
- if(condition1){
- //code to be executed if condition1 is true
- }else if(condition2){
- //code to be executed if condition2 is true
- }
- else if(condition3){
- //code to be executed if condition3 is true
- }
- ...
- else{
- //code to be executed if all the conditions are false
- }
- Example :
- public class IfElseIfExample {
- public static void main(String[] args) {
- int marks=65;
- if(marks<50){
- System.out.println("fail");
- }
- else if(marks>=50 && marks<60){
- System.out.println("D grade");
- }
- else if(marks>=60 && marks<70){
- System.out.println("C grade");
- }
- else if(marks>=70 && marks<80){
- System.out.println("B grade");
- }
- else if(marks>=80 && marks<90){
- System.out.println("A grade");
- }else if(marks>=90 && marks<100){
- System.out.println("A+ grade");
- }else{
- System.out.println("Invalid!");
- }
- }
- }
- Output : C grade
All Categories
Travel
850
Legal
149
Food & Drink
451
Arts & Crafts
361
Health & Medical
2882
Gaming
246
Kids & Teens
20
Technology
635
Communications
153
Business
4847
Others
673
Real Estate
470
Womens Interests
110
Internet & eBusiness
3776
Home & Family
880
Music
35
Computers
352
Society & News
1412