Srikanth A Srikanth A -4 years ago 86
Java Question

Summing just primitive types

When I do the following operation, it gives me confusing results.

public static void main (String[] args){
int output = (byte) + (char) - (int) + (long) - 1;
System.out.println(output);
}



Output : 1


Do we have an explanation for this - on how JVM processes this ?

Answer Source

You aren't performing any operations, just a chain of unary operators.

int output = (byte) + (char) - (int) + (long) - 1;

First, -1 as a long. Then +-1 which is -1, then --1 (which is 1), finally +1 which is 1. Thus your output (1).

long first = -1;
int second = (int) +first;
char third = (char) -second;
byte fourth = (byte) +third;
System.out.printf("%s %s %s %s%n", String.valueOf(first), String.valueOf(second),
        String.valueOf(third), String.valueOf(fourth));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download