Java Conditions and If Statements
Java supports the usual logical conditions from mathematics:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to a == b
- Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
- Use
if
to specify a block of code to be executed, if a specified condition is true - Use
else
to specify a block of code to be executed, if the same condition is false - Use
else if
to specify a new condition to test, if the first condition is false - Use
switch
to specify many alternative blocks of code to be executed
1)The if Statement
Use the if
statement to specify a block of Java code to be executed if a condition is true
.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is true
, print some text:
Example
public class MyClass
{
public static void main(String[] args)
{
int x = 20;
int y = 18;
if (x > y)
{
System.out.println(“x is greater than y”);
}
}
}
2)The else Statement
Use the else
statement to specify a block of code to be executed if the condition is false
.
Example
public class Conditional
{
public static void main(String[] args)
{
int x = 20;
int y = 18;
if (x > y)
{
System.out.println(“x is greater than y”);
}
else
{
System.out.println(“y is greater then x”);
}
}
}
3)The else if Statement
Use the else if
statement to specify a new condition if the first condition is false
.
Example
public class Conditional
{
public static void main(String[] args)
{
int x = 20;
int y = 18;
if (x > y)
{
System.out.println(“x is greater than y”);
}
else if(y > x)
{
System.out.println(“y is greater then x”);
}
else
{
System.out.println(“x is equal y”);
}
}
}
No comments:
Post a Comment