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

Saturday, July 5, 2008

SCJP: Operators

Subclasses of the RuntimeException class are called ___ (checked/unchecked) exceptions. Unchecked

Every try block should have a corresponding catch block. (True/False)
False

The ___ statement causes the current iteration of the loop to be skipprd, the next iteration starts.
Continue

What will be the values of “a” and “b” when the following for loop completes?
for(a=1,b=4; a
a=2, b=3

The arguments to case labels of a switch statement can not be variables. (True/False)
True

A local variable of an enclosing context can be accessed by an inner class only if it is ____.
Final

An exception can be explicitly thrown using the ___ statement.
Throw

An Inner class can be declared private.
True

Inner classes may not declare ___ initializers/members unless they are compile time constants.
Static

The if statement takes an argument of __ data type.
Boolean

Thursday, July 3, 2008

SCJP: overriding, overloading methods questions

1. Anonymous inner classes cant have an explicit constructor.
True

2. The return type of a Constructor in java is “void”.
False

3. Java includes a special reference value called ____, which is used inside any method to refer to the current object.
this

4. The ____ operator creates a single instance of a named class and and returns a reference to the object.
new

  1. To call another constructor from a constructor (of the same class), the ___ keyword is used This

6. In java it is possible and often desirable to create more than one method with the same name, but different parameter lists. This is called method ___.
Overloading

  1. A static inner class doesn’t have any refrence to an enclosing instance. True

8. An interface in java can extend another interface.
True

  1. Constructors are inherited by subclasses. False

10. An overriding method can be defined in the same class as the method it overrides.
False

SCJP: Questions on Thread

  1. ___ is the normal priority value of a Thread.

5

  1. ___ method waits until the thread on which it is called terminates.

join

  1. The ____ method returns true if the thread upon which it is called is still running.

isAlive

  1. A thread can attain a lock on an object only if the class of that object implements Runnable. True/False?

False.

  1. The wait() method can not be invoked from synchronized code. True/False

False

  1. A class lock is obtained on synchronizing the ___ methods of a class.

static

  1. A dead thread cannot be stated again. True/False?

True

  1. Threads in Java are platform dependent. True/False

True

  1. when we invoke notify(), it is not possible to specify which thread is to be notified. True/False?

True

  1. sleep() method declares ___ in its throw clause.

InterruptedException

Wednesday, July 2, 2008

Collection Framework Questions

  1. Equals () method of java.lang.Object class compares whether two object references of this class are aliases of each other. True/False

True

Explanation: equals() method of java.lang.Object class compares whether two objects are same or aliases of each other, as its implementation compares the objects with(==) operator. Not to confuse. This equals () method is overridden in java.lang.String class to show different behavior by comparing the values of two strings not the references.

  1. Set, List and Map extend java.util.Collection interface. True/False?

False

Explanation: Set and list extend java.util.Collection interface, but Map does not.

  1. Java collections generally have the ability to extend to accommodate as many elements of objects as necessary. True/False.

True

Explanation: Collections in java can hold as many object references as the size of the collections can grow dynamically.

  1. Java collections can hold only references to objects not actual objects. True/False?

True

Explanation: Collections in java are container classes that hold the object references, not the actual objects.

  1. Dictionary is the abstract class that behaves similar to the interface____. A) Set B) List C) Map D) Collection

Map

Explanation: The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value. Given a Dictionary and a key, the associated element can be looked up. Any non-null object can be used as a key and as a value. This class is obsolete now. New implementation should implement the map interface, rather than extending this class.

  1. equals() method of java.lang.String class compares whether two references are indication the same string object while the equality operator (= =) compares whether the value of two strings are same or not. True/False

False

Explanation: Quite the opposite; equals method of java.lang.String class compares whether the value of two strings are same or not; while (= =) whether two references are indication the same string object.

  1. Java collections can hold primitives values as well as object references. True/False.

False

