Java if語(yǔ)句用于測(cè)試條件。它檢查布爾條件為:true或false。 java中有各種類型的if語(yǔ)句,它們分別如下:
Java語(yǔ)言中的if語(yǔ)句用于測(cè)試條件。如果條件為true,則執(zhí)行if語(yǔ)句塊。
語(yǔ)法:
if(condition){
// if 語(yǔ)句塊 => code to be executed.
}
執(zhí)行流程如下圖所示 -

public class IfExample {
public static void main(String[] args) {
int age = 20;
if (age > 18) {
System.out.print("Age is greater than 18");
}
}
}
輸出結(jié)果如下 -
Age is greater than 18
Java if-else語(yǔ)句也用于測(cè)試條件。如果if條件為真(true)它執(zhí)行if塊中的代碼,否則執(zhí)行else塊中的代碼。
語(yǔ)法:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
執(zhí)行流程如下圖所示 -

示例代碼:
public class IfElseExample {
public static void main(String[] args) {
int number = 13;
if (number % 2 == 0) {
System.out.println("這是一個(gè)偶數(shù)");
} else {
System.out.println("這是一個(gè)奇數(shù)");
}
}
}
輸出結(jié)果如下 -
這是一個(gè)奇數(shù)
Java編程中的if-else-if語(yǔ)句是從多個(gè)語(yǔ)句中執(zhí)行一個(gè)條件。
語(yǔ)法:
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
}
執(zhí)行流程如下圖所示 -

示例:
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!");
}
}
}
輸出結(jié)果如下 -
C grade