Decision Control Instruction
We all need to alter our actions in the face of changing circumstances. If the weather is fine, then I will go for a stroll. If the highway is busy, I would take a diversion. If the pitch takes spin, we would win the match. If she says no, I would look elsewhere. If you like this book, I would write the next edition. You can notice that all these decisions depend on some condition being met. Java language too must be able to perform different sets of actions depending on the circumstances. In this chapter, we will explore ways in which a Java program can react to changing circumstances.
Decisions! Decisions!
In the programs written in Chapters 2 and 3, the instructions in them got executed sequentially. However, in many programming situations, we want one set of instructions to get executed in one situation, and an entirely different set in another situation. Such situations are dealt with in Java programs using a decision control instruction. A decision control instruction can be implemented in Java using:
(a) The if-else statement
(b) The conditional operators Now let us learn each of these and their variations in turn.
The if-else Statement
Like most languages, Java uses if-else to implement the decision control instruction. The general form of if statement looks like this:
if ( this condition is true )
{
execute statement1 ;
execute statement2 ;
}
else
{
execute statement4 ;
execute statement5 ;
}
The keyword if tells the compiler that what follows is a decision controlinstruction. The condition following the keyword if is always enclosed ina pair of parentheses. If the condition is true, then the statements 1, 2 are executed. If the condition is false, then statements 4, 5 areexecuted.But how do we express the condition itself in Java? And how do weevaluate its truth or falsity? We understand the condition using java Relaction operator They allow us to compare two values to seewhether they are equal to each other, unequal, or whether one is greater than the other Hear how they look and how they are evaluated in Java.

