Java Programming I

Course Home

Java Programming II

Course Home


Start Here

JoC Help

Bonus Videos

Quiz Reviews

Java Tutorial Trail: Learning the Java Language

CodingBat Warmups




AP Computer Science

How do I...

Related Links

If Statements

Joy of Code #5: If statements

Nothing to download - we continue with the scenario from last time.

Joy of Code #6: Random behavior

If you have previous experience with boolean expressions, you might want to skip directly to the quiz.

If statements: Introduction

If statements: Java statements

If statements: Conditions

Java Operators

Comparison Operators

Boolean expressions can be written using comparison operators. Comparison operators are operators that compare two values. Java has a number of these:

  • less than <
  • greater than >
  • equal ==
  • not equal !=
  • less than or equal <=
  • greater than or equal >=

For example,

2 != 3

is true, and

7 <= 4

is false.

Methods with int return types

Methods with int return type can be used with comparison operators to create boolean expressions. For example,

Greenfoot.getRandomNumber(100) < 10

is true if the number returned by Greenfoot.getRandomNumber(100) is less than 10, or false if the number returned is greater than or equal to 10.

The method getX() also has a return type of int. In the trick-the-turtle scenario, it returns the int value of the turtle's x coordinate. So the expression

getX() >= 100

returns true if the x coordinate of the turtle is greater than or equal to 100, or false if the x coordinate is less than 100.

Methods with boolean return types

Methods with boolean return type can be used as conditions all by themselves. For example, in the trick-the-turtle scenario,


is true if the turtle is at the edge of the world, or false if it's not.

After you've learned the quizlets,

take this quiz.

Boolean Operators

To be successful with the CodingBat logic problems, you should be clear about the use of boolean operators. If you're already comfortable with boolean operators, you might want to go

directly to CodingBat.

Boolean operators take two boolean values and produce another boolean value. Compare the arithmetic operators * and + with the boolean operators && and ||.

Arithmetic operators * and +
p q p * q p + q
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 2
Boolean operators && and ||
p q p && q p || q
false false false false
false true false true
true false false true
true true true true

There's also a unary operator ! that produces the opposite of a given boolean value. In other words, !true is false and !false is true.

Logic Problems on CodingBat

You can find further discussion on the

CodingBat site.

After watching the video and reading text of

Java If Boolean Example Solution Code 1, complete sumDouble, sleepIn, and monkeyTrouble.

Next, work on

CodingBat/Java/Logic-1 or CodingBat/Java/Logic-2