-5

What is the differences between String str1="" and String str2 =null? When we print str1 there is no output and when we print str2 output is null.

Ankush soni
  • 1,439
  • 1
  • 15
  • 30
Gauri Shankar
  • 91
  • 3
  • 9
  • 2
    Not really clear what you're asking here... one is a reference to a `String` object with a length of 0, and one is a null reference (i.e. not a reference to an object at all) – Jon Skeet Sep 29 '14 at 12:12
  • 3
    @vikeng21 What do you mean by `null` not being "valid"? –  Sep 29 '14 at 12:13
  • 2
    Already asked question..Refer this http://stackoverflow.com/questions/4802015/difference-between-null-and-java-string – Karthik Sep 29 '14 at 12:13
  • @ Tichodroma i meant what you have excatly answered – vikeng21 Sep 29 '14 at 12:15

5 Answers5

5

"" is the empty string, null is the null reference.

  • 2
    @sotcha - `""` is a *String Literal*, it will go into the String constants pool. It is not equal to `new String()` – TheLostMind Sep 29 '14 at 12:27
  • @TheLostMind you got right, it is not equal, it's equivalent (as the documentation says). If I create many "" objects with point to the same object. – sotcha Sep 29 '14 at 16:50
1

The first is an empty String whereas the second is a null reference to a String.

An empty String is a String with no characters.

A null reference is a reference to a String that is not existent.

Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48
  • if A null reference is a reference to a String that is not existent,than how System.out.print(str) give output as like null – Gauri Shankar Sep 29 '14 at 12:18
  • 2
    @GauriShankar null is handled as a special case, explicitly. Check out the docs for [String.valueOf](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)): `if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.` – default locale Sep 29 '14 at 12:23
  • A null reference is a reference to *nothing* (null). – TheLostMind Sep 29 '14 at 12:28
1

There Huge Difference "" means this empty String and Second one null means there is noting to assign and its noting exists.

Simmant
  • 1,477
  • 25
  • 39
1

"" means strings is created in string pool while for second one is nothing exist.

str1 there is no output

because string is empty so its printing nothing to output while second is null so its string value is null.

Community
  • 1
  • 1
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

The first you are creating a new String object and assigning it "" or empty String. Your variable is pointing to this string object. The second you are not creating a new String object. You are creating a pointer that is not pointing to anything it is null. When you print using "" + yourstring it will print null because of the base Class objects toString() method.

brso05
  • 13,142
  • 2
  • 21
  • 40