i was working on the basic java program and i found verry funny thing which i am sharing with you. foo() gives output (s==s1) = false and bar gives (s==s1) = true.
I want to know why this happens.
public class StringTest
{
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));
}
}
In the latter case, the compiler optimizes the string concatenation. As this can be done at compile time, both reference the same constant string object.
In the former case, the length()
call can't be optimized during compile time. At runtime, a new string object is created, which is not identical to the string constant (but equal to it)
The string catenation in bar()
can be done at compile time, because it's an expression composed of nothing but compile-time constants. Although the length of the String s
is obviously known at compile time, the compiler doesn't know that length()
returns that known value, so it won't be used as a constant.
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