Swanand
Swanand

Reputation: 117

Evaluation of two Strings in java

I would like to know why the second System.out.println statement prints false and not true. I believe the strings would be cached and both s1 and s3 point to the same string object, then why would false be printed when both strings have same value.

 String s="hello";
 String s1="hello5";
 String s2="hello"+5;
 String s3="hello"+s.length();
 System.out.println(s1==s2);//prints true
 System.out.println(s1==s3); //I know equals method would print true

Upvotes: 1

Views: 188

Answers (4)

TheLostMind
TheLostMind

Reputation: 36304

The compiler replaces "hello" + 5 with "hello5" during compile time itself (which is valid because both are constants) where as call to String#length() is done at runtime (And hence the compiler cannot use "hello5" directly).

Byte code :

         0: ldc           #19                 // String hello ==> s
         2: astore_1
         3: ldc           #21                 // String hello5 ==> s1
         5: astore_2
         6: ldc           #21                 // String hello5 ===> s2 <==
         8: astore_3
         9: new           #23                 // class java/lang/StringBuilder
        12: dup
        13: ldc           #19                 // String hello 
        15: invokespecial #25                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
        18: aload_1
        19: invokevirtual #28                 // Method java/lang/String.length:()I
        22: invokevirtual #34                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
        25: invokevirtual #38                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;

Upvotes: 3

Ankit Deshpande
Ankit Deshpande

Reputation: 3604

String s3="hello"+s.length();

Computed at runtime, because until and unless the length() function isn't evaluated, it's value will remain unknown.

String Literal Pool has a major role to play in this.
s1 and s2 will refer to the same String in the string literal pool.

This will return false:

String s1 = "hello";
String s2 = new String("hello");// creates new string in pool


Use of equals() is better when checking for equality in strings and objects. For objects you have to override equals() method,because by default equals() and == have same nature.

Upvotes: 1

RamanSB
RamanSB

Reputation: 1172

The second print statement is false, because at runtime the two Strings s1 and s3 point to different locations of memory.

E.g. if we have two strings:

   String s1 = "Hi";
   String s2 = "Hi".trim();
   System.out.println(s1==s2); //Yields false

Upvotes: 1

SatyaTNV
SatyaTNV

Reputation: 4135

 String s2="hello"+5;
 String s3="hello"+s.length();
 System.out.println(s1==s2);//prints true
 System.out.println(s1==s3); //I know equals method would print true

the second SOP checks at runtime not at compile time.

Upvotes: 4

Related Questions