Ch5 – Conditional Statements

  1. Open DrJava and expand the Interactions Pane.
  2. Declare an integer named x and assign it the value five.
> int x = 5;
  1. Type the following and note the result.
> if(x > 0) { System.out.println("x is positive"); }
x is positive
  1. Assign x a value of negative two, then hit the up arrow two times to reprint the conditional statement above. Note the result, or more accurately, lack of a result.
> x = -2;
> if(x > 0) { System.out.println("x is positive"); }
> 
  1. Type the following and note the result. As an aside, typing all on one line is not the correct way to format these statements in an actual Java program and are typed this way only to ensure the Interactions Pane interprets the statements as we intended.
> if(x % 2 == 0) { System.out.println("x is even");} else { System.out.println("x is odd"); }
x is even
  1. Change x’s value to five and hit the up arrow twice to re-enter the previous statement. Hit return and note the result now that x is odd.
> x = 5;
> if(x % 2 == 0) { System.out.println("x is even");} else { System.out.println("x is odd"); }
x is odd
  1. Retype the previous conditional statements, this time excluding the braces, and not the result is the same.
> if(x % 2 == 0) System.out.println("x is even"); else  System.out.println("x is odd"); 
x is odd
  1. As the Interactive Pane is not actual Java coding, but rather a means of evaluating statements interpretively for learning, there are some things you do in it that is not standard. For instance, note that we should have formatted the previous statement as follows in an actual Java program.
if(x % 2 == 0) 
  System.out.println("x is even"); 
else  
  System.out.println("x is odd"); 
  1. But we already know that braces group code into a block. We can use this to our advantage when evaluating statements in the Interactions Pane. Type the following and note that now it is easier to enter a multi-line statement in the Interactions Pane. Again, this is a function of using the Interactions Pane and not Java programming in general.
> { if(x % 2 == 0) 
System.out.println("x is even"); 
else  
System.out.println("x is odd");
}
x is odd

Here we used DrJava to explore conditional statements. The following video by LearningLad presents conditional statements more traditionally by illustrating them in a complete Java class.