When we want render or execute something based on certain condition we use if statement or if conditional block in java. It is like filtering some statements.
Like many websites have age limit to access their contents. In this case we can use java conditional statements. Another scenario is you can only eligible to vote if you are at least 18 years old.
Java If statement syntax:
if(condition to check){
//code block to execute
//if the condition is true
}
Let's propagate a simple example that checks the int age variable and print some statements if the condition is true.
public class Main{
public static void main (String[] args){
//create an int variable age
int age = 20;
if(age>=18 ){
System.out.println("You are eligible to vote");
}
}
}
/**
* Output:
* You are eligible to vote
*/
Now make the age to 16 and again run the Main.java file.
public class Main{
public static void main (String[] args){
//create an int variable age
int age = 16;
if(age>=18 ){
System.out.println("You are eligible to vote");
}
}
}
/**
* Output:
*
*/
In the console you see nothing. Because if statement or the if condition is false. The compiler checks the condition first, and if the condition is true it executes the if block otherwise it doesn't.
Imagine, though the if block is false but we want to print something to the console. So, how to achieve it?
In this case we can use java else block.
Java if-else syntax:
if(condition to check){ //if block
//code block to execute
//if the condition is true
}
else{ //else block
//code to execute if the if block
//is false
}
Let's propagate another example: it's the modification of the Example-1.
public class Main{
public static void main (String[] args){
//create an int variable age
int age = 16;
if(age>=18 ){
System.out.println("You are eligible to vote");
}
else{
System.out.println("You are not eligible to vote");
}
}
}
/**
* Output:
* You are not eligible to vote.
*/
Explanation: The compiler first checks the if condition and finds age must be 18 or above but age is 16 here (input will be taken from the user in real life application) so, it doesn't the execute the if block. Thus it executes the else block.
Note: else block always executes if the condition is false in the if block. Another thing, inside the main method of the application, in our case Main.java file all the members are static by default. So we don't need to use static keyword to make them static.