The relational operators should be familiar to you except for the equality operator == and the inequality operator !=. Note that = is used for assignment, whereas, == is used for comparison of two quantities. Let us understand the usage of relational operators using a simple program
If his basic salary is less than Rs. 1500, then HRA = 10% of basic salaryand DA = 90% of basic salary. If his salary is either equal to or above Rs.1500, then HRA = Rs. 1500 and DA = 98% of basic salary. If theemployee’s salary is input through the keyboard write a program to findhis gross salary.
Now let us look at the program that implements this logic.
// Calculation of gross salary
package calofgrosssalary ;
import java.util.* ;
public class CalOfGrossSalary
{
public static void main ( String[ ] args )
{
float bs, gs, da, hra ;
Scanner scn ;
scn = new Scanner ( System.in ) ;
bs = scn.nextFloat( ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 1200 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
System.out.println ( “Gross salary = Rs. ” + gs ) ;
}
}
Here is some sample interaction with the program.
Enter basic salary
1200
Gross salary = Rs. 2400.0
Enter basic salary
2000
Gross salary = Rs. 4660.0
A few points worth noting…
a) The group of statements in {} after the if is called an ‘if block’. Similarly, the statements in {} after the else form the ‘else block’.
b) Notice that the else is written exactly below the if. The statements in the if block and those in the else block have been indented to the right. This formatting convention is followed throughout the book to enable you to understand the working of the program better.
(c) Had there been only one statement to be executed in the if block and only one statement in the else block we could have dropped the pair of braces.
(d) In the first run of the program, the condition evaluates to true, as 1200 (value of bs) is less than 1500. In this case the statements in the if block get executed. In the second run, the condition evaluates to false, as 2000 (value of bs) is greater than 1500. Now the statements in the else block get executed.
(e) It is perfectly all right if we write an entire if-else construct within an if block or else block. This is called ‘nesting’ of if-else statements.
(f) At times we may not wish to do anything if the condition in if fails. In such a case we should drop the else and the associated else block.
More Complex Decision Making
Sometimes the decision making becomes complex. We may wish to execute a set of statements if multiple conditions are true, or one out of multiple conditions is true. To deal with such situations Java provides Logical operators, &&, || and I. These are to be read as ‘AND’ ‘OR’ and “NOT’, respectively
The first two operators, && and ||, allow two or more conditions to be combined in an if statement. Let us see how they are used in a program. Consider the following example:
Example : The marks obtained by a student in 3 different subjects are input through the keyboard. The student gets a division as per the following rules:
Percentage above or equal to 60 – First division
Percentage between 50 and 59 – Second division
Percentage between 40 and 49 – Third division
Percentage less than 40 – Fail
Write a program to determine the division obtained by the student.
Here is the program that implements this logic.
// Determining student’s division
package studentdiv ;
import java.util.* ;
public class StudentDiv
{
public static void main ( String[ ] args )
{
int m1, m2, m3, per ;
Scanner scn ;
scn = new Scanner ( System.in ) ;
System.out.println ( “Enter marks in three subjects” ) ;
m1 = scn.nextInt( ) ;
m2 = scn.nextInt( ) ;
m3 = scn.nextInt( ) ;
per = ( m1 + m2 + m3 ) * 100 / 300 ;
if ( per >= 60 )
System.out.println ( “First division” ) ;
if ( ( per >= 50 ) && ( per < 60 ) ) System.out.println ( “Second division” ) ; if ( ( per >= 40 ) && ( per < 50 ) )
System.out.println ( “Third division” ) ;
if ( per < 40 )
System.out.println ( “Fail” ) ;
}
}
As can be seen from the second if statement, the && operator is used to combine two conditions. ‘Second division’ gets printed if both the conditions evaluate to true. If one of the conditions evaluates to false then the whole expression is treated as false.
We could have implemented the same logic without using logical operators, by using nested if-else statements. You may try doing this. If you do so you would observe that the program unnecessarily becomes lengthy.
else if
There is one more way in which we can write program for Example 4.1.This involves usage of else if blocks as shown below.
// Else if ladder demo
package elseifladderdemo;
import java.util.Scanner;
public class ElseIfLadderDemo {
public static void main(String[] args) {
int m1, m2, m3, per;
Scanner scn = new Scanner(System.in);
System.out.println("Enter marks in three subjects: ");
m1 = scn.nextInt();
m2 = scn.nextInt();
m3 = scn.nextInt();
per = (m1 + m2 + m3) * 100 / 300; // Calculate percentage
if (per >= 60) {
System.out.println("First division");
} else if (per >= 50) {
System.out.println("Second division");
} else if (per >= 40) {
System.out.println("Third division");
} else {
System.out.println("Fail");
}
scn.close(); // Closing the scanner to avoid resource leak
}
}
Explanation of else if
Ladder:
- The program uses an
else if
ladder to classify marks based on percentage. - The conditions are checked sequentially. Once a condition is met, the subsequent conditions are not evaluated.
- If none of the
if
orelse if
conditions are true, theelse
block is executed. - The code is more readable and reduces unnecessary indentation.
Improved Code for Driver Insurance Program
// Insurance of driver – using logical operators
package driverinsurance;
import java.util.Scanner;
public class DriverInsurance {
public static void main(String[] args) {
int age;
char sex, maritalStatus;
Scanner scn = new Scanner(System.in);
System.out.println("Enter age, sex (M/F), and marital status (M/U): ");
age = scn.nextInt();
sex = scn.next().charAt(0);
maritalStatus = scn.next().charAt(0);
if ((maritalStatus == 'M') ||
(maritalStatus == 'U' && sex == 'M' && age > 30) ||
(maritalStatus == 'U' && sex == 'F' && age > 25)) {
System.out.println("Driver is insured");
} else {
System.out.println("Driver is not insured");
}
scn.close(); // Closing the scanner
}
}
Simplified Explanation:
- Input: The program asks for the driver’s:
- Age
- Gender (M for Male, F for Female)
- Marital status (M for Married, U for Unmarried)
- Logic:
- The driver is insured if:
- They are married.
- They are an unmarried male older than 30.
- They are an unmarried female older than 25.
- If none of these conditions are true, the driver is not insured.
- The driver is insured if:
- Flow:
- First, it checks if the driver is married.
- If not, it checks gender and age for unmarried drivers.
- If none match, it outputs “Driver is not insured.”
Key Points:
- The logic uses
||
(OR) to combine different cases where the driver is insured. - The scanner is closed after taking input to avoid resource waste.
The &
and |
Operators vs &&
and ||
Let’s break down the differences between the & and | operators and their short-circuiting counterparts && and ||.

