Skip to Content
Think Java
book

Think Java

by Allen B. Downey, Chris Mayfield
May 2016
Beginner content levelBeginner
249 pages
5h 13m
English
O'Reilly Media, Inc.
Content preview from Think Java

Chapter 5. Conditionals and Logic

The programs we’ve seen in previous chapters do pretty much the same thing every time, regardless of the input. For more complex computations, programs usually react to the inputs, check for certain conditions, and generate appropriate results. This chapter presents the features you need for programs to make decisions: a new data type called boolean, operators for expressing logic, and if statements.

Relational Operators

Relational operators are used to check conditions like whether two values are equal, or whether one is greater than the other. The following expressions show how they are used:

x == y          // x is equal to y
x != y          // x is not equal to y
x > y           // x is greater than y
x < y           // x is less than y
x >= y          // x is greater than or equal to y
x <= y          // x is less than or equal to y

The result of a relational operator is one of two special values, true or false. These values belong to the data type boolean; in fact, they are the only boolean values.

You are probably familiar with these operations, but notice that the Java operators are different from the mathematical symbols like , , and . A common error is to use a single = instead of a double ==. Remember that = is the assignment operator, and == is a comparison operator. Also, there is no such thing as the =< or => operators.

The two sides of a relational operator have to be compatible. For example, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn Java the Easy Way

Learn Java the Easy Way

Bryson Payne
Optimizing Java

Optimizing Java

Benjamin J. Evans, James Gough, Chris Newland

Publisher Resources

ISBN: 9781491929551Errata Page