Explanation: Collections in java can only hold object references not primitive values. But arrays in java can hold both primitive values and object references.

  1. hashCode() is a non-static methods of java.lang.Object class. True/False?

True

Explanation: Public int hashCode() resides in Object class; every java class inherits this method.

  1. hashCode() of java.lang.Object produces a hash code of type ___ for an object. A) String B) int C)double D)long

int

Explanation: hashCode() produces a hash code of type int for an object that is typically used as an offset from the start of the memory that has been allocated to that object.

10. which two of the following statements are true about List in java? A) A list id ordered but rejects duplicate values. B) A List is ordered and accepts duplicate values. C) A list has no special order but accepts duplicate values. D) A list has no special order and rejects duplicate values.

B

11 _____ method is used of java.lang.String to check equality between two string objects ignoring the case of the string characters (No extra space space, parentheses or arguments are required while typing the method name)

equalsIgnoreCase

12) There are three main types of collections in Java: Set, List and ___.

Map

Monday, June 30, 2008

Tips N Tricks



My title
Tips N Tricks

1. Just reading about the concepts and seeing examples will not make things clear. Make a small

example of your own to test every new concept/rule you learn. This will help you understand it

better. Also, alter the example and experiment with different possibilities. You will learn and

retain much deeper if you follow this process.

Lets say, you read about the rule that static methods cannot be overridden. It is not very clear

what will happen if you attempt to override a static method, whether this will cause a compiler

error or not.

To explore this, you can make an example similar to this one.

class Base{

static void f() { System.out.println("base"); }}

class Derived extends Base{

static void f() { System.out.println("derived"); }

public static void main(String args[]){

Base base=new Derived();

base.f();

}

}

Now try to compile, there are no errors. So that means it is not illegal to have the same static

method in the base and derived class. But when you invoke the method, the actual method

invoked is that of the base class. This is because the method invoked depends on the type of

the reference variable. Thats why you say that overriding does not happen in this case. If this

had been a non static method, the method invoked would have been the derived one. Now

things are clear to you.

Once this concept is clear, you can start trying different possibilities.

- What happens if you override a static method as non-static or vice versa

- What will happen if you try to declare a static method abstract

- Can a static method be synchronized.

You can think of many options like this. Make small variations to the program and try out all of

them.

Instead of learning just one concept, you will get a deep understanding of many related

concepts.

2. Once you have gone through all the concepts once, start taking as many mock exams as

possible to test your knowledge. However much you have prepared, you will still find weak

areas where you need to concentrate and important points which you missed out. After taking

each exam, note down the mistakes you made. On the day before the exam, you can go

through them once more to make sure that you are clear in those now.

3. The objective on Garbage collection will have questions asking how many objects are eligible

for garbage collection at a particular point in the program. The answers to such questions

cannot be verified with the help of examples because you cannot force the garbage collector to

run. So attempt as many questions as possible on this topic from various mock exams,

compare your answers to test your knowledge.

4. Inner classes is one of the most confusing sections, you need to memorize the correct syntax,

ways of instantiation and access rules. Even questions from other objectives might be using

inner classes. So try to practice a lot in this area.

Anonymous inner class are especially prone to errors.

Watch out for small syntax errors like the missing semicolon at the end of this anonymous

inner class defined inside a method argument.

t.doSomething(new AnotherClass(3) {

public void f(){

System.out.println("something");

}

})

5. Threads and Garbage collection are 2 topics in Java which have some platform/implementation

dependent features. You should be able to clearly differentiate betweeen such behaviour and

features which do follow the rules and hence are predictable.

For example, garbage collection algorithm varies between different implementations. Garbage

collection cannot be forced to happen, you can only request for it. So there are no guarantees

here. Now lets see what you can be sure about. The finalize() method of an object will be

surely called once before it is garbage collected. This rule will not be violated, whatever the

implementation is like. But again, you need to remember that finalize() might never be

invoked on the object because the garbage collector might never run during the program

execution.