Monday, January 25, 2010

SCJP Sample questions

Q1. Which of these statements are legal. Select the three correct answers.

A. int arr[][] = new int[5][5];

B. int[]arr[] = new int[5][5];

C. int[] arr = new int[5][];

D. int[] arr = new int[][5];

Correct Answer: A,B,C

02

Class C {

public static void main(String[] args) {

int[]a1[]=new int[3][3]; //3

int a2[4]={3,4,5,6}; //4

int a2[5]; //5

}}

What is the result of attempting to compile and run the program ?

1.compiletime error at lines 3,4,5

2.compiltime error at line 4,5

3.compiletime error at line 3

4.Runtime Exception

5.None of the above

Ans: 2

Explanation:

no value shoud be specified in the rightsidebrackets when constructing an array

Q3. How can you force garbage collection of an object?

A. Garbage collection cannot be forced.
B. Call System.gc().
C. Call System.gc() passing in a reference to the object to be garbage collected.
D. Call Runtime.gc().
E. Set all references to the object to new values(null, for example).

Correct Answer: A

Q4. Consider these classes, defined in separate source files,

public class Test1{

public float aMethod(float a, float b) throws IOException{

}

}
1. public class Test2 extends Test1{
2.
3. }

Which of the following methods would be legal at line 2 in class Test2?

A. float aMethod(float a, float b){}
B. public int aMethod(int a, int b) throws Exception{ }

C. public float aMethod(float a, float b) throws Exception{ }

D. public float aMethod(float p, float q){ }


Correct Answer: B,D

Explanation:

B and D are correct. B is legal as it is an example of method overloading.

A is illegal because it is less accessible than the original method, because method in Test1 is public. And for any overriding method, accessibility must not be more restricted than the original method.

C is illegal because for overriding method, it must not throw checked exception of classess that are not possible for the origincal classes.

Q5. In Java, an abstract class cannot be sub-classed.

A. True

B. False


Correct Answer: B. False
Explanation:

The answer is false, in java abstract class must be sub classessed to make it concrete class.

Q6. TreeMap class is used to implement which collection interface. Select the one correct answer

A. Set
B. SortedSet
C. List
D. Tree
E. SortedMap

Correct Answer: E

Q7. What is the name of collection interface used to maintain unique elements.

_____________________ (Fill-in-the-blank)

Correct Answer: Set interface

Q8. A monitor called mon has 5 threads in its waiting pool; all these waiting threads have the same priority. One of the threads is thread1. How can you notify thread1 so that it alone moves from Waiting state to Ready State?

A. Execute notify(thread1); from within synchronized code of mon.

B. Execute mon.notify(thread1); from synchronized code of any object.

C. Execute thread1.notify(); from synchronized code of any object.

D. Execute thread1.notify(); from any code(synchronized or not) of any object.

E. You cannot specify which thread will get notified.


Correct Answer: E



Explanation:

E is correct, when you call notify() on a monitor, you have no control over which waiting thread gets notified.


Q9. What happens when the following code is compiled and run. Select the one correct answer.

