Difference between null and empty (“”) Java String

前端 未结 22 1687
再見小時候
再見小時候 2020-11-22 17:10

What is the difference between null and the \"\" (empty string)?

I have written some simple code:

String a = \"\";
String b         


        
22条回答
  •  悲&欢浪女
    2020-11-22 17:41

    "" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.

    But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.

    public class StringCheck {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        String s1 = "siddhartha";
        String s2 = "";
        String s3 = null;
    
        System.out.println("length s1 ="+s1.length());
        System.out.println("length s2 ="+s2.length());
    
        //this piece of code will still throw nullpointerexception . 
        if(s3 != ""){
            System.out.println("length s3 ="+s3.length());
        }
    }
    

    }

提交回复
热议问题