CodePlex Challenge #3 - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

CodePlex Challenge #3


Challenge Statement


Predict the Output with proper reasons

Problem Statement 1:

Problem Statement 2:






Right Answer

Problem Statement 1: Save Mother Earth to save ourselves
Problem Statement 2: true
                                    false

Reasoning

Problem Statement 1:

The static method is not a member of any object, rather it is a member of a class itself. Hence when b1, which indeed is a null object , calls the static method, the static method gets called only with the type of the object, not with the value, ensuring that the static method gets called in a static way. 

If you decompile the .class file of TestBox class, you will see that instead of newBox, the print method is being called as Box.print();

Problem Statement 2:


When an Integer object is created through autoboxing or Integer.valueOf (n) method, it pools -128 to 127 (both inclusive) in a cache. Hence multiple objects having values within this range will be served from a cache. So first and second these two objects have same reference in cache, hence we are getting the output as true. But any values outside this range will never be cached, so two different objects third and fourth, will have two different referenced. So their equality will never succeed.


Right Answer Given By

Meet Mr. Jagannath Kundu

4 comments:

  1. Problem statement 1 : NullPointerException, as object reference b is null, and passed as the parameter to b1.getInstance(), which returns a null object reference, stored in newBox. So newBox being a null reference, will yield NullPointerException at newBox.print().

    Problem statement 2 : true
    false
    If a number upto 127 on the heap is already referenced in the program, a second reference will point to the same location in memory. The "==" operator checks for equality in memory reference. So it returns true in case of 127. But after that, it returns false. Same in the case of 137.

    ReplyDelete
  2. problem 1 Output:-
    (Save mother earth to save ourselves) because of print method is static.static method present only one copy in memory.static method execution is depends on reference type not Object type.

    Problem 2 OutPut:-
    (True,False) first and Second after autoboxing only one object created because of the is given range -128 to 127.that's why both are refer to the same memory location and == Operator returns true.third and fourth after autoboxing two object created because of no caching is happend. thats whay both are refer to the different memory location and == Operator return false

    ReplyDelete