String.valueOf() Null pointer [duplicate] - java

This question already has answers here:
Why does String.valueOf(null) throw a NullPointerException?
(4 answers)
Closed 9 years ago.
In java Doc it is written that String.valueOf() will return "null" if argument is null, but in practical it gives null pointer exception for null argument. I want to understand the reason. Tried looking on GREPCODE, could not get it. Please explain

If you have code like this:
System.out.println(String.valueOf((Object) null));
"null" is printed to the console. If you have:
System.out.println(String.valueOf(null));
a NPE is thrown.
That is because valueOf is overloaded.
String.valueOf(Object)
String.valueOf(char[])
To explain the NPE, if you examine the code for String.valueOf(char[]):
return new String(data);
and the constructor for String is:
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
On this line, a NPE is thrown with the statement value.length.

Your call activates String.valueOf(char value[]) that throws NPE in case of null argument. String.valueOf(Object value) works only if you drop the object to this method. Have a look at here

Related

Unwanted Null Pointer Exception in ternary operator with Optional [duplicate]

This question already has answers here:
Unwanted NullPointerException in ternary operator - Why? [duplicate]
(2 answers)
Nullpointer exception with conditional operator, (ternary operator) but not with if else [duplicate]
(1 answer)
Closed 3 years ago.
To my understanding following code should not throw Null Pointer exception as I am safely using Optional interface.
However, when I ran this code it is throwing NPE.
public class Test {
public static void main(String[] args) {
final Integer inte = false ? 0 : Optional.ofNullable((Integer) null).orElse(null);
}
}
Please let me know if I am mistaken somewhere in my code and help me to rectify the same.
The reason you get a NullPointerException, is that the type of the expression false ? 0 : Optional.ofNullable((Integer) null).orElse(null) is int (by JLS Table 15.25-C).
The expression Optional.ofNullable((Integer) null).orElse(null) evaluates to null, and casting a null to an int results in a NullPointerException.
Surely you'll get a NullPointerException, because your right hand side is just a very verboose way of saying null. You're wrapping a null in an Optional thus forcing the orElse which executes to null.
Having null in a statement that resolves to int, as explained by #Hoopje (even if it's assigned to an Integer variable) leads to a NullPointerException.
Just wrapping null in an Optional still gives you a null when unwrapping it again.
I found the work around
final Integer inte = false ? (Integer)0 : Optional.<Integer>ofNullable(null).orElse(null);
or
final Integer inte = false ? (Integer)0 : Optional.ofNullable((Integer)null).orElse(null);
the type returned by the ternary operator is expected to be int (because of the literal 0).

Why the order is reverse in equals() [duplicate]

This question already has answers here:
String.equals() argument ordering
(10 answers)
Closed 3 years ago.
In part of the code for check empty string the programmer use equals() like this:
if ("".equals(name)) {
// some logic
}
Why is it executed from a string value directly? What is the difference from this;
if (name.equals("")) {
// some logic
}
Both of them have the same result, but what is the idea behind doing the first one?
The idea behind using;
"".equals(name)
is that "" can never be null, whereas name can be. equals() accepts null as a parameter, but trying to execute a method from a null variable will result in a NullPointerException.
So this is a shorthand way to evade such possible exceptions. Same goes for any such constant object.
e.g.
final Integer CONSTANT_RATE = 123456;
....
if (CONSTANT_RATE.equals(someVariable)) { .. }
rather than doing;
if (someVariable != null && someVariable.equals(CONSTANT_RATE)) { .. }

Conversion of null to string in Java [duplicate]

This question already has answers here:
Why does String.valueOf(null) throw a NullPointerException?
(4 answers)
Closed 5 years ago.
Today I found a bug in legacy code, which led me to a shocking discovery:
String s = null + ""; //results in "null" string
s = String.valueOf(null); // NullPointerException is thrown
Integer i = null;
s = String.valueOf(i); //results in "null" string
First question is: Why such an unexpected behavior happens?
It mean that a convenient code like this:
String age = person.getAge() + "";
is being totally unexpected.
Second question: What is the best (most elegant) way to get a null instead of "null"
String.valueOf(null) calls public static String valueOf(char data[]) due to method overloading resolution rules (char[] is more specific than Object). That method throws NullPointException for a null argument.
String.valueOf(i) calls public static String valueOf(Object obj), which returns the String "null" for a null argument.
To avoid this exception, either don't call s = String.valueOf(null); (you can always assign s = "null"; directly, or cast the null value to some type other than char[] (for example s = String.valueOf((String)null);).

what are the scenarios where System object might throw a null pointer exception?

