What will be the result of the following code execution?

public class Test {
    public static void main(String args[]) {
        byte a = 1;
        byte b = ++a;
        byte c = -a;
        System.out.print(a);
        System.out.print(b);
        System.out.print(c);
    }
}
Explanation

Compilation error will occur in the following line

byte c = -a;

since the result of the "-a" expression is of type int, despite the fact that the operand is byte. This is necessary to prevent possible loss of accuracy. For example, when a = -128 the received value exceeds a byte range.

It doesn't happen during an increment / decrement operations execution because, for example, for a = 127 the value of the ++a expression will be equal to -128.

So minus in front of a variable implicitly converts it to an int?

2023 Feb 19, 11:23:29 AM

Follow CodeGalaxy

Mobile Beta

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