#273 String Comparison and String.intern()
What will be printed?
public class Main {
public static final String CONST_S = "const";
public static void main(String[] args) {
String str1 = CONST_S;
String str2 = CONST_S;
String str3 = "abcdefg098";
String str4 = new String(str3);
String str5 = new String("abcdefg098");
String str6 = str5.intern();
System.out.println(str1 == str2 ? "1" : (str1.equals(str2) ? "-1" : ""));
System.out.println(str1 == str3 ? "2" : (str1.equals(str3) ? "-2" : ""));
System.out.println(str4 == str3 ? "3" : (str4.equals(str3) ? "-3" : ""));
System.out.println(str5 == str3 ? "4" : (str5.equals(str3) ? "-4" : ""));
System.out.println(str1 == str5 ? "5" : (str1.equals(str5) ? "-5" : ""));
System.out.println(str1 == str6 ? "6" : (str1.equals(str6) ? "-6" : ""));
System.out.println(str4 == str6 ? "7" : (str4.equals(str6) ? "-7" : ""));
System.out.println(str3 == str6 ? "8" : (str3.equals(str6) ? "-8" : ""));
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor