Skip Top Navigation Bar

If Statements and Ternary Conditional Operators

Practice 1: Even or Odd

Determine whether int value is even or odd and print these terms to the screen.

  1. Write an if statement on a piece of paper or white board.
  2. Write a ternary conditional expression on a piece of paper or white board.
  3. One at a time, put both program code segments you wrote into the Java Playground, embedded below, to see the results.
  4. If possible, make necessary changes so that the results of your program code segment is the same regardless of using an if statement or ternary conditional operator.

Practice 2: Positive, Negative, Zero

Determine whether int value is positive, negative, or zero and assign these terms to String classify.

  1. Write an if statement on a piece of paper or white board.
  2. Write a ternary conditional expression on a piece of paper or white board.
  3. One at a time, put both program code segments you wrote into the Java Playground, embedded below, to see the results.
  4. If possible, make necessary changes so that the results of your program code segment is the same regardless of using an if statement or ternary conditional operator.

Practice 3: Robot Turning

Consider a program with a Robot class. The Robot class has void methods turnRight() and turnLeft(). Given that randy is a proper declared and initialized Robot object. Turn randy to the right if the value of int direction is 1 and turn randy left otherwise.

  1. Write an if statement on a piece of paper or white board.
  2. Write a ternary conditional expression on a piece of paper or white board.
  3. One at a time, put both program code segments you wrote into the Java Playground, embedded below, to see the results.
  4. If possible, make necessary changes so that the results of your program code segment is the same regardless of using an if statement or ternary conditional operator.

Practice 4: Car Wipers

Consider a simulation of a car's windshield wipers, represented by the class CarWhipers. The automatic wipers will turn on if it is raining and will turn off if it is not raining. The CarWipers class has the following methods:

  • boolean isRaining() - returns true if it is raining and false otherwise.
  • boolean wipersOn() - turn the wipers on and returns true indicating the wipers are on
  • boolean wipersOff() - turns the wipers off and returns false indicating the wipers are off

Write program code to represent the functionality of the automatic windshield wipers.

  1. Write an if statement on a piece of paper or white board.
  2. Write a ternary conditional expression on a piece of paper or white board.
  3. One at a time, put both program code segments you wrote into the Java Playground, embedded below, to see the results.
  4. If possible, make necessary changes so that the results of your program code segment is the same regardless of using an if statement or ternary conditional operator.