Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get different results when comparing strings after using different concatenation in Java?

Tags:

java

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));
 }
}
like image 306
Chakravyooh Avatar asked Jun 15 '11 13:06

Chakravyooh


2 Answers

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)

like image 110
king_nak Avatar answered Oct 08 '22 23:10

king_nak


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.

like image 29
Ernest Friedman-Hill Avatar answered Oct 08 '22 22:10

Ernest Friedman-Hill