### Finding The Output

Question 6 :

What will be the output of the program?

``````class Test
{
public static void main(String [] args)
{
int x=20;
String sup = (x < 15) ? "small" : (x < 22)? "tiny" : "huge";
System.out.println(sup);
}
}``````

A). small
B). tiny
C). huge
D). Compilation fails
Answer : Option B

Explanation :

This is an example of a nested ternary operator. The second evaluation (x < 22) is true, so the "tiny" value is assigned to sup.

Question 7 :

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);
}
}``````

A). 5 2
B). 5 3
C). 6 3
D). 6 4
Answer : Option C

Explanation :

In the first two iterations x is incremented once and y is not because of the short circuit && operator. In the third and forth iterations x and y are each incremented, and in the fifth iteration x is doubly incremented and y is incremented.

Question 8 :

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);
}
}``````

A). 5 3
B). 8 2
C). 8 3
D). 8 5
Answer : Option B

Explanation :

The first two iterations of the for loop both x and y are incremented. On the third iteration x is incremented, and for the first time becomes greater than 2. The short circuit or operator || keeps y from ever being incremented again and x is incremented twice on each of the last three iterations.

Question 9 :

What will be the output of the program?

``````class Bitwise
{
public static void main(String [] args)
{
int x = 11 & 9;
int y = x ^ 3;
System.out.println( y | 12 );
}
}``````

A). 0
B). 7
C). 8
D). 14
Answer : Option D

Explanation :

The & operator produces a 1 bit when both bits are 1. The result of the & operation is 9. The ^ operator produces a 1 bit when exactly one bit is 1; the result of this operation is 10. The | operator produces a 1 bit when at least one bit is 1; the result of this operation is 14.

Question 10 :

What will be the output of the program?

``````class SSBool
{
public static void main(String [] args)
{
boolean b1 = true;
boolean b2 = false;
boolean b3 = true;
if ( b1 & b2 | b2 & b3 | b2 ) /* Line 8 */
System.out.print("ok ");
if ( b1 & b2 | b2 & b3 | b2 | b1 ) /*Line 10*/
System.out.println("dokey");
}
}``````

A). ok
B). dokey
C). ok dokey
D). No output is produced
E). Compilation error
Answer : Option B

Explanation :

The & operator has a higher precedence than the | operator so that on line 8 b1 and b2 are evaluated together as are b2 & b3. The final b1 in line 10 is what causes that if test to be true. Hence it prints "dokey".