Reputation: 11
I made a simple code like below and I can't understand why it's false when comparing between a subString and a String array's element.
public static void main(String[] args) {
String str = "abcdef";
String str1 = str.substring(0, 4);
String str2 = "abcd";
String[]arr = new String [10];
System.out.println(arr [0 ]+ " - " + str1); //output: null - abcd
arr[0] = str1;
System.out.println("after: " + arr [0] + " - " + str1); //output: after: abcd - abcd
boolean b = str.equals(arr[0]);
System.out.println(b); //output: false
System.out.println(str1.equals(str2)); //output: true
System.out.println(str1.length() + " " + str2.length() + " " + arr[0].length()); //output: 4 4 4
}
str1, str2, arr[0]: they are same in length and character, but the compare's result is difference. that's weird. anyone can know about it, pls share.
Upvotes: 0
Views: 90
Reputation: 683
Over here, you are comparing:
boolean b = str.equals(arr[0]);
but str
is abcdef
while arr[0]
is str1
which is abcd
. Hence they are not equal.
Upvotes: 2
Reputation: 147124
boolean b = str.equals(arr[0]);
Did you mean
boolean b = str1.equals(arr[0]);
or
boolean b = str2.equals(arr[0]);
Or did you think that
String str1 = str.substring(0, 4);
modifies str
?
Upvotes: 0