What is the best way to create a String in java?
String str = "skill gun";
String str = new String("skill gun");
both option 1 and 2 are same
we can't predict
String str = "skill gun"; will store string in string constant pool.
String constant pool: has a behavior where before creating a string object it will first check if it is already available or not. If it is not available then only it will create, else it will shared the previous copy only.
That means string constant pool will efficiently use the memory space by reusing the strings. where as heap doesn't have this property. While creating strings if we don't use new operator, it will be automatically created in string constant pool.
Back To Top