0

I came across this code

public class Main {
    static int someint;

    public static void main(String[] args) {
        someint = -0;
        print();
    }

    private static int print()
    {
        System.out.println(someint);
        return someint;
    }

}

This prints -0 when i run it

I was just curios as to how -0 is a legal integer value

4

4 回答 4

6

Because "-" is a monadic negate operator and works on all numbers including 0 even though it does not affect 0 at all.

See BNF rules for Java:

numeric_expression  = 
 (  (  "-" 
 /  "++" 
 /  "--"  ) 
expression ) ...

Interestingly -0.0 is not the same number as 0.0.

于 2013-05-16T14:30:43.230 回答
5

The JLS #15.15.4 explicitly says that:

For integer values, negation is the same as subtraction from zero.

so int i = -0; is equivalent to int i = 0 - 0; which is equivalent to int i = 0;.

Note that it is not the case for floating-point values:

For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0.

So your code MUST print 0 to be compliant with the language.

于 2013-05-16T14:40:56.877 回答
0

minus 0 is lust like 0, and the compiler assume someint = 0

于 2013-05-16T14:30:04.370 回答
0

Probably you mean something like this:

private int someint;

private int print()
{
    someint = -0;
    System.out.println(someint);
    return someint;
}

Why this should not be compiled? Unary operation - is valid for all numeric constants. For value 0 it doesn't change its sign.

What about your output - it isn't reproducable under last version of JVM (Java 1.7_17). It prints out just 0.

于 2013-05-16T14:30:50.100 回答