Control Flow
Java control flow statements including loops, conditional statements, and switch statements
Questions
What will be the output of the program?
int x = l, y = 6;
while (y--)
{
x++;
}
System.out.println(x = + x + y = + y);
- x = 6 y = 0
- x = 7 y = 0
- x = 6 y = -1
- compilation fails
public void test(int x)
{
int odd = 1;
if(odd) /* Line 4 */
{
System.out.println(odd);
}
else
{
System.out.println(even);
}
}
Which statement is true?
- compilation fails.
- odd will always be output.
- even will always be output.
- odd will be output for odd values of x, and even for even values.
What will be the output of the program?
int i = 0, j = 5;
tp: for (;;)
{
i++;
for (;;)
{
if(i > --j)
{
break tp;
}
}
System.out.println(i = + i + , j = + j);
- i = 1, j = 0
- i = 1, j = 4
- i = 3, j = 4
- Compilation fails
What will be the output of the program?
for (int i = 0; i < 4; i += 2)
{
System.out.print(i + );
}
System.out.println(i); /* Line 5 */
- 0 2 4
- 0 2 4 5
- 0 1 2 3 4
- compilation fails
What will be the output of the program?
int x = 3;
int y = 1;
if (x = y) /* Line 3 */
{
System.out.println(x = + x);
}
- x = 1
- x = 3
- compilation fails
- no output
class MyClass
{
public static void main()
{
int s=2;
for(int i=0;i<=s;i++);
{
System.out.print(i);
}
}
}
- 01
- undefined loop
- Run time error
- compile time error
- 012
public class While
{
public void loop()
{
int x= 0;
while ( 1 ) /* Line 6 /
{
System.out.print("x plus one is " + (x + 1)); / Line 8 */
}
}
}
Which statement is true?
- There is a syntax error on line 1.
- There are syntax errors on lines 1 and 6.
- There are syntax errors on lines 1, 6, and 8.
- There is a syntax error on line 6.
public class Test2
{
public static int x;
public static int foo(int y)
{
return y * 2;
}
public static void main(String [] args)
{
int z = 5;
assert z > 0; /* Line 11 /
assert z > 2: foo(z); / Line 12 /
if ( z < 7 )
assert z > 4; / Line 14 */
switch (z)
{
case 4: System.out.println("4 ");
case 5: System.out.println("5 ");
default: assert z < 10;
}
if ( z < 10 )
assert z > 4: z++; /* Line 22 */
System.out.println(z);
}
}
Which line is an example of an inappropriate use of assertions?
- Line 11
- Line 12
- Line 14
- Line 22
What will be the output of the program?
int i = l, j = -1;
switch (i)
{
case 0, 1: j = 1; /* Line 4 */
case 2: j = 2;
default: j = 0;
}
System.out.println(j = + j);
- j = -1
- j = 0
- j = 1
- compilation fails
What will be the output of the program?
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);
- 1
- 2
- 3
- 4
What will be the output of the program?
class Test
{
public static void main(String [] args)
{
int x= 0;
int y= 0;
for (int z = 0; z < 5; z++)
{
if (( ++x > 2 ) && (++y > 2))
{
x++;
}
}
System.out.println(x + " " + y);
}
}
- 5 2
- 5 3
- 6 3
- 6 4