-1

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..

Kamlesh Arya
  • 4,864
  • 3
  • 21
  • 28
rad123
  • 1
  • 3

4 Answers4

1

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

Suprabhat Biswal
  • 3,033
  • 1
  • 21
  • 29
0

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()

Community
  • 1
  • 1
senseiwu
  • 5,001
  • 5
  • 26
  • 47
0

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

astack
  • 3,837
  • 7
  • 22
  • 21
0
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.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
Dwijendra
  • 61
  • 1
  • 4