for(int i = 1; i < style=""> for(int j = 3; j >= 1; j--)
assert i!=j : i;

A. The class compiles and runs, but does not print anything.

B. The number 1 gets printed with AssertionError

C. The number 2 gets printed with AssertionError

D. The number 3 gets printed with AssertionError

E. The program generates a compilation error.

Correct Answer: B

Explanation:correct answer is B. When i and j are both 1, assert condition is false, and AssertionError gets generated.

Q10. What is the optput of this code fragment.

1. int X=3; int Y =10;

2. System.out.println(y%x);

A. 0

B. 1

C. 2

D. 3

Correct Answer: B

Explanation:

B is a correct answer. Dividing 10 by 3 gives 3 reminder 1, and this 1 forms the result of the modulo expression. Same rule applies for the negative numbers, you should ignore the signs during calculation part, and simply attach the sign of the Left-hand operand to the result.

Friday, August 15, 2008

Garbage Collection

Java, they say, scores over other languages like C or C++ in memory management. In Java you need not worry about memory management since its garbage collection mechanism takes care of memory leaks. When an object cannot be referenced in a program or if it cannot be accessed anymore, maybe due to its reference being assigned to another object or its reference being set to null, it becomes eligible for garbage collection. The built in garbage collector mechanism then reclaims the memory which had been allocated to the object.

The storage allocated to an object is not recovered unless it is definitely no longer in use. Even though you may not be using an object any longer, you cannot say when, even if at all, it will be collected. Even methods like System.gc() and Runtime.gc() cannot be relied upon in general, since some other thread might prevent the garbage collection thread from running.

An important consequence of the nature of automatic garbage collection is that there can still be memory leaks. If live, accessible references to unneeded objects are allowed to persist in a program, then those objects cannot be garbage collected. Therefore it is better to explicitly assign null to a variable when it is not needed any more. This is particularly important when implementing a collection.

Object lifetime

The lifetime of an object is from the time it is created to the time it is garbage collected. The finalization mechanism does provide a means for resurrecting an object after it is no longer in use and eligible for garbage collection, but finalization is rarely used for this purpose.

Cleaning up

Objects that are created and accessed by local references in a method are eligible for garbage collection when the method terminates, unless references to those objects are exported out of the method. This can occur if a reference is returned or thrown as an exception.

Object finalization

protected void finalize() throws Throwable;

A finalizer can be overridden in a method in a subclass to take appropriate action before the object is destroyed. A finalizer can catch and throw exceptions like other methods. However, any exception thrown but not caught by a finalizer when invoked by the garbage collector is ignored. The finalizer is only called once on an object, regardless of being interrupted by any exception during its execution. In case of finalization failures the object still remains eligible for garbage collection at the discretion of garbage collector unless it has been resurrected.

Finalizer chaining

Finalizers are not implicitly chained like constructors for subclasses, therefore a finalizer in a subclass should explicitly call super class finalizers as its last action.

A finalize method may make the object accessible again, thus avoiding it being garbage collected. One simple technique is to assign its this reference to a static variable, from which it can later be retrieved. Since a finalizer is called only once on an object, an object can be resurrected only once.

finalize () method:

Sometimes an object will need to perform some action when it is destroyed by the garbage collector. For example, if an object is holding some non java resources such as a file handle or window character font, then you might want to make sure these resources are freed before an object is destroyed. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define a finalize() method. This method has the general form:

protected void finalize ();

You might find that the storage for an object never gets released because your program never nears the point of running out of storage. If your program completes and the garbage collector never gets around to releasing the storage for any of your objects, that storage will be returned to the operating system en masse as the program exits. This is a good thing, because garbage collection has some overhead, and if you never do it you never incur that expense.

Finalizers are guaranteed to be called before the memory used by an object is reclaimed. However there is no guarantee that any memory will ever be reclaimed. Hence there is no guarantee that finalize( ) will ever be called. There is a promise that barring catastrophic error conditions, all finalizers will be run on leftover objects when the Java virtual machine exits. However this is likely too late if your program is waiting for a file handle to be released. Besides it is not convincing that it happens anyway. Therefore it is vital that you never rely on a finalizer to free finite resource, such as file handles, that may be needed late by your program.

Sunday, July 6, 2008

SCJP: Flow control, Assertions and Exception Handling

1. One of the most common uses of assertions is to ensure that the program remains in a consistent state. True/False?

Ans: True

2. Assertions checks can be turned on and off at runtime, so that programmers don’t have to think during development whether there checks should remain in the code or removed during deployment. True/False

Ans: True

3. The ‘>>>’ operator performs a signed right shift.

Ans: false

4. Assertions can be enabled or disabled for specific packages. True/False.

Ans: True

5. The <, <=, >, >= operators all return a result of ___ type.

Ans: Boolean

6. The ____ operator tests the type of an object at runtime.

Ans: instanceof

7. When assertions are off, they don’t use system resources and only takes little space in the compiled bytecode, but they can be turned on at runtime whenever the software seems to have a problem. True/False

Ans: True

8. If one operand in an operation is a boolean, the other operand can be of integral type.

Ans: False

9. AssertionError is the immediate subclass of

A) java.lang.RuntimeException

B) java.lang.Throwable

C) java.lang.Exception

D) java.lang.Error

Ans: D

10. Assert is not a java keyword. True/False

Ans: false

11. The command for compiling a sourse code using java’s new assertion feature is as follows ___.

A) javac –source 1.3 filename.java

B) javac –source 1.4 filename.java

C) javac filename.java

D) javac –source assert filename.java

Ans: B

12. The ‘&&’ operator might not always evaluate the right hand operand.

Ans: True

13. Assertions in java is an alternative to exception handling.

Ans: false

14. Assertions should not be used in which of the following cases?

A) to use internal assumptions about the aspect of data structures.

B) To enforce constraints on arguments to provide methods.

C) To check for conditional cases that should never happen, even if you are really sure they can never happen

D) To enforce command- line usage and constraints on arguments to public methods

Ans: D

15. The <<>

Ans: 0

16. It is not possible to enable or disable assertion from the program itself (in source code level). The programmer has to use command line argument java –ea or java –da etc, to indicate whether assertions should be enable or disabled. True/False

Ans: false

17. By default , assertion mechanism is turned off. True/False.

Ans: True

18. Is line 1 indicating a valid assertion statement in the following code?

Public class AssertionTest{

Public void anyMethod(int argument){

Object testObj=null;

//… somehow get testObj object or construct it.

// now check to make sure you have manage to get one.

assert testObj!=null //line 1

}

}

Ans: Yes

19. Each class contains an “assertion status” flag that tells the system whether assertions are enabled for that class.

Ans: True

20. If double x=42.3 then the value of “x%10” will be ___.

Ans: 2.3

21. Assert expression should not cause side effects. True/False?

Ans: True

22. If int a=35 then the value of “a>>2” will be ___

