JAVA IF … ELSE
DCIT 22 - COMPUTER PROGRAMMING 1
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.
Java Conditions and If Statements
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
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is
true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error
The if Statement
Example
if (20 > 18) {
System.out.println(“20 is greater than 18”);
}
The if Statement
Example
int x = 20;
int y = 18;
if (x > y) {
System.out.println(“x is greater than y”);
}
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y
(using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18,
we print to the screen that "x is greater than y".
The else Statement
Use the else statement to specify a block of code to be executed if the condition is
false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
The else Statement
Example
int time = 20;
if (time < 18) {
System.out.println(“Good day.”);
} else {
System.out.println(“Good evening.”);
}
// Outputs “Good evening.”
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this,
we move on to the else condition and print to the screen “Good evening”. If the time was
less than 18, the program would print “Good day”
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if the condition1 is true
} else if (condition2){
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
The else if Statement
Example
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.”);
}
// Outputs “Good evening.”
Example explained
In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else
if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false –
and print to the screen “Good evening”.
Short Hand If…Else
There is also a short-hand if else, which is 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 most often used to
replace simple if else statements:
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Short Hand If…Else
Instead of writing:
Example
int time = 20;
if (time < 18) {
System.out.println(“Good day.”);
} else {
System.out.println(“Good evening.”);
}
We can simply write
int time = 20;
String result = (time < 18) ? “Good day.” : “Good evening.”;
System.out.println(result);
Java Switch Statements
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Java Switch Statements
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of
each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, and will
described later in this chapter
Java Switch Statements
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
System.out.println(“Monday”);
break;
case 2:
System.out.println(“Tuesday”);
break;
case 3:
System.out.println(“Wednesday”);
break;
Java Switch Statements
case 4:
System.out.println(“Monday”);
break;
case 5:
System.out.println(“Tuesday”);
break;
case 6:
System.out.println(“Wednesday”);
break;
case 7:
System.out.println(“Wednesday”);
break;
}
// Outputs “Thursday” (day 4)
Java Switch Statements
The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
Java Switch Statements
The default Keyword
The default keyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
System.out.println(“Saturday”);
break;
case 7:
System.out.println(“Sunday”);
break;
default:
System.out.println(“Looking forward to the Weekend”);
}
// Outputs “Looking forward to the Weekend”
Note that if the default statement is used as the last statement in a switch block, it does not need a break.
Java User
Input
Java User Input
The Scanner class is used to get user input, and it is
found in the java.util package.
To use the Scanner class, create an object of the class and
use any of the available methods found in the Scanner
class documentation. In our example, we will use the
nextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String [] args){
Java User Scanner myObj = new Scanner(System.in); // Create a Scanner object
Input System.out.println(“Enter username”);
String username = myObj.nextLine(); // Read user input
System.out.println(“Username is: ” + userName); // Output user input
}
}
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:
Method Description
nextBoolean() Reads a Boolean value from the user
Java User nextByte() Reads a byte value from the user
Input
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner;
class Main {
public static void main(String [] args){
Scanner myObj = new Scanner(System.in);
Java User System.out.println(“Enter name, age and salary”);
Input
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj. nextDouble();
// Output input by user
System.out.println(“Name: ” + name);
System.out.println(“Age: ” + age);
System.out.println(“Salary: ” + salary);
}
}