Conversion of null to string in Java [duplicate] - java

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);).

Related

It says NullPointerException even though my String s has a stored text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
If I use l.search("Hi"); the code will run fine but if I pass String s to search method, it will prompt an error NullPointerException
System.out.print("Search: ");
String s = scan.next();
l.search(s);
public void search(String name){
Node current = tail;
while(current != null && current.name != name){
current = current.previous;
}
if(current.name == name){
System.out.println("Item found.");
}
}
You have several issues here. A null pointer exception occurs when you try to reference an object that doesn't exist. If "s" hasn't been initialized, referring to it causes a null pointer exception.
To compare strings use methods like myFirstString.equals(stringComparingTo) which returns an integer. If I recall this equals zero when the two strings are equal (or current.name.equals(name)==0 - in your case). This assumes "name" is a field of your "node" class.

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)) { .. }

What is the difference between String str=null and String str="null"? [duplicate]

This question already has answers here:
What is null in Java?
(14 answers)
Closed 3 years ago.
I have a class with the two string variable i.e:
String str = null;
String str1="null";
One is a "string value null" and other in other case null object is assigned to a string variable.
So what is the difference in both the two assignments and how to check if one is different from other ??
String str = null; means str is a reference of String which points to null.
And String str1="null"; means str1 object which points to String Object which is "null".
First check if object is null or not ? then compare by using equals method.
like
if(str==null && str1==null){
//Both are null and equal
}
if(str != null && str.equals(str1)){
//return true;
}
else
{
//return false;
}
The String "null" is a string of length 4 with the characters n, u, l and l. It can be worked on as any other string.
The null reference isn't a string. Any attempt to use it like a string will result in a NullPointerException.
1) String str = null;
Here str has no instance is created because it is assigned to null, so no new memory is consumed in heap
2) String str1="null";
Here str1 string instance is created and "null" is stored as value

difference between (string == null) and (string.length() == 0)? [duplicate]

This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
Closed 4 years ago.
I got different simulation results when I programmed in these two ways:
if (S == null) {
return new LinkedList<>();
}
and
int len = S.length();
if(len == 0) return new LinkedList<>();
The first code gave me [""], which passed the testing. While the second one gave me [], got failed.
And I also noticed that there is another way: S.isEmpty()
Would anyone please explain? Many thanks!
String == null checks if the object is null (nothing, not even an empty string) and String#length() == 0 (actually, you should use String#isEmpty() instead) checks if the string object has 0 chars. Also, you can't access any methods if the object is null, it will throw a NullPointerException (or NPE for short).
difference between (string == null) and (string.length() == 0)?
Very different.
When you check (string == null), it checks whether the string reference is pointing to any existing object. If it is not referencing to any object, it will return true.
string.length() == 0 just checks your existing String object's content and see if its length is 0. If no object exist in the current variable when you invoke .length(), you get a NullPointerException.
S is a reference variable (you should write it in lower case).
S (or rather s) references an object that provides the method length().
You can only access the object referenced by s, if s is a really a reference to an object. If s is null (s==null), s does not reference an object and therefore, you can not call the method length(). If you try, you will get a NullPointerException.
When s references an object, you can call the length method on that object. In this case, it is a string object. A string object may exist without any characters (empty string, or "").
String s; // just a reference, initial value is null
s = ""; // s now references an empty string and is no longer null
new String(""); // create a new object with an empty string
In Java, you never really work with objects. You only work with references to objects, though in most cases, it appears as if you work with the object directly.
Keep in mind that the reference variable and the object are really to different things.
If the string you are passing into the second one is null, an exception should occur, since .length() will throw an exception when called on a null string.
if a String instance is null, myInstance.length() == 0 would throw a NullPointerException, because you call an instance member of a not instantiated instance and crash your application.
So, if you're not sure your String instance is instantiated, always do a null-check, or better yet, with Java 8 or later, use Optional to avoid null's.
S == null mean that there if you try to print something for instance, nothing wiil happen (or maybe a nullPointerEcxeption) because null mean that there is nothing inside this variable.
String.lenght(S) == 0 mean that your string equals to ''
for instance :
String S1 = '';
String S2 = null;
try{
System.out.println(S1.length() == 0) {
System.out.println('S1 is not null');
}catch(nullPointerExeption e){
System.out.println('S1 is null');
}
try{
System.out.println(S2.length())//it will throw you a java.nullpointerexcption
System.out.println('S2 is not null');
}catch(nullPointerExeption e){
System.out.println('S2 is null');
}
The system will write
0
S1 is not null
S2 is null
//case1
String s;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
//error: variable s might not have been initialized
//case2
String s=null;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
/* output
I am null
error: Null pointer exception
*/
//case 3
String s=new String();
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/
String s="";
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/

Java String concatenation - nulls [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Concatenating null strings in Java
I'm just wondering if someone can explain why does the following code works the way it does:
String a = null;
String b = null;
String c = a + b;
System.out.println(c.toString());
This prints "nullnull" to the console.
I was kind of expecting that the operation + would thrown an exception or, to a lesser degree, that "c" would be null.
because that code compiles to
String c = new StringBuilder().append(a).append(b).toString();
and StringBuilder.append(a) appends the result of String.valueof(a) which is "null" if a is null
"String conversion," required by the concatenation operator, mandates that null values are to be mapped to the four characters null whenever a string representation is needed.
Spec for string conversion: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.11
Spec for string concatenation: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.1
When java find a null reference during the string concatenation convert it to the string "null". So "nullnull" is the right result.
Before concatenation for every object Java call
java.lang.String.valueOf(Object)
and if you look at the source code of that method you find this
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

Categories