love with java
love with java

Reputation: 123

String comparison unexpected output

In below program i am getting output as false .But as per my understanding when we add two temporary reference variable then result go inside constant pool which does not allow duplicates so we must have gotten output as true here but we are getting false as an output.Can somebody explain me reason behind this?

package com.lara;

public class Man9 
{
    public static void main(String[] args) 
    {
        String s1 = "ja";
        String s2 = "va";
        String s3 = "ja".concat("va");
        String s4 = "java";
        System.out.println(s3==s4);
    }
}

Upvotes: 2

Views: 192

Answers (2)

Alexx
Alexx

Reputation: 3692

You need to use s3.equals(s4), not s3==s4.

Then you will get your true result.

See transcript below

C:\temp>java foo
false
true

C:\temp>type foo.java
public class foo
{
    public static void main(String[] args)
    {
        String s1 = "ja";
        String s2 = "va";
        String s3 = "ja".concat("va");
        String s4 = "java";
        System.out.println(s3==s4);
        System.out.println(s3.equals(s4));
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

Your understanding about string concatenation is incorrect.

Only string constants get interned by default. Now a string constant isn't just a string literal - it can include the concatenation of other constants using the + operator, e.g.

String x = "hello";
String y = "hel" + "lo";
// x == y, as the concatenation has been performed at compile-time

But in your case, you're making a method call - and that's not part of what the Java Language Specification considers when determining constant string expressions.

See section 15.28 of the JLS for what is considered a "constant".

Upvotes: 3

Related Questions