In Java programming, making decisions is essential. That’s where if-else statements come in! They help your program make choices based on certain conditions.
if-else is a control flow statement that tells your program:
“Do this if a condition is true. Otherwise, do something else.”
Syntax of if-else in Java
if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}
example :
public class Bignumber {
int a ;
int b ;
Bignumber (int a, int b){
this.a = a;
this.b = b;
}
public void findbig (){
if (a>b){
System.out.println("a is big ");
}
else{
System.out.println("b is big");
}
}
public static void main(String[] args) {
Bignumber big = new Bignumber(100,200 );
big.findbig();
}
}
output:
b is big
if-else-if is a control flow statement that allows your program to choose between multiple conditions.
It tells your program:
“Check this first. If it’s true, do it.
If not, check the next one.
If nothing is true, do the final else.”
Syntax of if-else-if in Java
if (condition1) {
// Executes if condition1 is true
} else if (condition2) {
// Executes if condition2 is true
} else {
// Executes if none are true
}
EXAMPLE:
public class Bignumber {
int a;
int b;
int c;
Bignumber(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public void findbig() {
if (a > b && a > c) {
System.out.println("a is big");
} else if (b > a && b > c) {
System.out.println("b is big");
} else if (c > a && c > b) {
System.out.println("c is big");
}
}
public static void main(String[] args) {
Bignumber big = new Bignumber(100, 200, 150);
big.findbig();
}
}
Output:
b is big
referel links :
1 : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
2 : https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.9
Top comments (1)
Hey! redeem your web3-based $50 worth of crypto in blockchain rewards ending soon! — Be part of the airdrop! Sign with wallet to verify and claim. 👉 duckybsc.xyz