Saturday, August 9, 2008

Accessor Types Public and Private

Question 1

Given :

public class Hello{
private int i = j;
private int j = 10;
public static void main(String args[]) {
System.out.println((new Hello()).i); }
}

Choose

1. Compiler error complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing.
3. No error - The output is 0;
4. No error - The output is 10;

Answer is 2. It is because i is a private variable of Hello. Hence it cannot be accessed directly.

Question 2


Given :

public class Hello {
private int i = giveJ();
private int j = 10;
private int giveJ()
{ return j;
}
public static void main(String args[])
{ System.out.println((new Hello()).i);
}
}

Choose :
1. Compiler error complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing. .
3. No Compilation error - The output is 0;
4. No Compilation error - The output is 10;


Answer 2 is correct. We cannot assign a value to instance varaible by calling the method.

1 comment:

Bala said...

As far as Question 2 is concerned
you are wrong.
The answer is 3.Since the main method is in the same class it returns 0;
If the main method defined in the different class the answer is 1

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google