2k views

What is the output of the following 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.printIn (x+ "" + y);
}
}
1. 8 2
2. 8 5
3. 8 3
4. 5 3
in Java | 2k views
0

In a lot of programming languages (including C) in case there are two arguments (or operations), and the first one's result is sufficient to get the overall result; other argument is not processed.

This is called Short Circuit Evaluation, and it can be extended to any number of arguments.

Here,

            if((++x >2)||(++y  > 2))


If the first operation is True, the second operation won't be evaluated.

Before solving the questions, if we think why they asked this particular question then probability of getting correct answer increased. For example this question is an example of Short-Circuit Evaluation

Here is the Answer:

$z = 0$  : $x = 1$ and $y = 1$, Because $x++;$ will not be executed because condition is false

$z = 1$  : $x = 2$ and $y = 2$, Because $x++;$ will not be executed because condition is false

$z = 2$  : $x = 4$ and $y = 2$, Here $x++;$ will be executed, but $++y$ will not be executed due to short circuit evaluation

$z = 3$  : $x = 6$ and $y = 2$, Here $x++;$ will be executed, but $++y$ will not be executed due to short circuit evaluation

$z = 4$  : $x = 8$ and $y = 2$, Here $x++;$ will be executed, but $++y$ will not be executed due to short circuit evaluation

Hence at the end, It will print 8 2.

by Boss (35.7k points)
selected by
0
@arjun sir and @srestha please verify this.
0
how x value sudden increase from 2 to 4 ?
0

Because of pre-increment operator (++x ) Note: Value will be incremented before evaluation.

while z=2, x will be incremented by 1 in the if statement (++x >2) . Now, x value became 3. Then, again it will be incremented by 1 in inside of the if statement X++; so that x value suddenly incremented x=2 to x=4.

1
2
+1 vote
3