Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Finding the output (Q.No. 5)
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);
    }
}
true
false
Compilation fails
An exception is thrown at runtime
Answer: Option
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.

Discussion:
9 comments Page 1 of 1.

1R.Harish said:   3 years ago
Here we compare double and an integer values. They are not equal so the output false. And we can assign double value to int value by using typecasting that is;

x= (int) y; it is called narrowing.

Vinisha said:   6 years ago
We can't assign double value to int.

Anand said:   9 years ago
@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.

Moni said:   9 years ago
Yes the answer is correct as you can't assign a double to int.

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

Mika said:   1 decade ago
The answer C is correct, but also because you cannot assign a double value to an int.

Srijay said:   1 decade ago
It will give output false. Because they are not equal and compared in doubles. So it can't give output 1.

Anshulwall said:   1 decade ago
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?

Manish said:   1 decade ago
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

Post your comments here:

Your comments will be displayed after verification.