I was just studying up on my Java in preparation for an exam and I ran into a sort of problem with uninitialized int/Integer values.
class A { int x; Integer y; static int z; static Integer z2; public A(){} }
Lets say I initialize an object of Class A. A a = new A();
I've tried this in a compiler and got the results
a.x == 0; true a.x == null; Static Error: Bad type in comparison expression a.y == 0; java.lang.NullPointerException a.y == null; true a.z == 0; true a.z == null; Static Error: Bad type in comparison expression a.z2 == 0; NullPointerException a.z2 == null; true
Furthermore , I tried some more uninitialized int/Interger comparisons in an interactions pane to see if I would get different results if my x, y were not class instance variables as they are above.
int x; Integer y; x == 0; true x == null; Static Error: Bad type in comparison expression y == 0; java.lang.NullPointerException y == null; true
However, my professor claims in a lecture that the values should be as follows:
x == 0; Uninitialized x == null; Undefined y == 0; java.lang.NullPointerException y == null; Uninitialized
Now I don't want to doubt the one who writes the exam, but which x == 0 and y == null truth value is correct? An explanation on why would be very much appreciated, thank you.
In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used.
The value in an uninitialized variable can be anything – it is unpredictable, and may be different every time the program is run. Reading the value of an uninitialized variable is undefined behaviour – which is always a bad idea.
"Unitialized int equals 0. Unitialized Integer equals null." Not true, only when they are instance variables not local variables.
No difference - int members are initialized to zero by default.
a.x == 0
- True because a.x has a default value of 0.a.x == null
- As noted, this is a compile-time error. This follows from §15.21.3: "A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5)." The null type isn't convertible to a number.a.y == 0
- This tries to unbox a.y,
which is null, so it throws a NullPointerException. Unlike the above (which has a literal null), the compiler doesn't try to figure out at compile-time that a.y
will be null.a.y == null
- Again, true because a.y
is initialized to nulla.z == 0
- Same as a.x
(except static)a.z == null
- Same as a.x
(except static)a.z2 == 0
- Same as a.y
(except static)a.z2 == null
- Same as a.y
(except static)The problem with the interactions pane is that it's up to the IDE how to implement it. If x and y are local (uninitialized) variables, all four of your last comparisons will fail to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With