What is the difference between String name="test" and String s4 = new String ("Peter");


What's different about assigning a value to the variable by creating an object and assigning unboxing to a direct value?

String s4 = new String("nome");

String nome = "nome";
System.out.println("nome == s4 " + (nome == s4)); //retorna false

If I compare these two variables with == it will give false , however with equals() equals true . These concepts I understood well.

But I have doubts because it does not matter if I assign another variable

String nome2 = "nome";
System.out.println("nome == nome2 " + (nome == nome2)); //resultado true
asked by anonymous 05.09.2017 / 04:07

1 answer


The == compares if two variables point to the same memory location and equals() compares the contents.

Give this equality because of the interning , where two equal values are stored in the same place, as long as they are immutable and determined at compile time. And the case of the string literal. So the "nome" in every application only exists one, including what is being used as argument of the constructor of class String used in the first example.

What is different is that in the case of the literal the compiler can already determine the location of the object and in case the use of the constructor can not, after all the argument could be a variable.

You may wonder if the compiler could not optimize this case since the constructor uses a literal. It could, but probably is not worth the effort because the builder is not usually used with a literal, and if using it probably used because it does not want interning .

Variables are different, but they point to the same object.

05.09.2017 / 04:27