Java Programming - Operators and Assignments - Discussion

5. 

What will be the output of the program?

class Equals 
{
    public static void main(String [] args) 
    {
        int x = 100;
        double y = 100.1;
        boolean b = (x = y); /* Line 7 */
        System.out.println(b);
    }
}

[A]. true
[B]. false
[C]. Compilation fails
[D]. An exception is thrown at runtime

Answer: Option C

Explanation:

The code will not compile because in line 7, the line will work only if we use (x==y) in the line. The == operator compares values to produce a boolean, whereas the = operator assigns a value to variables.

Option A, B, and D are incorrect because the code does not get as far as compiling. If we corrected this code, the output would be false.


Manish said: (Jul 3, 2011)  
class Equals
{
public static void main(String [] args)
{
int x = 100;
double y = 100.1;
boolean b = (x == y); /* Line 7 */
System.out.println(b);
}
}
The above code is correct and will produce output : false

Anshulwall said: (Aug 14, 2011)  
class Equals
{
public static void main(String [] args)
{
int x = 100;
double y = 100.1;
boolean b = (x == y);
System.out.println(b);
}
}

on linux o/p is: 1

Can anyone explain?

Srijay said: (Jun 19, 2013)  
It will give output false. Because they are not equal and compared in doubles. So it can't give output 1.

Mika said: (Feb 11, 2014)  
The answer C is correct, but also because you cannot assign a double value to an int.

Renu said: (Jul 25, 2015)  
I think double does not take float value and only 100 takes and equalizes and so the result comes as 1.

Moni said: (Aug 2, 2016)  
Yes the answer is correct as you can't assign a double to int.

Anand said: (Jan 4, 2017)  
@Anshulwall.

I don't know what o/p will give in Linux, but in windows o/p will be false because the data type is boolean.

Vinisha said: (Jun 8, 2019)  
We can't assign double value to int.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.