Conditional Statements in Java
Conditional Statements in Java
Output
Inside If block
10 is less than 15
I am Not in if
2. Java if-else Statement
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won't. But what if we
want to do something else if the condition is false? Here, comes the "else"
statement. We can use the else statement with the if statement to execute
a block of code when the condition is false.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
Example
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i < 15) {
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println(
"i is smaller than 12 too");
}
else {
System.out.println("i is greater than 15");
}}}
Output
i is smaller than 15
i is smaller than 12 too
class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
Output
1 3 5 7 9
Return Statement
The return statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller of
the method.
Example: The below Java program demonstrates how the return
statements stop a method and skips the rest of the code.
// Java program to demonstrate the use of return
import java.util.*;
if (t)
return;