Reputation: 121
Is there any possibility that Integer.toString(args)
give an NullPointerException
like String.valueOf(args)
.
I know its Silly Question but I want to be clear that is there any possibility that Integer.toString()
can give NullPointerException
.
Upvotes: 7
Views: 11403
Reputation: 3346
Integer.toString(args)
may give an NullPointerException
unlike String.valueOf(args)
.
Integer i = null;
Integer.toString(i); // Null pointer exception!!
String.valueOf(i); // No exception
i.toString(); // Again, Null pointer exception!!
See my experiment here : http://rextester.com/YRGGY86170
Upvotes: 6
Reputation: 11652
The answer is yes and no. It depends on how one interprets your question.
Is it possible for the expression var.toString()
(or Integer.toString(var)
) to throw a NullPointerException?
Yes.
Can the method Integer.toString()
(or Integer.toString(int)
) ever throw a NullPointerException?
No.
In var.toString()
, a NullPointerException will be thrown if var
is null. But the exception will be thrown by the current method, and toString()
will not be called.
In Integer.toString(var)
, a NullPointerException will be thrown if var
is null. But it is not the toString(int)
method that throws it. If var is an Integer object, the expression is shorthand for
Integer.toString(var.intValue())
and so obviously if var
is null, a NullPointerException will be thrown by the current method, and neither intValue()
nor toString(int)
will be called.
So to reiterate, toString()
and toString(int)
themselves never throw NullPointerException.
Upvotes: 2
Reputation: 14415
Technically yes, due to unboxing. Although I'm not sure if that is what you meant:
public class Test {
public static void main(String[] args) {
Integer i = null;
System.out.println(Integer.toString(i)); // NullPointerException
}
}
Upvotes: 3
Reputation: 206946
Do you mean the static method toString(int i)
of class Integer
? That method will never throw NullPointerException
- there is no int
value that you can pass that will ever produce a NullPointerException
.
Upvotes: 1
Reputation: 1024
Integer#toString does not take any args, and only passes in the field value
. value
can never be null because you cannot pass a null int
primitive and a null String
will simply throw a NumberFormatException
here
EDIT:
I did not consider the toString methods which take an int
, but the results will be the same - int
can never be null so there will be no NPE
Upvotes: 0