Java Programming - Java.lang Class - Discussion

10. 

What will be the output of the program?

int i = 1, j = 10; 
do 
{
    if(i++ > --j) /* Line 4 */
    {
        continue; 
    } 
} while (i < 5); 
System.out.println("i = " + i + "and j = " + j); /* Line 9 */

[A]. i = 6 and j = 5
[B]. i = 5 and j = 5
[C]. i = 6 and j = 6
[D]. i = 5 and j = 6

Answer: Option D

Explanation:

This question is not testing your knowledge of the continue statement. It is testing your knowledge of the order of evaluation of operands. Basically the prefix and postfix unary operators have a higher order of evaluation than the relational operators. So on line 4 the variable i is incremented and the variable j is decremented before the greater than comparison is made. As the loop executes the comparison on line 4 will be:

if(i > j)

if(2 > 9)

if(3 > 8)

if(4 > 7)

if(5 > 6) at this point i is not less than 5, therefore the loop terminates and line 9 outputs the values of i and j as 5 and 6 respectively.

The continue statement never gets to execute because i never reaches a value that is greater than j.


Shijo said: (Jun 24, 2011)  
Wont i be 1 while entering and j 9 it would have been 2 for ++i; .

Vijayshree said: (Aug 30, 2011)  
Agreed with shijo.

Tiago said: (Jan 19, 2012)  
The correct answer is D. But the explanation is wrong.
The evaluations will be:

if
1>9
2>8
3>7
4>6

while
5<5

Jaswinder Singh said: (Oct 10, 2013)  
Yes, the explanation is wrong. Look at the following program:

class OperDemo
{
public static void main(String arr[])
{
int i = 1, j = 10;
do
{
System.out.println(i++ > --j); /* Line 9*/
System.out.println("i = " + i + "and j = " + j);
//if(i++ > --j)
//{
// continue;
//}
} while (i < 10);
}
}

In this program, the condition checking are:
1>9
2>8
3>7
4>6
5>5
6>4 true

The postfix (++ or --) operator is evaluated after the value is used or assigned.

Harshad said: (Apr 8, 2017)  
The explanation is RIGHT.

Because the prefix and postfix operators have higher precedence than relational operators.

Suri said: (May 31, 2017)  
Please Tell me the step by step explanation.

Sandy said: (Oct 1, 2017)  
No, in postfix increment or decrement the values are used first and then evaluated.

Adam Prog said: (Nov 19, 2017)  
The explanation is wrong.

Running the following code:
int i=1,j=3;
if (i++<--j)
System.out.println(i+" is less than "+j);
else
System.out.println(i+" is not less than "+j);

The output is "2 is less than 2", since i is incremented after the comparison.

If you use the prefix incremention- if (++i<--j) , then the output is: "2 is not less than 2".

Since the values of i and j are the same when the loop ends, the correct answer is the same (D).

Vikas said: (Feb 21, 2018)  
Correct Answer is D,

In line 4 i++ is post increment so the value is initialized first then increment.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.