Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please explain this java code: public class ObjComp public static void main(Stri

ID: 3752682 • Letter: P

Question

Please explain this java code:

public class ObjComp

   public static void main(String[] args) {

        int result = 0;

        ObjComp oc = new ObjComp();

        Object o = oc;

        if (o == oc) {

            result = 1;

        }

        if (o != oc) {

            result = result + 10;

        }

        if (o.equals(oc)) {

            result = result + 100;

        }

        if (oc.equals(o)) {

            result = result + 1000;

        }

        System.out.println("result = " + result);

    }

}

Explanation / Answer

/*If you have any query do comment in the comment section else like the solution*/

Here Object 'o' is an object of Object class which is the base class of all Java classes, its a generic class whose object's value can be object of any other class and this statement 'Object o = oc;' is assigning value of object 'o' to object 'oc' (Object of main class ObjComp).

So the value of 'o' becomes equivalent to 'oc' and hence first if gets executed making value of result variable to 1, now equals function is used to compare two objects and as object 'o' and 'oc' are equal so third if gets executed and add 100 to result making it 101 and similarly fourth if condition will get executed and you will get 1101 as answer.