I know that the title of the question is not very clear, sorry about that, did not know how to put it up. I have a very basic java implementation question which I want to focus on application performance, but it also involves String creation pattern in java.
I understand the immutability concept of Strings in Java. What I am not sure about is that, I have read somewhere that the following will not make two different String objects:
String name = "Sambhav";
String myName= "Sambhav";
I want to know how does Java do that? Does it actually look for a String value in the program memory and check for its existence and if it does not exist then creates a new String object? In that case obviously it is saving memory but there are performance issues.
Also lets say I have a code like this:
public void some_method(){
String name = "Sambhav";
System.out.println(name); // or any random stufff
}
Now on each call of this function, is there a new String being made and added to memory or am I using the same String object? I am just curious to know about the insights of how all this is happening?
Also if we say that
String name = "Sambhav";
String myName= "Sambhav";
will not create a new object because of reference, what about
String name = new String("Sambhav");
String myName= new String("Sambhav");
Will Java still be able to catch that the string are the same and just point myName to the same object as created in the previous statement?