Explanation:
- Expected Output: At first glance, you might expect
b
to be assigned9
(sincec + 4 = 9
), and therefore the output should be9
. But it actually prints1
. - Reason: The first condition
a > 3
isfalse
, so the second condition(b = c + 4) > 1
is not evaluated at all due to short-circuiting. In short-circuiting, when the first condition of&&
isfalse
, the second condition is ignored, and this is whyb
remains1
.
Preventing Short-Circuiting:
By replacing &&
with &
, we force both conditions to be evaluated, even if the first one is false
.
int a = 1, b = 1, c = 5, d;
if (a > 3 & (b = c + 4) > 1) {
d = 35;
}
System.out.println(b); // Output: 9
Explanation:
- No Short-Circuiting: The
&
operator ensures that both conditions are always evaluated. Even thougha > 3
is stillfalse
, the second condition(b = c + 4)
is evaluated, settingb
to9
. - Final Output: Now, the value of
b
becomes9
, and that is printed.
Summary of Operators:
Operator | Short-Circuits | Meaning |
---|---|---|
&& | Yes | Logical AND, stops evaluating if the first condition is false. |
` | ` | |
& | No | Bitwise AND, always evaluates both conditions. |
` | ` | No |
When to Use:
&&
and||
: Use these when you want short-circuiting behavior to improve performance by skipping unnecessary evaluations.&
and|
: Use these when both conditions must be evaluated, regardless of whether the first one fails (e.g., assignments inside conditions).
Key Takeaway:
- The
&&
and||
operators are useful when you want to skip further evaluation if the first condition already gives a conclusive result. - The
&
and|
operators ensure that all conditions are evaluated, which can be helpful when certain actions (like assignments) must always happen.
Conditional (Ternary) Operators
The conditional operator (? :
) is often called the ternary operator because it works with three arguments. It provides a way to shorten if-else
statements into a single line.

If the condition is true
, expression1
is evaluated and returned .If the condition is false
, expression2
is evaluated and returned.

If x > 5
is true
, y
will be assigned 7
(result of 3 + 4
). If x > 5
is false
, y
will be assigned 11
(result of 4 + 7
).

- If
a
is between 65 and 90 (inclusive),y
will be assigned1
. - If not,
y
will be assigned0
.
Important Points About the Conditional Operator:
- Functions in the Conditional Expression: If a function is used in the
?
or:
part, it must return a value that can be assigned to a variable. If the function returnsvoid
, it will cause an error.- Valid Example:

This works because Math.sin()
and Math.cos()
return values that can be assigned to j
.
- Invalid Example

Using Conditional Operators Inside println()
: Conditional operators can be used directly inside System.out.println()
, as shown below:
- Valid Example:

Nesting Conditional Operators: You can nest conditional operators inside one another:

- This example checks if
a
is greater than bothb
andc
. If true,big
is assigned3
or4
based on the value ofa > c
. - If
a
is not greater thanb
, it checks ifb
is greater thanc
and assigns6
or8
.
Assignment inside Conditional Expressions: A common mistake is to try assigning values inside the ?
and :
parts without assigning the result to a variable, which results in an error.
- Invalid Example:
a > b ? g = a : g = b; // Error
This will cause an error because the result of g = a
or g = b
is not assigned to any variable.
- Correct Example:
g = a > b ? a : b;
This correctly assigns the larger value between a
and b
to g
.
Limitation of the Conditional Operator:
- After the
?
or:
part, you can only have one expression. This means you cannot execute multiple statements directly within a ternary operator. For multiple actions, you’ll need to use a regularif-else
statement.
Summary:
- Conditional operators (
? :
) are a shorter way of writingif-else
statements. - They take three arguments: a condition, a value to return if the condition is
true
, and a value to return if the condition isfalse
. - Be mindful that only one statement can follow
?
or:
, and all expressions must return a value.