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
user2420898
  • 89
  • 1
  • 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? – Dawood ibn Kareem Mar 01 '15 at 13:21
  • Also see - http://stackoverflow.com/questions/7520432/java-vs-equals-confusion – bwegs Mar 01 '15 at 13:21

1 Answers1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523