01.Java if
01.Java if
else Statement
In this tutorial, you will learn about control flow statements using Java if and
if...else statements with the help of examples.
if (condition) {
// statements
}
Output
In the program, number < 0 is false . Hence, the code inside the parenthesis
is skipped.
Note: If you want to learn more about about test conditions, visit Java
Relational Operators and Java Logical Operators.
// if statement
if (language == "Java") {
System.out.println("Best Programming Language");
}
}
}
Run Code
Output
if (condition) {
// codes in if block
}
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
expression number > 0 checks if number is greater than 0.
Since the value of the number is 10 , the test expression evaluates to true . Hence
code inside the body of if is executed.
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:
Here, the value of number is -5 . So the test expression evaluates to false . Hence
code inside the body of else is executed.
3. Java if...else...if Statement
In Java, we have an if...else...if ladder, that can be used to execute one block of
code among multiple other blocks.
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,
program control jumps outside the if...else...if ladder.
If all test expressions are false , codes inside the body of else are executed.
int number = 0;
The number is 0.
else {
largest = n3;
}
} else {
else {
largest = n3;
}
}
Output:
However, in real-world applications, these values may come from user input
data, log files, form submission, etc.