Skip Top Navigation Bar

Equivalent If Statements

Sometimes there are many different ways to write boolean expression to get the result that you want. If you attempt to write a solution and it doesn't look exactly the way we present it in these tutorials, that doesn't mean that you are wrong necessarily. This is also true if you are working with another programmer. In this section, we will look at how to write statements that all do the same thing in a variety of ways.

Your Turn

Let's try it in the Java Playground.

Alternate Solution

Not Equivalent Solution

Testing Your Code

As you can see, this last solution looks good on the surface but does not function the same way in the case of gradeLevel having an initial value of 11. Writing out the expected behavior of your program code before you start can be helpful when you test and debug your code later. For the code provided, here are some test cases that would help us identify whether the program code is function as we expect it to or not. Take a few minutes to run each test case on the original code, alternate solution, and the not equivalent alternate solution to see which case causes the not equivalent solution to fail.

Test Case Expected Result Description
  • gradeLevel = 9
  • passed = true
prints: 10 The value of gradeLevel will be increased to 10 and Congratulations! is not printed.
  • gradeLevel = 12
  • passed = true
prints: Congratulations! 12 The value of gradeLevel will stay 12 and Congratulations! will be printed.
  • gradeLevel = 11
  • passed = true
prints: 11 The value of gradeLevel will be increased to 12 and Congratulations! is not printed.
  • gradeLevel = 9
  • passed = false
prints: 10 The value of gradeLevel will stay the same and Congratulations! is not printed.
  • gradeLevel = 12
  • passed = false
prints: 12 The value of gradeLevel will stay the same and Congratulations! is not printed.
  • gradeLevel = 11
  • passed = false
prints: 11 The value of gradeLevel will stay the same and Congratulations! is not printed.

Resources

Next Learn Tutorial