Java and String object

String object is very popular in Java programming language and today I want to ask a simple question in order to shed light on String object details. Here is the question :

public class StringQuestion {

    public static void main(String[] args) {

        String s1 = new String("selam");
        String s2 = "selam";
        String s3 = "selam" ;

        if (s1 == s2) {
            System.out.println(" s1 == s2");
        }

        if (s2 == s3) {
            System.out.println("s2 == s3");
        }

    }
}

 

We have 3 local variables, s1, s2, and s3 which are String type.  The question is what will be the output of this small program?

The output will be s2 == s3 and let’s explain why and what is the lesson of this tutorial.

First, let’s explain what is the meaning of “s1 == s2”?  It means that s1 and s2 references are connected to the same String object? The answer is “No” they are connected to different String objects because “new String” expression will always create new String object. In other words, Java cannot use same String object based on its content, no shortcuts.

Second, let’s explain why s2 and s3 are equal?  s2 and s3 references are connected to the same String object because Java can use shortcut based on String object’s content.  In that case, content is same “selam”. If you change the content from “selam” to “selam dünya” then s2 and s3 no longer will be equal.

What is the lesson here? The lesson is clear, do not use “new String(…)” expression if you do not have a good reason. If you use”new String(…)” then you remove Java shortcut option based content so that you might be faced with performance problems in the future.

 

No Comments

Post a Comment

Comment
Name
Email
Website