Reputation: 1116
I have a rather simple test case below. I can send nulls to the constructor with no problems or errors, but when I try to send nulls to a method, it errors out with: error: incompatible types: <null> cannot be converted to int
(or whatever type is expected). I'm not exactly sure why this occurs and I've seen in many places where sending nulls is acceptable practice. In all reality I just need nulls so that I can pump this example into Soot and Spark for static analysis, so the actual parameters sent to the methods are irrelevant other than a semantic necessity for entry points in the Spark-static analysis.
public class Test {
public Test(Object var1, Object var2) {
//do irrelevant stuff here with var1 and var2
}
public void api1(int x, int y) {
// do irrelevant stuff with x and y
}
public List<String> api2(String x, int y, boolean a) {
// do irrelevant stuff with x, y, and a and return a new ArrayList<String>()
}
}
public class Main {
public static void main(String[] args) {
Test usingVars = new Test(1, 2); // works, compiles and no errors
Test usingNulls = new Test(null, null); // works, compiles and no errors
/**
* usingVars will obviously work and not complain at all
*/
usingVars.api1(1, 2); // works, compiles and no errors
usingVars.api2("test", 1, false); // works, compiles and no errors
/**
* usingNulls should work, but throws this error on compilation:
* error: incompatible types: <null> cannot be converted to int
*/
usingNulls.api1(null, null); // should work, doesn't compile errors out
usingNulls.api2(null, null, null); // should work, doesn't compile errors out
}
}
Upvotes: 0
Views: 257
Reputation: 3140
It is impossible to pass null
to a method, constructor or otherwise, to a primitive type (e.g. int
, short
, byte
, float
) because in java you have two type systems, primitives and objects. Primitives can be cast to their object wrappers (e.g. Integer
, Short
, Byte
, Float
) and be used as objects, so if you need to pass null, use Integer
, not int
. However the convention in java for passing useless values for int
s is to use -1
.
Upvotes: 1
Reputation: 533492
In Java you have two types of variables, primitives and references.
A reference can be null
as it references nothing. A primitive, such as int
cannot be null
, it has to be a number.
If you don't care what the values is you can use 0
, -1
or Integer.MIN_VALUE
Upvotes: 1
Reputation: 311163
primitives, (e.g., int
s), can't take null
s. If you absolutely positively have to use a null
value, you should define your method parameters as the appropriate wrapper class (e.g., java.lang.Integer
for int
):
public Test(Integer var1, Integer var2) {
//do irrelevant stuff here with var1 and var2
}
public void api1(Integer x, Integer y) {
// do irrelevant stuff with x and y
}
public List<String> api2(String x, Integer y, Boolean a) {
// do irrelevant stuff with x, y, and a and return a new ArrayList<String>()
}
Upvotes: 6