Ans: 8

23. The “!” operator inverts the value of a Boolean expression.

Ans: True

24. An assertion is a conditional expression that should evaluate to ___, if and only if your code is working correctly.

A) true

B) false

C) void

D) null

Ans: A

25. For the XOR operation, a 1 bit results only if exactly one operand bit is 1.

Ans: True

SCJP: Declarations and Access Control

1. Garbage collection is performed by a low priority thread.
Ans: True

2. Garbage collection can not be forced to happen.
Ans: True

3. The following definition for main method (an entry point of a java application) is valid.

public static void Main(String args[])

Ans: False

4. The “null” is a reserved java keyword.

Ans: True

5. The following variable declaration is valid in java.

byte b=128;

Ans: False

6. The “char” type in java is 16 bit and signed.

Ans: False

7. Which method is used to request for garbage collection?

Ans: System.gc()

8. The default value of Boolean in java is ___.

Ans: false

9. The garbage collector will usually call on object’s ___ method just before the object is garbage collected.

Ans: finalize

10. The following declaration of array type in java is correct.

int number[]=new number[12];

Ans: false

SCJP: Garbage Collection

  1. All Java objects are created on ____ (heap/stack).
    Ans: heap
  2. A private method may be overridden by a private, friendly, ____ , or public method.
    Ans: protected
  3. A ____ class may not be sub classed.
    Ans: final
  4. An ___ class provides a way to defer implementation to subclasses.
    Ans: abstract
  5. Following is the correct declaration of method in java.
    Ans: False
  6. The following lines of code inside a method are valid(i.e will compile):
    final MyCar myCar =new MyCar(“BMW”);
    myCar=new Car(“Merc”);
    Ans: False
  7. In java a “protected” variable is more accessible than a default variable(variable with no access modifier).
    Ans: True
  8. A constant variable in java is marked ___.
    Ans: final
  9. A ___ variable is not stored as part of its object’s persistent state
    Ans: transient
  10. The “native” modifier applies only to methods while “volatile” applies only to variables.
    Ans: True

SCJP: Language Fundamentals

  1. An interface type can be converted to any other interface type.
    Ans: False
  2. A ‘char’ type can be assigned to a double variable(without casting).
    Ans: True
  3. A boolean may be converted to integer and vice-versa by casting.
    Ans: False
  4. In an expression, which has 2 operands, one of which is a long and the other is a float the result will be of ____ type.
    Ans: float
  5. Implicitly converting an interface type to a class type is never allowed.
    Ans: False
  6. byte b=(byte)256;
    System.out.println(b);
    Value of b printed is ___.
    Ans: 0
  7. For unary operators, if the operands is a byte, char or a short, it is converted to __.
    Ans: int
  8. An array can be converted to an object of the class Object without casting.
    Ans: True
  9. An array of integers can be converted to an array of bytes by casting.
    Ans: False
  10. A subclass object can be assigned to a super class type without casting.
    Ans: True

SCJP: Fundamental Classes in java.Lang Package

  1. A ____ object can store and retrieve “value” objects indexed by “key” object.
    Ans: Hashtable
  2. Wrapper class objects contain mutable values. True/False?
    Ans: False
  3. A Vector can hold object references or primitives types.
    Ans: False
  4. Hashtable class implements which of the following interfaces?
    Ans: Map
  5. String s1=new String(“MyString”);
    String s2=new String(“MyString”);
    s1==s2 will return ___.
    Ans: False
  6. Float.NaN or Double.NaN refers to ___
    Ans: Not a number
  7. The java.lang.System is a ___ class.
    Ans: final
  8. The ___ class is a wrapper around int data type in java.
    Ans: Integer
  9. java.lang.Double is a concrete subclass of abstract class java.lang.Number. True/False
    Ans:True
  10. What happens when you try to compile and run the following code snippet?
    public class Wrapper{
    public static void main(String []a){
    String s=”15.25”;
    try{
    int number=Integer.parseInt(s);//line 1
    System.out.println(number);//line 2
    }
    catch(NumberFormatException nfe){
    System.out.println(“sorry”);
    }
    catch(Exception e){ }
    }
    }
    A) It will compile fine and display 15 when run.
    B) It will compile fine and display Sorry when run.
    C) It will not compile
    D) It will compile fine nothing will be displayed when run
    Ans: B
  11. The java.lang.Math class has ___ constructor.
    A) public
    B) private
    C) protected
    Ans: B
  12. A Vector maintains object references in the order they were added.
    Ans: True
  13. The String class represents a mutable string
    Ans: False
  14. The parent class of both Integer and Character class is Number class
    Ans: False
  15. What happens when you try to compile and run the following code snippet?
    public class WrapChar{
    public static void main(String []a){
    Character wrapChar=new Character(“c”);//line1
    System.out.println(wrapChar);//line 2
    }
    }
    A) Compile time error at line 1
    B) Compile time error at line 2
    C) Compile fine and display c when run
    D) Compile fine but throws RuntimeException
    Ans: A