Wednesday, May 14, 2014

What is the output for the below piece of Code? #1

Leave a Comment

Question :


public class StringTest {
 

    public static void main(String args[])

    {

        String s = "sachin";

        s.concat("tendulkar");

        System.out.println(s);

    }

}


Output:

sachin

Because String is immutable in Java.


Question :


public class StringTest {

  

    public static void main(String args[])

    {

        String s = "sachin";

        s=s.concat("tendulkar");

        System.out.println(s);

    }

}


Output:

sachintendulkar

Here a new string "sachintendulkar" is created and 's' is made as a reference to this new string.
String object "sachin" still exist in the string constant pool.



0 comments:

Post a Comment