Java
TOPIC 19 – WHILE LOOPS – PART 1

AP EXTRA

 

 

AP LESSON NOTE

 

 

ONE LINE STATEMENT BLOCKS

 

Just like IF statements, WHILE loops can also be written without the { and } brackets.  In such a situation, only the first line is immediately after the WHILE statement is part of the statement block.

It should be noted that this very rarely used and students are discouraged from using it.  However, it's always good to know in case you are reading somebody else's code.

 

EXAMPLE – NOT WHAT YOU THINK

 

Consider the code below:

       int x = 0;

       while(x<5)

           System.out.println("hi");

           x++;

 

 You may think that it will output "hi" five times.  However, because there are no { and } brackets around the statement block, the statement block is only one statement. Therefore, only the output statement is inside the loop.  So, this will loop forever and the bottommost statement will never actually get executed.

It should also be noted that the bottommost statement is false indented in the example above.  It should be moved left.