Reputation: 1605
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
Upvotes: 0
Views: 143
Reputation: 328608
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.
Upvotes: 5
Reputation: 34900
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
.
Upvotes: 0
Reputation: 65811
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
.
Upvotes: 6