Java Programming - Flow Control
- Flow Control - General Questions
- Flow Control - Finding the output
for (int i = 0; i < 4; i += 2)
{
System.out.print(i + " ");
}
System.out.println(i); /* Line 5 */
Compilation fails on the line 5 - System.out.println(i); as the variable i has only been declared within the for loop. It is not a recognised variable outside the code block of loop.
int x = 3;
int y = 1;
if (x = y) /* Line 3 */
{
System.out.println("x =" + x);
}
Line 3 uses an assignment as opposed to comparison. Because of this, the if statement receives an integer value instead of a boolean. And so the compilation fails.
Float f = new Float("12");
switch (f)
{
case 12: System.out.println("Twelve");
case 0: System.out.println("Zero");
default: System.out.println("Default");
}
The switch statement can only be supported by integers or variables more "narrow" than an integer i.e. byte, char, short. Here a Float wrapper object is used and so the compilation fails.
int i = 0;
while(1)
{
if(i == 4)
{
break;
}
++i;
}
System.out.println("i = " + i);
Compilation fails because the argument of the while loop, the condition, must be of primitive type boolean. In Java, 1 does not represent the true state of a boolean, rather it is seen as an integer.
public class Delta
{
static boolean foo(char c)
{
System.out.print(c);
return true;
}
public static void main( String[] argv )
{
int i = 0;
for (foo('A'); foo('B') && (i < 2); foo('C'))
{
i++;
foo('D');
}
}
}
'A' is only printed once at the very start as it is in the initialisation section of the for loop. The loop will only initialise that once.
'B' is printed as it is part of the test carried out in order to run the loop.
'D' is printed as it is in the loop.
'C' is printed as it is in the increment section of the loop and will 'increment' only at the end of each loop. Here ends the first loop. Again 'B' is printed as part of the loop test.
'D' is printed as it is in the loop.
'C' is printed as it 'increments' at the end of each loop.
Again 'B' is printed as part of the loop test. At this point the test fails because the other part of the test (i < 2) is no longer true. i has been increased in value by 1 for each loop with the line: i++;
This results in a printout of ABDCBDCB