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

3

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

5 Comments

Nothing will be "placed in the pool" by that line because it's already in the pool.
So, please can you tell me the exact difference between these two lines, so i can clear my doubt.
Read my other contributions on this page.
Thanks, I read this difference from SCJP Sun Certified Programmer for Java book, May be they had given incorrect description.
SCJP is not a very reliable source of information. It is both outdated and self-serving, targeted at the silly exam instead of real-life code.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.