开发者

null = "" for a string

In Java are these 2 statements the same?

String a = null;
String b = "";

It feels a bit of a 开发者_StackOverflowdumb question but have a complete mental block currently.


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)


No, an empty string is not null.


They are most definitely not the same. Your String variable acts as a reference to an object in memory, and if it's set to null, it's not pointing to anything. If it's set to the empty-string value, it's pointing to that.

In my own coding, I generally set a String to "" instead of to null unless I have a special need for null. There are some libraries like Apache Commons that include helper classes like StringUtils that will collapse a check for null, the empty string, and even just whitespace into one call: StringUtils.isBlank(), StringUtils.isNotBlank(), etc. Pretty handy. Or you can write your own helper methods to do similar pretty easily.

Good luck as you progress in Java!


The third possibility is:

String c;

All three are different, of course.


this is not as dumb as it sounds. it bothers even seasoned programmers. in many real world projects people often write something like if(s==null || s.isEmpty()), i.e. people treat null and "" as semantically equivalent .


null means it refers to nothing, while empty string is a special string with zero length.


String a = null;
String b = "";

The first statement in java initialises a variable handle. there is no memory allocated for data to be saved.

The second statement shows two objects the first object being the handle (b) and second object being "" (if we ignore the higher concepts of string pooling in java where string is mutable and jvm gives out pooled instances of string)

thus the two lines are not same.


No, They are different. If you use a null String in a method, then Exception occur But not occur in a empty String!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