Tuesday, 17 April 2012

Few OCJP/SCJP Questions and Answers


1. public class LocalTime {
public static void main(String [] args) {
int second;
int min; // second & min only declared but not initialized
System.out.println("Welcome");
second = 180; // Initialize the variable
System.out.println("Minute " + min);
}
}

Ans : Code fails in compilation .Local variable should be initialize before they used in the method/block. Here “min” variable is no where used in the program..

2. public class LocalTest {
public static void main(String [] args) {
int a;
if (args[0] != null) { // assume you know this will
// always be true

a = 7; // compiler can't tell that this
//  statement will run
}
int b = a; //Compiler will choke here
}
}
Ans: Compilation Error. The variable “a” is only initialize in the loop. When JVM comes from the loop, it can not find the value of “a” .

3. class Foo {
static int size = 7;
static void changeIt(int size) {
size = size + 100;
System.out.println("size in changeIt is " + size);
}
public static void main (String [] args) {
Foo f = new Foo();
System.out.println("size = " + size);
changeIt(size);
System.out.println("size after changeIt is " + size);
}
}
o/p :
size = 7
size in changeIt is 107
size after changeIt is 7

4. class TestWrapper {
public static void main(String args[]) {
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");
}
}

o/p:
different objects
meaningfully equal

5 .
class TestWrapper {
public static void main(String args[]) {
Integer i2 = 20;
Integer i3 = 20;
if(i2 == i3) System.out.println("same object");
if(i2.equals(i3)) System.out.println("meaningfully equal");
}
}

o/p :
same object
meaningfully equal

NB :For Short & Integer range from -128 to 127. When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.

6. class Boxing {
static Integer x;
public static void main(String [] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
} }

0/p: It will throw NullPointerException at Runtime bacause when JVM tries to invoke dostuff(x) method, x does not have the value to outbox.

NB : wrapper reference variables can be null. You have to take care for code that appears to be doing safe primitive operations, but that could throw a NullPointerException:


7. class LongTest {
static void go(int x) { System.out.print("int "); }
static void go(long x) { System.out.print("long "); }
static void go(double x) { System.out.print("double "); }
public static void main(String [] args) {
byte b = 5;
short s = 5;
long l = 5;
float f = 5.0f;
go(b);
go(s);
go(l);
go(f);
}
}
Which produces the output:
int int long double

8. class Dog {
public static void main(String [] args) {
Dog d = new Dog();
d.test(new Long(5)); // can't widen an Integer
// to a Long
}
void test(Double x) { }
}


O/P :  Compilation Fails.
Wrapper class can not widen with one another.



9. class TryWiden {
static void go(Object o) {
Integer b2 = (Integer) o; // ok - it's a Integer object
System.out.println(b2);
}
public static void main(String [] args) {
Integer b = 10;
go(b); // can this integer turn into an Object ?
}
}

o/p: 10

Since Object is the parent class of all wrapper classes(here Byte),so it can widen to Object.

10.
class MixerTest {
MixerTest() { }
MixerTest( MixerTest m) { m1 = m; }
MixerTest m1;
public static void main(String[] args) {
MixerTest m2 = new MixerTest();
MixerTest m3 = new MixerTest(m2); m3.go();
MixerTest m4 = m3.m1; m4.go();
MixerTest m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}

what will be the o/p ?

o/p : hi hi, followed by an exception
Because m2 object’s m1 instance variable is never initialized, so when m5 tries to use it a NullPointerException is thrown


11. class Bird {
{ System.out.print("b1 "); }
public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}

o/p : r1 r4 pre b1 b2 r3 r2 hawk
Static init blocks are executed at class loading time, instance init blocks run
right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down

12. public class Make {
static int make = 7;
public static void main(String[] args) {
new Make().go(make);
System.out.print(" " + make);
}
void go(int make) {
make++;
for(int make = 3; ouch < 6; ouch++)
;
System.out.print(" " + make);
}
}

o/p : Compilation fails because the variable “make” is declare again in for loop

13. class Dozens {
int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
}
public class Mango{
public static void main(String[] args) {
Dozens [] da = new Dozens[3];
da[0] = new Dozens();
Dozens d = new Dozens();
da[1] = d;
d = null;
da[1] = null;
// do stuff
}
}

question : How many objects this program will create & how many are eligible for garbage collection ?

Ans : 5 objects are created & 2 objects are eligible for Garbage Collection

Monday, 16 April 2012

Explicitly Make Objects Eligible for Garbage Collection



As all java people know how Memory Management & Garbage Collection work in java.
As of Summary: Garbage collector revolves around making sure that the heap has as
much free space as possible. Objects are created in the heap. When JVM(Java Virtual Machine) senses that memory is running low, at that time it calls garbage collector to remove/delete the unused objects that are not needed any more from memory(heap)...

Explicitly Makes Objects Eligible for Collection

(a). Nulling a Reference:
  1. An object becomes eligible for garbage collection when there are no more reachable references to it. To remove a reference to an object is to set the reference variable that refers to the object to null.

Program code :

public class RemoveReference {
public static void main(String [] args) {

StringBuffer sb = new StringBuffer("Reference");

System.out.println(sb); 
// Here the StringBuffer object is not eligible for collection

sb = null;
// Now the StringBuffer object is eligible for collection
}
}

(b). Reassigning a Reference Variable:

  1. We can also decouple a reference variable from an object by setting the reference variable to refer to another object.
  1. The objects created in the method are eligible for garbage collection ,once the method has returned.
  2. If an object is returned from the method, its reference might be assigned to a reference variable in the method that called it; hence, it will not be eligible for collection

Program Code:

import java.util.Date;
class ReassignReference {
public static void main(String [] args) {
Date d = getDate(); // Reference return from the method

StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("goodbye");

System.out.println(s1);
// At this point the StringBuffer "hello" is not eligible

s1 = s2; // Redirects s1 to refer to the "goodbye" object
// Now the StringBuffer "hello" is eligible for collection

}
public static Date getDate() {
Date d2 = new Date();

StringBuffer now = new StringBuffer(d2.toString());
// object eligible to garbage collector even we don't set the object as null explicitly.

System.out.println(now);

return d2; // Reference Return , not eligible for garbage collector
}
}

(c) .Isolating a Reference

1.There is another way in which objects can become eligible for garbage collection,even if they still have valid references! We call this scenario "islands of isolation."

Program Code :

public class Island {
Island i;
public static void main(String [] args) {
Island i2 = new Island();
Island i3 = new Island();
Island i4 = new Island();

i2.i = i3; // i2 refers to i3
i3.i = i4; // i3 refers to i4
i4.i = i2; // i4 refers to i2

i2 = null;
i3 = null;
i4 = null;
// do complicated, memory intensive stuff
}

}


When the code reaches // do complicated, the three Island objects (previously known as i2, i3, and i4) have instance variables so that they refer to each other, but their links to the outside world (i2, i3, and i4) have been null. These three objects are eligible for garbage collection.

(d) Forcing Garbage Collection

  1. Garbage collection cannot be forced by a programmer.
  2. However, Java provides some methods that allow you to request that the JVM perform garbage collection.
  3. We can call garbage collector using Runtime java classes.
Ex: Runtime.getRuntime().gc();
Ex: System.gc();