I am preparing for an interview and while I was going through null pointer exceptions, I suddenly realized every object is somehow capable of throwing a null pointer exception, but I can't seem to imagine certain objects like System, Out etc. throwing NullPointerException.
Can anyone mention such scenarios? Thank you!
For example: System.out.println(s.get(name));
First, System is not an object. It is a class whose methods are static. Second, out is a static field of that class that is (initially) a reference to a standard output PrintStream. You can change that PrintStream to your own with System.setOut(PrintStream).
Finally, if you did
System.setOut(null);
System.out.println("42"); // because out is now a null reference
you would get a NullPointerException.
Sure, you can find a method of System that throws a NullPointerException as well.
Most of these NullPointerException are thrown by the JVM when you try to dereference a null object reference.
You don't dereference a class.
Only executable code can throw an NPE, such as a method, constructor,
or an initializer. - Marko
Not every object is capable of throwing a NullPointerException. It's generally best to try to write classes that cannot!
public class ClassThatCannotNPE {
public int getOne() {
return 1;
}
}
The only two things you can do with the above class, are to run its constructor, and invoke getOne(). Neither of those things can NPE.
We must be careful to define what we mean by saying that "something" throws an exception. This code will throw an NPE at line 2:
Date d = null;
System.setProperty("now",d.toString());
But that's not an example of System, or code from System, throwing the exception. The code above is equivalent to:
Date d = null;
String temp = d.toString();
System.setProperty(temp);
This would also throw an NPE at line 2 -- before System.setProperty() gets a chance to run. The execution order is exactly the same as the previous example.
What about:
System.out.print(null);
This will throw an NPE. But once again, it's not code from System that's throwing it. It is equivalent to:
PrintStream temp = System.out;
temp.print(null);
The NPE happens at line 2 -- which doesn't refer to System nor anything that refers to System.
System is a class, not an object. It does not have a constructor, so cannot be instantiated.
However, it has a lot of static methods. Is it possible to make any of those throw a NullPointerException?
Actually, we can find out pretty quickly by looking at the Javadoc for System, and searching for "NullPointerException". The first match of many is in System.arraycopy():
If dest is null, then a NullPointerException is thrown.
So there you have it:
System.arrayCopy(null,0,null,0,0);
... will cause some of the code in the System class to throw an NPE.
In fact we can look at the actual source code for System and see where it throws NullPointerExceptions.
488 public static native void arraycopy(Object src, int srcPos,
489 Object dest, int destPos,
490 int length);
Oh. arraycopy is native - meaning the actual implementation is some C code in the JRE. But what else can we find?
825 private static void checkKey(String key) {
826 if (key == null) {
827 throw new NullPointerException("key can't be null");
828 }
...
and
777 public static String setProperty(String key, String value) {
778 checkKey(key);
...
So another way to make code from System throw an NPE is:
System.setProperty(null,"value");
An operation on a null object will throw a NullPointerException. In the example s.get(name) e if s is null then a NullPointerException will be thrown. Since System is an class, a static reference will not be null. Looking at the source you can see that out is static and final and is eventually initialized with the following command.
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
Normally since it is final this means that it will not be null and cannot be made null. However public static void setOut(PrintStream out) calls a native function private static native void setOut0(PrintStream out) in which the implementing VM can create a null reference.
It depends on the implementation of a method whether or not it will throw a NullPointerException. Specifically println(String) will do a null check before operating on the passed in variable.
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
So in that case the method itself should not throw a NullPointerException as long as the PrintStream is properly initialized which in the case of System it is.
I hope that helps answer your question. If not, please articulate in the comments what you are looking for.
Wrapper class are capable of throwing NPE.Although java provides autoboxing,but they are not initialized by default unlike primitive data type.
Integer r;
if(r>1)

Java: checking if Comparable is not null returns NullPointerException

I have a big problem with this code and I have no idea how to cause it:
while(tree.find(indexreg)!=null){
//do stuff
}
For some reason, comparing tree.find(indexreg) with null causes a NullPointerException. Since this is a college project I have to use my own binary tree implementation instead of the one provided by Java. tree is a BinarySearchTree and indexreg is a Comparable object, that was already initialized. This is the code for find in the BinarySearchTree class:
public Comparable find(Comparable x) {
return elementAt(find(x, root));
}
It looks for the object in the tree and it returns null if it doesn't find it (I don't think you can return an empty Comparable object). I tried Googling but I didn't find an useful answer. Does anyone know how to make this code work?
I don't think the problem has anything to do with your Comparable.
If the line while(tree.find(indexreg) != null) { throws a NullPointerException, it must be because tree is null. No other possibilities are credible.
Comparison of an object reference with null using == or != will NOT throw an NPE. So even if tree.find(...) returned a null, that can't be the cause of this exception.
Passing a null value as a method argument will NOT throw an NPE. So if indexreg was null, that wouldn't cause this exception. (An NPE could be thrown by the find method or something it calls, but the stacktrace will not show a different line in a different method as the origin of the exception.)
(I could be misinterpreting the question. I'm assuming that the OP means "throws" when he says that the line "causes" the exception.
Unfortunately, the OP is only posting snippets of code and hasn't shown us the stacktrace ... which is the critical piece of evidence.)
public Comparable find(Comparable x) {
return x == null ? null : elementAt(find(x, root));
}
fyi this is equivalent to:
public Comparable find(Comparable x) {
if (x == null) return null;
return elementAt(find(x, root));
}
You nay also consider improving the clarity of your code: You have a method call and a test combined. While this is not "bad" per se, IMHO it would be cleaner to separate the two, AND get a hold of the value returned in case you want to do something with it, like this:
for (Comparable<?> result = tree.find(indexreg); result != null; result = tree.find(indexreg)) {
//do stuff with variable "result"
}
It just makes it more obvious what is controlling the loop.
There is another way to get the result, but it's considered "bad coding style" by some; that is to assign and test in one:
Comparable<?> result;
while ((result = tree.find(indexreg)) != null) {
//do stuff with variable "result"
}
Some believe that you should avoid this style of coding. I tend to agree with them.
Possibly indexreg is null, not initialized at all. You should certainly code find() more defensively as suggested by #Bohemian but this may be the underlying problem. Or see next comment below.

Categories