What will be the result of compiling and running this code?

public class Sentence {
    public static void main(String[] args) {
        String str1 = "Zero";
        String str2 = "Zero";

        boolean b1;

        if (str1 == str2)
            b1 = true;
        else
            b1 = false;
        System.out.println(b1);

        String str3 = "Zero";
        String str4 = "Zero1";

        boolean b2;

        if (str3 == str4)
            b2 = true;
        else
            b2 = false;
        System.out.println(b2);
    }
}
Explanation
Class objects must be created explicitly. In the present matter, objects are created implicitly: String str1 = "Zero"; String str2 = "Zero"; leads to the assignment of the second reference variable of the address stored in the first reference variable, because the compiler code optimization. In the abovementioned initialization process variable object is created only once. If there is another variable with the same assignment method and the same the character set (i.e. - "Zero"), the line will be used together. This means that str1==str2 = true(reference to the same memory area). However, the equality of objects in this way is usually not verified. The content of objects is usually checked by the method equals()(eg, str1.equals(str2)), which is redefined with this purpose.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes