What will be the result of compilation and execution of the following code?

public class Test {
    public static void main(String[] args) {
        Double d = 1.56D;
        Long l = 257L;
        byte b = 10;
        System.out.println(d.longValue() + l.byteValue() + b % 2);
    }
}
Explanation
Conversion of a floating-point number to an integer type is done using IEEE 754 round-toward-zero mode, i.e. just removing fraction.
Convertion of long to byte simply discards all but the 8 lowest order bits. 257L is 0 ... 01 0000 0001 (64 bits) After conversion only 8 bits left: 0000 0001, that equals to 1.
Then b % 2 = 0
And the result will be 1 + 1 + 0 = 2
( More on type conversions: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3 )

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes