Java Strings
If you are unfamiliar with Java or interested in a refresher, use this link.
In this blog we look at some quirky dealings with Java Strings. We'll be using concepts of Java variables, data-types and operators and especially Strings.
The following code constructs two strings s1 and s2. When they are compared, their contents are identical.
String s1 = "12345";
String s2 = "123";
s2 += "45";
if(s1 == s2) {
System.out.println(s1 + " equals " + s2);
} else {
System.out.println(s1 + " does NOT equal " + s2);
}
Strangely, this code reports that the strings are not equal:
12345 does NOT equal 12345
Why is that? How do we fix this? Notice the change in bold below.
String s1 = "12345";
String s2 = "123";
s2 += "45";
if(s1.equals(s2)) {
System.out.println(s1 + " equals " + s2);
} else {
System.out.println(s1 + " does NOT equal " + s2);
}
Now it looks ok:
12345 equals 12345
What's going on here? Do you think there are other Java types have this 'issue' as well?
Once you've figured it out, let's explore characters in Java
Once you've figured it out, let's explore characters in Java
Java Object and Classes
ReplyDeletevariables
ReplyDelete