1

Following program returns 3 different values from toCharArray() function. Can anyone tell me why is that ?

public class StrEqual {
    public static void main(String args[]){
        String s1="hi";
        String s2=new String("hi");
        String s3="hi";

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

        }else{
            System.out.println("s1 and s2 not equal");
        }

        if(s1==s3){
            System.out.println("s1 and s3 equal");
        }else
        {
            System.out.println("s1 and s3 not equal");          


        }
        System.out.printf("\n%s",s1.toCharArray());
        System.out.printf("\n%s",s2.toCharArray());
        System.out.printf("\n%s",s3.toCharArray());     
    }//end main
}//end StringComparision
2
  • According to the Javadoc for String, the toCharArray method returns a newly allocated array. So you get a different array every time you call it. Are you asking WHY this method was designed this way? Commented Mar 1, 2015 at 13:21
  • Also see - stackoverflow.com/questions/7520432/java-vs-equals-confusion Commented Mar 1, 2015 at 13:21

1 Answer 1

3

Unlike String objects which are immutable, character arrays are mutable. This implies a requirement that each call of toCharArray must create and return a different object, even if you call it on the same String object.

String a = "a";
char[] a1 = a.toCharArray();
char[] a2 = a.toCharArray();
System.out.println(a1==a2); // Prints "false"

Demo.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.