What is the difference String a; from String a = new String();

    3 answers 3

    According to @Pavel Parshin, in the first case, the variable a not initialized (it is not even null ). Its further use is impossible, otherwise the error will be compiled error: variable a might not have been initialized . An example .

    enter image description here

    In the second case, according to en-SO , a new object of type String with an empty string inside ""

     Sting a; TextUtils.isEmpty(a); //ошибка компиляции - переменная не инициализирована. a = new String(); TextUtils.isEmpty(a); //true 
    • 2
      Not quite right. In the first case, the variable a not initialized (it is not even null ). Its further use is impossible, otherwise the error will be compiled error: variable a might not have been initialized. ideone.com/cn6cCg - Pavel Parshin
    • @PavelParshin, you are right. I updated the answer with your comment. - Yuriy SPb
    • Well, if I write String a = ""; and String a = new String(); Then what's the difference? - MaximPro
    • @MaximPro, there are many subtleties. Look here for a comparison of the lines - Yuriy SPb
    • 2
      when you write String a = new String (); it always creates a new object. If you write String a = "Hello"; and String b = "Hello"; and cut the links a == b then the result will be true. Links point to one object. with String b = "Hello"; checks if there is such a string in the row pool and if there is a link to it returned - MrGarison

    The above are good answers, but if not clear, then String is the name of the class, String a; - the creation of a pointer to a variable of class String , it tells us that a variable of this class will be available for this pointer, but so far it is only a pointer that does not point to anything concrete. new String() is the creation of a specific object in memory, under which space is allocated, and for access to which the same pointer a can be used, thus this construct String a = new String(); tells us that the pointer а will point to this particular object in memory new String() .

      When writing String b - you simply create a variable b , which is a reference to an object of type string (but so far it does not indicate anything).

      When you write String b = "Hello world" , you initialize the object immediately, in fact, it replaces new . And assign our link b link to this object.