2

I wrote the program to reverse the string

String original = "hello";
String rev = "";
for (int i = original.length() - 1; i >= 0; i--) {
    rev += original.charAt(i);
}
System.out.println("Reversal:" + rev);

The output is : Reversal:olleh

But, when I rewrite String rev="" as String rev =null

I get the output as Reversal:nullolleh

What is the difference between null and "" character?

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
TodayILearned
  • 1,440
  • 4
  • 20
  • 28
  • 1
    I wont answer since there are decent answers already, but you should use StringBuilder for this. It is much more performant. Or you can just use a char array as you know the exact size. – cvesters Jul 19 '15 at 11:21

3 Answers3

3

"" is an empty String, i.e. an object of the String class having 0 characters. null represents a lack of a reference to an object.

When you append a null reference to a String, the null reference is converted to a String whose value is "null". Therefore, if you intend to append two Strings, you should make sure that none of them is null (assuming you don't want your output to contain the "null" String).

However, using a StringBuilder is the preferred way to concatenate Strings (though the compiler may do this optimization anyway when encountering the String concatenation operator +) :

String original = "hello";
StringBuilder rev = new StringBuilder();
for (int i = original.length() - 1; i >= 0; i--) {
    rev.append (original.charAt(i));
}
System.out.println("Reversal:" + rev.toString());
Eran
  • 387,369
  • 54
  • 702
  • 768
2
String s = null; // no refrences to it at all
String s1 = "";
s.trim()// NullPointerException
s1.trim()// will give ""

Basically we use "" if any string is blank, so doing any operation on it, ie calling methods on it wont give NPE. While null is a keyword, will give NPE, if performed any operation on it. No references to it at all.

AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23
2

null means your variable points to no object at all. "" is the representation of a String object containing zero characters.

BladeCoder
  • 12,779
  • 3
  • 59
  • 51