Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As we all know, Java will not create a new string constant if it already exists in the String Constants Pool. But by that logic, shouldn't s1==s5 and others be true? None of the strings I created used the "new" keyword.

What I have tried:

Java
public class strings1 {

    public static void main(String[] args) {

        // String str = new String("very");

        String s1 = "mynameisbond";
        String s2 = "myname" + "isbond";
        String s3 = "myname";
        String s4 = "isbond";
        String s5 = s3 + s4;
        String s6 = "myname" + s4;
        String s7 = s3.concat(s4);

        System.out.println(s1 == s2); // true
        System.out.println(s1 == s5); // false
        System.out.println(s5 == s6); // false
        System.out.println(s2 == s7); // false

    }

}
Posted
Updated 11-Aug-23 11:05am
v2

1 solution

No, because
String s1 = "mynameisbond";
uses a single string literal and
String s2 = "myname" + "isbond";
uses two that can be combined at compile time into a single literal.
But s5, s6, and s7 all get assigned at run time, not compile - so the strings they contain are not string literals: they are not "known" at compile time so they do not get added to the Constants Pool.

Quote:
If i do: String greet = new String("hello") , I know the string "hello" will be allocated to the HEAP but at the same time this "hello" will also be created in String Constant Pool? so in the next line if I do: String greet2 = "hello" , greet2 will point to the already existing "hello" by greet in the String Constant Pool or it never existed there because of new keyword of greet?


There are two ways to create a string:
Java
String s="Welcome";
This creates a variable called s which "points" to a literal string "Welcome" in the Constant Pool.
Java
String s=new String("Welcome");
This creates a variable called s, a string literal "Welcome" in the Constant Pool unless it already exists there, and a copy of the literal the heap - s "points" at the heap version.
The new keyword always constructs a heap based variable.
 
Share this answer
 
v2
Comments
Sharyar Javaid 2-Aug-23 12:30pm    
Thank you so much! One more question : If i do: String greet = new String("hello") , I know the string "hello" will be allocated to the HEAP but at the same time this "hello" will also be created in String Constant Pool? so in the next line if I do: String greet2 = "hello" , greet2 will point to the already existing "hello" by greet in the String Constant Pool or it never existed there because of new keyword of greet?
OriginalGriff 2-Aug-23 14:50pm    
Answer updated.
CPallini 3-Aug-23 2:39am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900