Questions for: Flow Control
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 I = 0;
outer:
while (true)
{
I++;
inner:
for (int j = 0; j < 10; j++)
{
I += j;
if (j == 3)
continue inner;
break outer;
}
continue outer;
}
System.out.println(I);
The program flows as follows: I will be incremented after the while loop is entered, then I will be incremented (by zero) when the for loop is entered. The if statement evaluates to false, and the continue statement is never reached. The break statement tells the JVM to break out of the outer loop, at which point I is printed and the fragment is done.
Discuss About this Question.
int x = l, y = 6;
while (y--)
{
x++;
}
System.out.println("x = " + x +" y = " + y);
Compilation fails because the while loop demands a boolean argument for it's looping condition, but in the code, it's given an int argument.
while(true) { //insert code here }
Discuss About this Question.
public class Test
{
public static void main(String [] args)
{
int I = 1;
do while ( I < 1 )
System.out.print("I is " + I);
while ( I > 1 ) ;
}
}
There are two different looping constructs in this problem. The first is a do-while loop and the second is a while loop, nested inside the do-while. The body of the do-while is only a single statement-brackets are not needed. You are assured that the while expression will be evaluated at least once, followed by an evaluation of the do-while expression. Both expressions are false and no output is produced.
Discuss About this Question.
public class If1
{
static boolean b;
public static void main(String [] args)
{
short hand = 42;
if ( hand < 50 && !b ) /* Line 7 */
hand++;
if ( hand > 50 ); /* Line 9 */
else if ( hand > 40 )
{
hand += 7;
hand++;
}
else
--hand;
System.out.println(hand);
}
}
In Java, boolean instance variables are initialized to false, so the if test on line 7 is true and hand is incremented. Line 9 is legal syntax, a do nothing statement. The else-if is true so hand has 7 added to it and is then incremented.
Discuss About this Question.
Discuss About this Question.