Chào các em. Hôm nay chủ đề của chúng ta sẽ về If Else trong lập trình Java. Trong bài viết về các loại toán tử trong lập trình bài trước phần toán tử so sánh. Dựa vào những điều kiện trên ta sẽ thực hiện những hành động khác nhau dựa trên kết quả so sánh.
Trong ngôn ngữ lập trình hướng đối tượng Java hỗ trợ ta các câu lệnh điều kiện. Mà điều kiện dựa vào các điều kiện mà ta đưa vào để thực hiện các yêu cầu của bài toán
if (condition) {
// block of code to be executed if the condition is true
}
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
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
}
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
variable = (condition) ? expressionTrue : expressionFalse;
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";