public class Foo {
public static void main(String[] args) {
foo();
bar();
}
public static void foo() {
String s = "str4";
String s1 = "str" + s.length();
System.out.println("(s==s1)" + (s1 == s));
}
public static void bar() {
String s = "str4";
String s1 = "str" + "4";
System.out.println("(s==s1)" + (s1 == s));
}
}
OUTPUT
(s==s1)false
(s==s1)true
At String s1 = "str" + s.length(); the value of s1=str4 but it turns out to be false at next sysout statement during double equal (==) check
*/
That's because "str" + "4"
is compiled as "str4"
.
String s = "str4";
String s1 = "str" + "4";
For the compiler, it will be:
String s = "str4";
String s1 = "str4";
Note that "str4"
is a literal String and it will be stored in String pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With