Chapter 2 - Java for Beginners Course

Conditional Operators

When working with boolean expressions, conditional operators allow you to mix them to create more complex conditions, like checking if two expressions are true or if at least one of the two expressions is true.

The first two conditional operators we’ll introduce work on two operands that need to be boolean values/variables/expressions and both are short-circuit operators, which means that the right operand will only be evaluated if necessary.

For the examples in this section, let’s assume we’ll be checking an age and a height values to validate if certain conditions hold true or not:

int age = 18;
int heightInCm = 170;

// check if the age is 18 or over
boolean ageCheck = (age >= 18);

// check if the height is over 160cm
boolean heightCheck = (heightInCm > 160);

In the example above, assume that you need to make a decision based on both the age and the height, for example checking if someone can ride a roller coaster in an amusement park. In such case, you can use the conditional operators.

Conditional AND

The conditional AND operator is represented by a double ampersand (&&) and can be used to check if the value of both operands is true or not. It displays the following behaviour:

Left Operand Right Operand Result

true

true

true

true

false

false

false

ignored

false

Note that if the left operand is false, the right operand will not be evaluated (short circuit); it doesn’t matter if its value is true or false, the result will be false.

For example:

int age = 18;
int heightInCm = 170;

// check if the age is 18 or over
boolean ageCheck = (age >= 18);

// check if the height is over 160cm
boolean heightCheck = (heightInCm > 160);

// check if someone is 18 or over AND their height is over 160cm
boolean check1 = (ageCheck && heightCheck);
System.out.println("a) 18 or over AND over 160cm? " + check1);

// alternatively, we could write the check in a single line (parenthesis used for clarity)
// for example:
// check if someone is 20 or over AND their height is over 160cm
boolean check2 = (age >= 20) && (heightInCm > 160);
System.out.println("b) 20 or over AND over 160cm? " + check2);

Output:

a) 18 or over AND over 160cm? true
b) 20 or over AND over 160cm? false

In this example, check1 is true because both operands ageCheck and heightCheck are both true.

However, in the case of check2, its value is false because the first operand (age >= 20) is false. Java won’t check the second operand as it will short-circuit (it already knows that one of the operands is NOT true).

"Short circuiting" is an important feature to bear in mind, specially when the short-circuited expression has method invocations in the mix, those methods won’t be invoked if the short-circuit occurs.

Conditional OR

The conditional OR operator is represented by a double pipe (||) and can be used to check if the value of at least one of the operands is true. It displays the following behaviour:

Left Operand Right Operand Result

true

ignored

true

false

true

true

false

false

false

Note that if the left operand is true, the right operand will not be evaluated (short circuit); it doesn’t matter if its value is true or false, the result will be true.

For example:

int age = 18;
int heightInCm = 170;

// check if someone is 18 or over or 190 or over in height
boolean check3 = (age >= 18) || (heightInCm >= 190);
System.out.println("c) 18 or over OR 190cm or over? " + check3);

// check if someone is 20 or over or 190 or over in height
boolean check4 = (age >= 20) || (heightInCm >= 190);
System.out.println("d) 20 or over OR 190cm or over? " + check4);

Output:

c) 18 or over OR 190cm or over? true
d) 20 or over OR 190cm or over? false

In this example, check3 is true as the left operand (age >= 18) is true. Java won’t check the second operand as it will short-circuit (it already knows that at least one of the operands is true).

In the case of check4 Java will check both operands (age >= 20) and (heightInCm >= 190) and because both are false, then the value of check4 is also false.

Ternary Operator

In contrast to the other two conditional operators, the ternary operator (?:) makes use of three operands as its name suggests and its return type doesn’t need to be a boolean, it depends on the type of the second and third operands provided.

The form of the ternary operator is: (booleanExpression ? resultIfTrue : resultIfFalse), for example:

int age = 18;

// give discount of 50% if the age is less than 18
double discount = (age < 18) ? 0.5d : 0.0d;
System.out.println("e) discount: " + discount);

Output:

e) discount: 0.0

In this example, the ternary operator (age < 18) ? 0.5d : 0.0d is checking if the age is below 18. If so, it will return the double value of 0.5, otherwise, a value of 0. The resulting value is assigned to the discount variable.

If we dissect the ternary operator in the example, the three operands are:

  1. The boolean expression being evaluated: (age < 18)

  2. The result if the boolean expression is true: 0.5d

  3. The result if the boolean expression is false: 0.0d

In our case, because the age is not below 18, then the 0.0d value is assigned to the discount variable.

Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations