Java Conditional Statement
Java Conditional Statement
Connect4techs
Conditional Statement
if Statement
switch Statement
➔ Java-if Statement :
The java if-Statement is used to test the condition.It check boolean condition:
true or false.
If statement
If-else statement
If-else-if ladder
Nested if statement
Java Programming
1. Java if Statement
if (condition) {
// statements
}
Working of if Statement
Output
In the program, number < 0 is false . Hence, the code inside the body of
does nothing.
In this case, we can use an optional else block. Statements inside the body
of else block are executed if the test expression is evaluated to false . This is
if (condition) {
// codes in if block
}
Java Programming
else {
// codes in else block
}
Here, the program will do one task (codes inside if block) if the condition
is true and another task (codes inside else block) if the condition is false .
}
}
Output
In the above example, we have a variable named number. Here, the test
Since the value of the number is 10 , the test expression evaluates to true .
Now, change the value of the number to a negative integer. Let's say -5 .
If we run the program with the new value of number, the output will be:
if (condition1) {
// codes
}
else if(condition2) {
// codes
}
else if (condition3) {
// codes
}
.
.
else {
// codes
}
Here, if statements are executed from the top towards the bottom. When the
test condition is true , codes inside the body of that if block is executed. And,
If all test expressions are false , codes inside the body of else are executed.
class Main {
public static void main(String[] args) {
int number = 0;
The number is 0.
class Main {
public static void main(String[] args) {
// if...else statement inside the if block // checks if n1 is greater than or equal to n3 if (n1 >= n3) {
largest = n1;
}
else {
largest = n3;
}
} else {
else {
largest = n3;
}
}
Output:
➔ Switch Statement :
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
Java Programming
class Main {
public static void main(String[] args) {
default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
Java Programming
Output:
Size: Large
In the above example, we have used the switch statement to find the size.
Here, we have a variable number. The variable is compared with the value of
Since the value matches with 44, the code of case 44 is executed.