Difference between null and empty (“”) Java String

前端 未结 22 1500
再見小時候
再見小時候 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:43

    as a curiosity

        String s1 = null;
        String s2 = "hello";
    
         s1 = s1 + s2;
       
    
        System.out.println((s); // nullhello
    
    0 讨论(0)
  • 2020-11-22 17:44

    In simple term,

    • "" is an empty String

    • null is an empty String Variable.

    0 讨论(0)
  • 2020-11-22 17:44

    "I call it my billion-dollar mistake. It was the invention of the null reference in 1965" - https://en.wikipedia.org/wiki/Tony_Hoare

    With respect to real world both can be assumed same. Its just a syntax of a programming language that creates a difference between two as explained by others here. This simply creates overhead like when checking/comparing whether string variable has something, you have to first check if its not null and then actual string comparing ie two comparisons. This is a waste of processing power for every string comparisons.

    Objects.equals() checks for null before calling .equals().

    0 讨论(0)
  • 2020-11-22 17:46

    The empty string is distinct from a null reference in that in an object-oriented programming language a null reference to a string type doesn't point to a string object and will cause an error were one to try to perform any operation on it. The empty string is still a string upon which string operations may be attempted.

    From the wikipedia article on empty string.

    0 讨论(0)
  • 2020-11-22 17:47

    A string can be empty or have a null value. If a string is null, it isn't referring to anything in memory. Try s.length()>0. This is because if a string is empty, it still returns a length of 0. So if you enter nothing for the same, then it will still continue looping since it doesn't register the string as null. Whereas if you check for length, then it will exit out of it's loop.

    0 讨论(0)
  • 2020-11-22 17:47

    Difference between null & empty string. For example: you have a variable named x. If you write in JS,

    var x = "";

    this means that you have assigned a value which is empty string (length is 0). Actually this is like something but which is feel of nothing :) On the other hand,

    var y = null;

    this means you've not assigned a value to y that clearly said by writing null to y at the time of declaration. If you write y.length; it will throw an error which indicates that no value assigned to y and as a result can't read length of y.

    0 讨论(0)
提交回复
热议问题