public class Test { public static void main(String[] args) { String s1 = "hello"; String s2 = new String("hello"); s2 = s2.intern(); System.out.println(s1 == s2); } } Answer: true We know that the intern() method will return the String object reference from the string pool since we assign it back to s2 and now both s1 and s2 are having the same reference. It means that s1 and s2 references point to the same object.
public class Test { public static void main(String[] args) { String s1 = new String("obify"); String s2 = new String("obify"); System.out.println(s1 = s2); } } Answer: The above program prints “obify” because we are assigning s2 String to s1. Don’t get confused with == comparison operator.
public class Test { public static void main(String[] args) { String s1 = "abc"; StringBuffer s2 = new StringBuffer(s1); System.out.println(s1.equals(s2)); } } Answer: false It will print false because s2 is not of type String. If you will look at the equals method implementation in the String class, you will find a check using instanceof operator to check if the type of passed object is String? If not, then return false.
public class Test { public static void main(String[] args) { String str = null; System.out.println(str.valueOf(10)); } } Answer:
This program will print 10 in the console.
public class Test { public static void main(String[] args) { String s = new String("5"); System.out.println(1 + 10 + s + 1 + 10); } } Answer:
public class StrEqual { public static void main(String[] args) { String s1 = "hello"; String s2 = new String("hello"); String s3 = "hello"; if (s1 == s2) { System.out.println("s1 and s2 equal"); } else { System.out.println("s1 and s2 not equal"); } if (s1 == s3) { System.out.println("s1 and s3 equal"); } else { System.out.println("s1 and s3 not equal"); } } } Answer:
s1 and s2 not equal
s1 and s3 equal
String s1 = new String("obify"); String s2 = new String("obify"); As we have used a new keyword to create String objects so there are two objects will be created and they will be stored in the heap memory.
String s1 = new String("obify"); String s2 = "obify"; Here, two string objects will be created. An object created using a new operator(s1) will be stored in the heap memory. The object created using a string literal(s2) is stored in the string constant pool.