Java Programming - Flow Control - Discussion

Discussion :: Flow Control - Finding the output (Q.No.12)


What will be the output of the program?

int x = 3; 
int y = 1; 
if (x = y) /* Line 3 */
    System.out.println("x =" + x); 

[A]. x = 1
[B]. x = 3
[C]. Compilation fails.
[D]. The code runs with no output.

Answer: Option C


Line 3 uses an assignment as opposed to comparison. Because of this, the if statement receives an integer value instead of a boolean. And so the compilation fails.

Balasaheb said: (Jun 7, 2012)  
== are use to compare to int
.equal are use to compare objects

Chitrangad said: (Nov 13, 2012)  
Here should be use comparisation operator. We can't assign the value within the if () statement.

Aniruddh said: (Dec 18, 2012)  
In C with IF statement, we can perform this assignment operation. Will this rule not work in java ?

Tinny said: (Aug 18, 2016)  
Answer is D because the code runs with no output.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.