Java If ...
< /
/ Else >
Presented by
Jarren Louie Garcia
Arvin Lester Diaz
1011 011 01 1011001 10 11011 011 01 110110 110111 1101
</Java Conditions and If
Statements
You already know that 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.
1011 011 01 1011001 10 11011 011 01 110110 110111 1101
</Java Conditions and If
Statements Use if to specify a block of code to be
if executed, if a specified condition is
true
Use else to specify a block of code to
Java has the else be executed, if the same condition is
following false
conditional
Use else if to specify a new
statements: else if condition to test, if the first condition
is false
Use switch to specify many
alternative blocks of code to be
switch executed
</If Use if to specify a block of code to be executed, if a specified condition is true.
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Example
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:
public class Main {
public static void main(String[] args) {
if (20 > 18) {
System.out.println("20 is greater than 18"); // obviously
}
}
}
We can also test variables:
public class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than
y");
}
}
}
Use else to specify a block of code to be executed, if the same
</Else condition is false.
Example
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.“);
} else {
System.out.println( "Good evening.“ );
}
}
}
</Else IfUse else if to specify a new condition to test, if the first
condition is false.
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.“);
} else if (time < 18) {
System.out.println("Good day.“);
} else {
System.out.println("Good evening.“);
}
}
}
There is also a short-hand if else, which is
</Short Hand If…Else known as the ternary operator because it
consists of three operands.
It can be used to replace multiple lines of code with a single line, and is most often used to
replace simple if else statements:
Example: Instead of writing
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.“);
} else {
System.out.println( "Good evening.“ );
}
}
}
You can simply write:
public class Main {
public static void main(String[]
args) {
int time = 20;
String result;
result = (time < 18) ? "Good
day." : “Good evening.”;
System.out.println(result);
}
}
JAVA SWITCH IS NOT
INCLUDED IN OUR REPORT.
THANK YOU
THE END