what is the difference between these two implementations :
String s1 = "java";
and
String s2 = new String("java");
is s1 is able to perform all the functions that s2 will do?? like to uppercase, append etc..
what is the difference between these two implementations :
String s1 = "java";
and
String s2 = new String("java");
is s1 is able to perform all the functions that s2 will do?? like to uppercase, append etc..
The only Difference is String s1 = "java"
will create a String Literal and it will be stored in a String Pool And for String s2 = new Sting("java")
an Instance object will be created plus a String Literal in String pool.
For Second part Yes
you can, Since its a Variable and variable can access library function using dot operator. so s1.toUpperCase()
and s2.toUpperCase()
.
Ex.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = new String("java");
System.out.println(s1.toUpperCase());
String s2 = "java";
System.out.println(s2.toUpperCase());
}
}
Result : JAVA
JAVA
For the first part of question, it has been asked many times and answered many times like here and I don't think we need a better answer there
For the second part of your question,
is s1 is able to perform all the functions that s2 will do?? like to uppercase, append etc..
Absolutely yes! Try "hello".toUpperCase()
String s = "abc"; // creates one String object and one reference variable In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects and one reference variable In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will be placed in the poo
String s1="java" // will store in string pool
String s2=new String("java"); //will store in heap
so s1==s2
results in false
.
if You want s2 also in pool then u have to call s2.intern()
. After that s1==s2
results in true
.