Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null = "" for a string

Tags:

java

In Java are these 2 statements the same?

String a = null;
String b = "";

It feels a bit of a dumb question but have a complete mental block currently.

like image 583
Dean Avatar asked Jun 27 '10 20:06

Dean


1 Answers

The empty string and null are different. The empty string is a string with no characters, null is not having a string at all.

You can call methods on an empty string but if you try to call a method on null you will get an exception.

public static void main(String[] args)
{
    String a = null;
    String b = "";
    System.out.println(b.length());
    System.out.println(a.length());
}

Output:

0
Exception in thread "main" java.lang.NullPointerException
        at Program.main(Program.java:12)
like image 124
Mark Byers Avatar answered Oct 13 '22 01:10

Mark Byers