Java If-Else Statement
Learn Java in simple and easy steps starting from basic to advanced concepts with examples java if-else statement. The Java if statement is used to test the condition. It executes the if block if the condition is true otherwise else block, is executed. There are several types of if statement in Java:- If statement
- If-else statement
- The if...else if...else Statement
- Nested if...else Statement:
1. Java If Statement with Example:
A true statement is one that evaluates to a nonzero number. A false statement evaluates to 0. when you perform the comparison with the relational operators, the operator will go back 1 if the assessment is proper or zero if the evaluation is false.
public class my
{
public static void main(String[] args)
{
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
2. If-Else Statement with Example:
The Java if-else declaration also assessments the situation. It executes the if block if the circumstance is genuine in any other case else block, is carried out.
public class my
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
Output: odd number
3. If...Else If...Else Statement with Example:
And if assertion can be accompanied by using an optional else if...else announcement, which may be very useful to test various situations using single if...else if assertion.
whilst the use of if, else if, else statements there are some factors to hold in mind.
- An if will have zero or one else's and it should come after any else if's.
- An if may have zero to many else if's and they need to come before the else.
- Once an else if succeeds, none of the last else if's or else's will be tested.
Syntax
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
// Executes when the Boolean expression 3 is true
}
else
{
// Executes when the none of the above conditions is true.
}
}
public class my
{
public static void main(String args[])
{
int x = 30;
if( x == 10 )
{
System.out.print("Value of X is 10");
}
else if( x == 20 )
{
System.out.print("Value of X is 20");
}
else if( x == 30 )
{
System.out.print("Value of X is 30");
}
else
{
System.out.print("This is else statement");
}
}
}
Output: value of x is 30
4. Nested If Statement with Example:
It is constantly lawful to settle if-else explanations which imply you can utilize one if or there will be consequences if articulation inside another if or something bad might happen if proclamation.
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}
Output: x=30 and y=10
No comments:
Post a Comment