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

Asked

Viewed 207 times

9

What’s the difference of assigning a value to a variable by creating an object and assigning Unboxing at 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 == will give false, but with equals() is equal to true. These concepts I understood well.

But I doubt because it does not equal if I assign another variable

String nome2 = "nome";
System.out.println("nome == nome2 " + (nome == nome2)); //resultado true
  • If you assign the value to a variable without creating an object, it creates the value in the same memory variable?

1 answer

9


The operator == compares whether two objects point to the same memory location and the equals() compares the contents of objects.

Give this equality because of the call interning, where two equal values are stored in the same location, provided that they are immutable and determined at compile time. This is the case for the literal string. Then the "nome" in every application there is only one, including the one being used as argument of the class constructor String used in the first example.

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

You may ask if the compiler could not optimize this case since the constructor uses a literal. Could, but probably not worth the effort because usually do not use the constructor with a literal, and if use probably used because do not want the interning.

The variables are different, but they point to the same object.

  • obg was great his explanation, bigown because I always thought the values of a string are as object, only in this case as Unbox, but then it is being "referenced" as a literal, in this case remains in the same place the values.

  • Like string is a type by reference does not fit Boxing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.