What will be printed after the following code is executed?

public class Main {    
    public static void main(String[] args) {
        String strA = "text";
        String strB = "text";
        strA += "1";
        strB += "1";
        System.out.println(strA != strB);
        strA = "text1";
        strB = "text1";
        System.out.println(strA != strB);
    }
}
Explanation
First of all, it is important to remember that string literals in Java are, in fact, objects (String). At the same time, if the same string literal is met several times in the program, then the same object will correspond to each literal. Therefore, strA == strB in the second case (false will be printed out).

Second of all, strings (String) in Java are immutable objects. Therefore, when another string is "concatenated" with object strA, another object, containing "text1" is actually created. Consequently, strA != strB, and true is printed out in the first case.

Actually, strA += "1" command results in strA = new StringBuilder().append(strA).append("1").toString(); And if this command is executed twice, two different objects will be created, even though they will have the same content.

@ericheatonu06 checked! should be right explanation

2018 Feb 2, 5:24:52 PM

is surely true, true?

2018 Jan 2, 8:56:45 PM

String strA = "text"; String strB = "text"; strA += "1"; strB += "1"; System.out.println(strA != strB); strA = "text1"; strB = "text1"; System.out.println(strA != strB);

2018 Jan 2, 8:56:31 PM

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести