Saturday 28 May 2011

Restrictions on clone method

There are couple of restrictions on clone methods:
  • It is a protected method and can only be called from within the same class or the module that contains the class.
  • We can only clone objects which are declared to implement the Cloneable interface.
  • Objects that cannot be cloned throw the CloneNotSupportedException.

Environment variables in java

Unlike C or C++, there is no getEnv() method in Java.

Part of the reason is that Java could conceivably be run on a platform that does not support the concept of environment variables. The expected way to pass environment-variable-like values to a Java application is with the -Dname=value syntax seen a few times in earlier chapters. Using the -D syntax on the java command line effectively adds the specified name and value to the list of system properties. Therefore, if you need to send a system environment variable named SomeEnvVar to your Java code, you can include it on the command line like this:

java -Dsome.env.variable=$SomeEnvVar YourClass (Unix/Linux)

or

java -Dsome.env.variable=%SomeEnvVar% YourClass (Windows) 


Then you access the new system property as follows:

String some_value = System.getProperty ("some.env.variable"); 

Obviously, you can name the system property anything you want.



Wednesday 25 May 2011

Common Class Loading Issues (java)

  • ClassNotFoundException
    • Thrown when an application tries to explicitly load a class using class name string and class (.class file) is not found in the classpath.
      Eg. Thrown when an application tries to load a class through its string name using:
      • The forName method in Class.
      • The findSystemClass method in ClassLoader.
      • The loadClass method in ClassLoader.

      By throwing a ClassNotFoundException, the class loader informs us that the bytecode required to define the class is not present in the locations where the class loader is looking for it. There may be classes in a system that cannot be seen by a class loader. This is because a class loader only sees classes that are loaded by itself or loaded by class loaders to which it has a reference. In the class loading delegation model, the classes that are visible to a class loader are those that are loaded by itself or loaded by its parent – in other words, a class loader cannot look down.
    • Can be easily checked by enabling verbose:class JVM argument

  • NoClassDefFoundError
    • Thrown if the ClassLoader instance tries to implicitly load in the definition of a class and no definition of the class could be found.
      The searched for class definition existed when the currently executing class was compiled but the definition can no longer be found. Essentially this means that a NoClassDefFoundError is thrown as a result of a unsuccessful implicit class load.
  • ClassCastException
    • Thrown as a result of incompatible types being found in a type comparison. It indicates that the code has attempted to cast an object to a subclass of which it is not an instance. (remember ClassLoader Namespace)
    • Two classes of the same fully qualified name are not equal to each other if they are loaded by different ClassLoaders. They cannot be cast to each other and such operations would result in a ClassCastException
  • UnsatisfiedLinkError
    It occurs during the resolving stage of the linking phase when a program tries to load an absent or misplaced native library.
  • ClassCircularityError
    It is thrown if a class if a class or interface could not be loaded because it would be its own superclass or superinterface.
  • ClassFormatError
    • This exception is thrown during the verification stage of the linking phase of class loading. The binary data can be malformed if the bytecodes have been changed --if the major or minor number has been changed, for instance. This could occur if the bytecodes had been deliberately hacked, for example, or if an error had occurred when transferring the class file over a network.
    • The only way to fix this problem is to obtain a corrected copy of the bytecodes, possibly by recompiling.


Principles of ClassLoader Operation

Delegation Principal
  • According to this principle, if a particular class is not loaded already, the classloaders delegate the requests to load that class to their parent classloaders.
    Suppose your class MyApp is being loaded:

    public class MyApp{
    Vector vec = new Vector
    }
    Since the System-Classpath classloader loaded the MyApp class, it first asks its parent, the extension classloader to load the class. The extension classloader asks the Bootstrap classloader to load java.util.Vector. Since java.util.Vector is a J2SE class, the bootstrap classloader loads it and returns.

Visibility Principal
  • According to this principle, Classes loaded by parent classloaders are visible to child classloaders but not vice versa
  • For classes loaded by ClassLoader X, classes A, B and X are visible, but not class Y. Sibling classloaders cannot see each other’s classes.

Uniqueness Principal
  • According to this principle, when a classloader loads a class, the child classloaders in the hierarchy will never reload the class. This follows from the delegation principle since a classloader always delegates class loading to its parents. The child classloader will load it (or try to load it) only if the parent hierarchy fails to load the class. Thus the uniqueness of the class is maintained. An interesting scenario emerges when both parent and child classloaders load the same

Static class loading vs Dynamic class loading

There are two ways in which classes can be loaded -- explicitly or dynamic or implicitly or static-- with subtle variations between the two.
Static Class Loading
Classes are statically loaded with Java’s 'new' operator.
class MyClass 
{
public static void main(String args[])
{
Car c = new Car();
}
}


A NoClassDefFoundException is thrown if a class is referenced with Java’s 'new' operator (i.e. static loading) but the runtime system cannot find the referenced class.

Dynamic class loading
Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
we can load classes dynamically by...
Class.forName (String className); //static method which returns a Class

The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.
  class.newInstance (); //A non-static method, which creates an instance of 
//a class (i.e. creates an object).

Jeep myJeep = null ;//myClassName should be read from a properties file or 
                     //Constants interface.
                     //stay away from hard coding values in your program. 
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);

Summary
Explicit class loading occurs when a class is loaded using one of the following method calls:
  • cl.loadClass() (where cl is an instance of java.lang.ClassLoader)
  • Class.forName() (the starting class loader is the defining class loader of the current class)
When one of these methods is invoked, the class whose name is specified as an argument is loaded by the class loader. If the class is already loaded, then a reference is simply returned; otherwise, the loader goes through the delegation model to load the class.

Implicit class loading occurs when a class is loaded as result of a reference, instantiation, or inheritance (not via an explicit method call). In each of these cases, the loading is initiated under the covers and the JVM resolves the necessary references and loads the class. As with explicit class loading, if the class is already loaded, then a reference is simply returned; otherwise, the loader goes through the delegation model to load the class.

What is class loading ? (in java)

Classloading is a mechanism to load a Class inside the JVM. It allows classes to be dynamically loaded as opposed to static loading(done through imports). It is done with the help of class-loader which must be a subclass of java.lang.Classloader. See more here on - What is class loader?

Tuesday 24 May 2011

Solution to Square rectangle problem

We have already gone through this problem here.
So inheritance is not always useful, but composition may be the key sometimes.

public class Square  
{
private Rectangle r;
public void SetWidth (double x) { r.SetWidth (x); r.SetHeight (x); }
public void SetHeight (double x) { r.SetWidth (x); r.SetHeight (x); }
public void GetWidth () { return r.GetWidth; }
public void GetHeight() { return r. GetHeight; }
public void GetArea () { return r. GetArea; }
}

So it solves our problem.

Monday 23 May 2011

Java interview questions on garbage collections

Which part of the memory is involved in Garbage Collection? Stack or Heap?

Ans) Heap

What is responsiblity of Garbage Collector?

Ans) Garbage collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run.

Is garbage collector a dameon thread?

Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM. The thread stops when all non-dameon threads stop.

Garbage Collector is controlled by whom?

Ans) The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low, but this behavior of jvm can not be guaranteed.
One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by jvm.

When does an object become eligible for garbage collection?

Ans) An object becomes eligible for Garbage Collection when no live thread can access it.

Can the Garbage Collection be forced by any means?
Ans) No. The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.

How can the Garbage Collection be requested?

Ans) There are two ways in which we can request the jvm to execute the Garbage Collection.

  • 1) The methods to perform the garbage collections are present in the Runtime class provided by java. The Runtime class is a Singleton for each java main program.
    The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked using this instance of Runtime to request the garbage collection.
  • 2) Call the System class System.gc() method which will request the jvm to perform GC.

What is the purpose of overriding finalize() method?

Ans) The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some point the same object becomes eligible for Garbage collection, will the finalize() method be called again?
Ans) No

How many times does the garbage collector calls the finalize() method for an object?
Ans) Only once.

What happens if an uncaught exception is thrown from during the execution of the finalize() method of an object?
Ans) The exception will be ignored and the garbage collection (finalization) of that object terminates.

What are different ways to call garbage collector?
Ans) Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().

How to enable/disable call of finalize() method of exit of the application
Ans) Passing the boolean value will either disable or enable the finalize() call.

Runtime.getRuntime().runFinalizersOnExit(boolean value) . 

Java interview questions on packages

Which package is always imported by default?
No. It is by default loaded internally by the JVM. The java.lang package is always imported by default.

Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains anything about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Does importing a package imports the sub packages as well? E.g. Does importing com.bob.* also import com.bob.code.*?
No you will have to import the sub packages explicitly. Importing com.bob.* will import classes in the package bob only. It will not import any class in any of its sub package’s.

Explain the usage of Java packages.
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
For example: The Java API is grouped into libraries of related classes and interfaces; these libraries are known as package.

Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.BOB compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying, cannot resolve symbol.

Conditional operators in java

The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)

int x = 10, y = 12, z = 0;
z = x > y ? x : y;
//As x>y is false, z=y

Compound operators in java

The compound operators perform shortcuts in common programming operations. Java has eleven compound assignment operators.
Syntax:

argument1 operator = argument2.

The above statement is the same as, argument1 = argument1 operator argument2. An example program is shown below that demonstrates the different Compound operators in java.

int x = 0, y = 5;
x += 3; //x = 3 now
y *= x; // y = 5*x = 15

Logical or Conditional Operators in java

Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result is always a boolean data type.
Symbol Name
AND &&
OR ||
NOT !
An example program is shown below that demonstrates the different Logical operators in java.
Example of &&
boolean b;
b = 3 > 2 && 5 < 6; // b is true
b = 2 > 3 && 5 < 6; // b is now false


Example of ||


boolean b;
b = 3 > 2 || 5 < 6; // b is true
b = 2 > 3 || 5 < 6; // b is still true

Example of !

boolean b;
b = !(3 > 2); // b is false
b = !(2 > 3); // b is true

Also there are bitwise logical operators also, please have a look.
Also see important rule for conditional operators - || and &&

Arithmetic operators in java

Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java.

The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed.

String message = 100 + “Messages”; //”100 Messages”

The assignment operators in java

The java assignment operator statement has the following syntax:

<variable> = <expression>

If the value already exists in the variable it is overwritten by the assignment operator (=).

j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.

// Multiple Assignments
k = j = 10; // (k = (j = 10))


But in case of reference, just a shallow copy is made:


SomeClass obj1 = new SomeClass();
SomeClass obj2 = new SomeClass();
obj2 = obj1;


obj2 and obj1 are 2 references pointing to the same object, which was initialized in 1st statement by obj1.

Sunday 22 May 2011

The instanceof operator in java

The instanceof operator is a binary operator that determines whether an object reference (the left operand) is an instance of the class, interface, or array type specified by the right operand. The instanceof operator cannot be used with primitive types (this results in a compilation error).

The instanceof operator returns a boolean value of true if the left operand references a non-null object of class C (or array of type T), so that at least one of the following conditions holds.
  • The right operand is a class name C' and C is a subclass of C'.
  • The right operand is an interface name I, and C implements I.
  • The right operand is an array of type T', the left operand is an array of type T, and T is a subclass or subinterface of T' or equal to T'.
The instanceof operator returns false if none of the above conditions are met or if the left operand is null.

String s = "abcd";
Vector v = new Vector();
v.add(s);
Object o = v.elementAt(0);
System.out.println(s instanceof String); // 1.true
System.out.println(s instanceof Object); //2.true
//because String is subclass of Object class
System.out.println(o instanceof String); //3.true
System.out.println(o instanceof Object); //4.true
System.out.println(o instanceof Vector); //5.false


The third output line displays a value of true even though o is declared to be of type Object. How is this so? That's because the object assigned to o is the String object that was added to Vector v.
The fourth and fifth output lines result from the fact that a String object is an Object object but not a Vector object.

Tuesday 17 May 2011

Beware of floating numbers in java

Outside of a scientific or engineering context, the use of float and double (and the corresponding wrapper classes Float and Double ) should likely be avoided. The fundamental problem is that rounding errors will always occur when using these data types - they are unavoidable.

In a typical business application, using float and double to represent money values is dangerous, because of these rounding issues. Instead, BigDecimal should usually be used to represent money.

Avoid excessive use of the instanceof operator

Many hold that the instanceof operator should be used only as a last resort, and that an overridden method is usually (but not always) a better alternative.

This is because, if one object is of type T1, it wouldn't guarantee that object T2, which returns True in case of (T2 instanceof T1), may be of type T1. This is because T2 may belong to subclass of T1, as instanceof returns true than as well. See how we used it in equals method.

Naming Convention–Differentiating field, argument,local variables and constant

Fields, arguments, local variables and constants are variables. It is common to use a variable naming convention to distinguish between fields, arguments, and local variables.

Within the body of a method, all of these types of variables can appear. Many find naming conventions to be a helpful aid in getting a rapid understanding of a method's implementation. These conventions have only one purpose : to pour understanding into the brain of the reader as quickly as possible.

To understand a method, you need to understand its data. An important part of understanding data is understanding where it is defined - as a field, argument, or local variable. Naming conventions which distinguish these cases usually allow the reader to understand an implementation more quickly, since they no longer need to scan the class to determine where items are defined.

Some different styles are :

  • field : _foo, foo_, fFoo, this.foo, m_foo, myFoo
  • argument : aFoo, pFoo
  • local variable : foo
  • constant : FOO_FOO
As well, some use a naming convention for type names, to distinguish between interfaces and regular classes :
  • interface : IFooBar
  • class : FooBar, CFooBar
Note that this 'I' and 'C' convention is fundamentally different from the other conventions mentioned above. This convention is visible to the caller, while the other naming conventions, being confined to the implementation, are not. Also note that class name is generally given on what it represents, and methods into it are named on the behaviour or function they do. Similarly interface name is given on what they add to class.

The example code on this site usually follows these conventions :

  • field : fBlahBlah
  • argument : aFooBar
  • local variable : fooBar
  • constant : FOO_BAR
  • class : FooBar
  • interface : IFooBar

The return value of a method is sometimes given a conventional name as well.

See also Sun's remarks on naming conventions in general.

See Also :

Conventional name for return value
Coding conventions
Avoid basic style errors

Naming Convention : Name for return value in method

Some people find it nice to name "return value" of the method as "result". So for eg. :

public String myMethod()
{
...// do something
String result = ...
...//do something
return result;
}


So in this way, when someone reads the method, he is clear what "result" is, and how it is being processed.

Naming Conventions for Exceptions in java

It's good practice to append the word "Exception" to the end of all classes that inherit (directly or indirectly) from the Exception class. Similarly, classes that inherit from the Error class should end with the string "Error".

Adding custom exception to your Project Design

When you design a package of Java classes that collaborate to provide some useful function to your users, you work hard to ensure that your classes interact well together and that their interfaces are easy to understand and use. You should spend just as much time thinking about and designing the exceptions that your classes throw.

Thinking of Exceptions


Suppose you are writing a linked list class that you're planning to distribute as freeware. Among other methods, your linked list class supports these methods:
objectAt(int n)
Returns the object in the nth position in the list.
firstObject
Returns the first object in the list.
indexOf(Object n)
Searches the list for the specified Object and returns its position in the list.

What Can Go Wrong?

Because many programmers will be using your linked list class, you can be assured that many will misuse or abuse your class and its methods. Also, some legitimate calls to your linked list's methods may result in an undefined result. Regardless, in the face of errors, you want your linked list class to be as robust as possible, to do something reasonable about errors, and to communicate errors back to the calling program. However, you can't anticipate how each user of your linked list class will want the object to behave under adversity. So, often the best thing to do when an error occurs is to throw an exception.
Each of the methods supported by your linked list might throw an exception under certain conditions, and each method might throw a different type of exception than the others. For example,

objectAt
Throws an exception if the integer passed into the method is less than 0 or larger than the number of objects currently in the list.
firstObject
Throws an exception if the list contains no objects.
indexOf
Throws an exception if the object passed into the method is not in the list.

But what type of exception should each method throw? Should it be an exception provided with the Java development environment? Or should you roll your own?

Choosing the Exception Type to Throw

When faced with choosing the type of exception to throw, you have two choices:
  1. Use one written by someone else. The Java development environment provides a lot of exception classes that you could use.
  2. Write one of your own.
You should go to the trouble of writing your own exception classes if you answer "yes" to any of the following questions. Otherwise, you can probably get away with using someone else's:
  • Do you need an exception type that isn't represented by those in the Java development environment?
  • Would it help your users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will your users have access to those exceptions? A similar question is: Should your package be independent and self-contained?

Your linked list class can throw multiple exceptions, and it would be convenient to be able to catch all exceptions thrown by the linked list with one exception handler. Also, if you plan to distribute your linked list in a package, all related code should be packaged together. Thus for the linked list, you should roll your own exception class hierarchy.
The following diagram illustrates one possible exception class hierarchy for your linked list:

LinkedListException is the parent class of all the possible exceptions that can be thrown by the linked list class. Users of your linked list class can write a single exception handler to handle all linked list exceptions with a catch statement like this:

catch (LinkedListException ex) {. . . }

Or, users could write more specialized handlers for each subclass of LinkedListException.



Choosing a Superclass


The diagram above does not indicate the superclass of the LinkedListException class. As you know, Java exceptions must be Throwable objects (they must be instances of Throwable or a subclass of Throwable). So, your temptation might be to make LinkedListException a subclass of Throwable. However, the java.lang package provides two Throwable subclasses that further divide the type of problems that can occur within a Java program: Errors and Exceptions. Most of the applets and applications that you write will throw objects that are Exceptions. (Errors are reserved for serious hard errors that occur deep in the system.)


Theoretically, any Exception subclass could be used as the parent class of LinkedListException. However, a quick perusal of those classes show that they are either too specialized or completely unrelated to LinkedListException to be appropriate. Thus, the parent class of LinkedListException should be Exception.
Because runtime exceptions don't have to be specified in the throws clause of a method, many packages developers ask: "Isn't it just easier if I make all of my exception inherit from RuntimeException?" The answer to this question is covered in detail on Runtime Exceptions--The Controversy. The bottom line is that you shouldn't subclass RuntimeException unless your class really is a runtime exception! For most of you, this means "No, your exceptions shouldn't inherit from RuntimeException."

Monday 16 May 2011

throw vs throws in java

throws is used to specify that an exception/s can be thrown. Specifying is more pertinent to checked exceptions.

throw is simply the statement to manually/programically throw the exception or any object of throwable type.

Using throws

a method, and then tell that this method throws following exception…and then write da .. da .. da. Eg.

public void myMethod() throws MalformedURLException,MyCustomException1
{
//do something in method
}



Using throw


throw just throws exception. Eg.

if(something)
throw someObjectOfThrowableType

Is the finally Statement Really Necessary in java?

At first the need for a finally statement may not be immediately apparent. Programmers often ask "Is the finally statement really necessary or is it just sugar for my Java?" In particular, C++ programmers doubt the need for a finally statement because C++ doesn't have one.The need for a finally statement is not apparent until you consider the following: how does the PrintWriter in the writeListmethod get closed if you don't provide an exception handler for the ArrayIndexOutOfBoundsException and anArrayIndexOutOfBoundsException occurs? (It's easy and legal to omit an exception handler for ArrayIndexOutOfBoundsExceptionbecause it's a runtime exception and the compiler won't alert you that the writeList contains a method call that might throw one.) The answer is that the PrintWriter does not get closed if an ArrayIndexOutOfBoundsException occurs and writeList does not provide a handler for it--unless the writeList provides a finally statement.
There are other benefits to using the finally statement. In the writeList example it is possible to provide for cleanup without the intervention of a finally statement. For example, you could put the code to close the PrintWriter at the end of the try block and again within the exception handler for ArrayIndexOutOfBoundsException, as shown here:

try {
. . .
out.close(); // don't do this; it duplicates code
} catch (ArrayIndexOutOfBoundsException e) {
out.close(); // don't do this; it duplicates code
System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}

However, this duplicates code, making the code hard to read and prone to errors if you modify the code later. For example, if you add code to the try block that may throw a new type of exception, you will have to remember to close thePrintWriter within the new exception handler (which if you're anything like me, you are bound to forget).


Catching Multiple Exception Types with One Handler in java

Consider the following code here, which has to deal with 2 exceptions. Now to handle this exception, we have to apply 2 catch blocks to handle the exception which we have shown here.

The two exception handlers used by the writeList method are very specialized. Each handles only one type of exception. The Java language allows you to write general exception handlers that handle multiple types of exceptions.As you know, Java exceptions are Throwable objects; they are instances of Throwable or a subclass of Throwable. The Java packages contain numerous classes that derive from Throwable and thus, build a hierarchy of Throwable classes. We have discussed the hierarchy here.

Your exception handler can be written to handle any class that inherits from Throwable. If you write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type. If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses.Let's modify the writeList method once again. Only this time, let's write it so that it handles both IOExceptions andArrayIndexOutOfBoundsExceptions. The closest common ancester of IOException and ArrayIndexOutOfBoundsException is the Exceptionclass. An exception handler that handles both types of exceptions looks like this:

try {
. . .
} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}

The class is pretty high in the Throwable class hierarchy. So in addition to the IOException and ArrayIndexOutOfBoundsExceptiontypes that this exception handler is intended to catch, it will catch numerous other types. Generally speaking, your exception handlers should be more specialized. Handlers that can catch most or all exceptions are typically useless for error recovery because the handler has to determine what type of exception occurred anyway to determine the best recovery strategy. Also, exception handlers that are too general can make code more error prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended.


How java implements Exception handling?

When an unexpected error occurs in a method, java has to handle this exception. So it has to throw that exception and handle it some way. Lets see how :

 

Throwing an exception

Many kinds of errors can cause exceptions--problems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception, including its type and the state of the program when the error occurred. The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception.

 

Catching an exception

After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler. An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception. The exception handler chosen is said to catch the exception.
If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates.

Sunday 15 May 2011

Disadvantage of Garbage collection

A potential disadvantage of a garbage-collected heap is that it adds an overhead that can affect program performance. The Java virtual machine has to keep track of which objects are being referenced by the executing program, and finalize and free unreferenced objects on the fly. This activity will likely require more CPU time than would have been required if the program explicitly freed unnecessary memory. In addition, programmers in a garbage-collected environment have less control over the scheduling of CPU time devoted to freeing objects that are no longer needed.

Static initialization block in java

You initialize a static field either by supplying an initial value or by using a static initialization block. You have already seen the first mechanism:
static int nextId = 1;


If the static fields of your class require complex initialization code, use a static initialization block.

Place the code inside a block and tag it with the keyword static. Here is an example. We want the employee ID numbers to start at a random integer less than 10,000.

// static initialization block

static

{

Random generator = new Random();

nextId = generator.nextInt(10000);

}




Static initialization occurs when the class is first loaded. Like instance fields, static fields are 0, false, or null unless you explicitly set them to another value. All static field initializers and static initialization blocks are executed in the order in which they occur in the class declaration.

Implementing Comparator interface

Suppose we have already decided natural ordering of the object, but for some reason we have to compare 2 objects based on some other fields in it.

Eg. Take the case of employee. We have already written compareTo() method for it. By this we have decided its natural ordering. Now, if we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.

By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.

Contract of compare method

java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.

  1. positive – o1 is greater than o2
  2. zero – o1 equals to o2
  3. negative – o1 is less than o1

Example

Sorting by name field

Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.

public class EmpSortByName implements Comparator<Employee>{

public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}


Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).
Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.

Using the above Comparator for sorting:

import java.util.*;

public class TestEmployeeSort {

public static void main(String[] args) {

List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}

private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}


Sorting by empID field


Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class does that.

public class EmpSortByEmpId implements Comparator<Employee>{

public int compare(Employee o1, Employee o2) {
return o1.getEmpId() - o2.getEmpId();
}
}


Comparator vs Comparable interface


The primary use of comparators is to pass them to something that does sorting, either one of the explicit sort methods, or to a data structure than implicitly sorts (eg, TreeSet or TreeMap).


Comparators are not needed for arrays of primitive values, or arrays of collections of objects that have a natural ordering, eg, String, BigInteger, etc.

Implementing compareTo() : Sorting in natural ordering using compareTo()

Defining the criteria for sorting

Suppose we have list of Employees. We have to sort them. By default, you can't sort it, until you define some criteria. Say you define sorting as first name of employee, or you may say sort on the basis of employee id or their salary. So first thing is we have to define some criteria for sorting. This defines "natural ordering" on which sort can be done.

How to define "natural order" in java?

For this, we have to implement Comparable interface, which has compareTo method, which decides how we put natural ordering on the object.

Example:

Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.

public class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;

/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
….
}

So this compareTo() method does the trick of implementing natural ordering. So if we have 2 Employees, emp1.id – emp2.id is negative, then emp1 falls before emp2 in this ordering. We can say it like this:

emp1.id < emp2.id – emp1 falls before emp2 in natural ordering

emp1.id == emp2.id – emp1 falls with emp2 in natural ordering

emp1.id > emp2.id – emp1 falls after emp2 in natural ordering

 

Sorting the employee list:

 

We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.

import java.util.*;

public class TestEmployeeSort {

public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}

private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}


Similarly to sort on the basis of name : write compareTo like this:


public int compareTo(Employee other) {
return name.compareTo(o2.getName());
//here compareTo() method of String is called
}

Implementing compareTo() using commons-lang

Here CompareToBuilder is used to implement compareTo();

public int compareTo(Person person) {
return new CompareToBuilder()
append(this.firstName, person.firstName)
append(this.lastName, person.firstName)
toComparison();
}


Also, there is yet another reflection option:


public int compareTo(Object o) {
return CompareToBuilder.reflectionCompare(this, o);
}

Useful steps in implementing your own hashCode() method

Here are some useful guidelines for implementing the hashCode method correctly.

  1. Store an arbitrary non-zero constant integer value (say 7) in an int variable, called hash.
  2. Involve significant variables of your object in the calculation of the hash code, all the variables that are part of equals comparison should be considered for this. Compute an individual hash code int var_code for each variable var as follows -
    1. If the variable(var) is byte, char, short or int, then
      var_code = (int)var;


    2. If the variable(var) is long, then

      var_code = (int)(var ^ (var >>> 32));


    3. If the variable(var) is float, then

      var_code = Float.floatToIntBits(var);


    4. If the variable(var) is double, then -

      long bits = Double.doubleToLongBits(var);
      var_code = (int)(bits ^ (bits >>> 32));


    5. If the variable(var) is boolean, then

      var_code = var ? 1 : 0;


    6. If the variable(var) is an object reference, then check if it is null, if yes then var_code = 0; otherwise invoke the hashCode method recursively on this object reference to get the hash code. This can be simplified and given as -

      var_code = (null == var ? 0 : var.hashCode());


  3. Combine this individual variable hash code var_code in the original hash code hash as follows -

    hash = 31 * hash + var_code;


  4. Follow these steps for all the significant variables and in the end return the resulting integer hash.
  5. Lastly, review your hashCode method and check if it is returning equal hash codes for equal objects. Also, verify that the hash codes returned for the object are consistently the same for multiple invocations during the same execution.
The guidelines provided here for implementing equals and hashCode methods are merely useful as guidelines, these are not absolute laws or rules. Nevertheless, following them while implementing these two methods will certainly give you correct and consistent results.






Saturday 14 May 2011

Implementing hashCode using commons-lang

This example shows how to implement hashCode() using HashCodeBuilder of commons-lang.

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;

import java.io.Serializable;

public class MyClass implements Serializable {
private Long id;

private String title;

private String author;

public int hashCode() {
return new HashCodeBuilder().append(id).append(title).append(author).toHashCode();

// return HashCodeBuilder.reflectionHashCode(this);

}
}

 

Also, reflection can be used to implement the same function:


public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}


equals() vs ==

Object class has a default method which looks like this :

public boolean equals(Object other)
{
return this==other;
}


== tests identity of the object, i.e. whether the 2 references are pointing the same object or not.

The default implementation of equals() is based on the == operator: Two objects are equal if and only if they are the same object. Naturally, most classes should define their own alternative implementation of this important method.

Implementing equals

Object class have methods like equals() and hashcode(). These methods have their own contracts which have to be fulfilled to override them.
 
Default implementation of equals() in object class

The default implementation of equals() in Object class is based on the == operator: Two objects are equal if and only if they are the same object. Naturally, most classes should define their own alternative implementation of this important method.

 
 
Contract of equals method:

Implementing equals() correctly is not straightforward. The equals() method has a contract that says the equality relation must meet these demands:

  • It must be reflexive. For any reference x, x.equals(x) must return True.
  • It must be symmetric. For any two nonnull references x and y, x.equals(y) should return the exact same value as y.equals(x).
  • It must be transitive. For any three references x, y, and z, if x.equals(y) and y.equals(z) are True, then x.equals(z) must also return True.
  • It should be consistent. For any two references x and y, x.equals(y) should return the same value if called repeatedly (unless, of course, either x or y were changed between the repeated invocations of equals()).
  • For any nonnull reference x, x.equals(null) should return False.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Steps to be taken when implementing equals()

Steps that need to be taken into consideration while implementing equals method

  1. Use the == operator to check whether the incoming object is null. Its kind of performance optimization.
    public boolean equals(Object incomingObject) {
    if (incomingObject == null) return false;
    }


  2. Use the == operator to check if the argument is a reference to this object. If so, return true. This is just a performance optimization, but one that is worth doing if the comparison is potentially expensive.

    public boolean equals(Object incomingObject){
    if(this==incomingObject)
    return true;
    }


  3. Use the instanceof operator to check if the argument has the correct type.
    If not, return false. Typically, the correct type is the class in which the method occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equals contract to permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entry have this property.

    public boolean equals(){
    if (!(incomingObject instanceof MyClass)) return false;
    }

    Note  : I have not checked like this:

    if(incomingObject instanceof MyClass)
    do something;

    The reason being instanceof returns true even when incomingObject is subclass object. So its important to check whether the object is type of class we are writing equals or not. If not, what is the point of writing further logic. Just return false, and leave.

  4. Cast the argument to the correct type. Because this cast was preceded by an instanceof test, it is guaranteed to succeed.

    public boolean equals(Object incomingObject){
    MyClass mc = (MyClass) incomingObject;
    }



  5. For each “significant” field in the class, checks if that field of the argument matches the corresponding field of this object. If all these tests succeed, return true; otherwise, return false


  6. When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?

Writing the complete equals function


Finishing whole steps:


public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof MyClass)) return false;
MyClass mc = (MyClass) o;
return ... // compare members of mc
}

Difference between static and init block

The static block is only loaded when the class object is created by the JVM for the 1st time whereas init {} block is loaded every time class object is created. Also first the static block is loaded then the init block.

public class LoadingBlocks {

static{
System.out.println("Inside static");
}

{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}



Output:

Inside static
Inside init
Inside init
Inside init


So static block is initialized only once, that is it is per class basis, whereas init block is per object basis.

Use of hashcode and equals


Implement equals method using commons-lang

Here we use EqualsBuilder to see whether the 2 objects are equal or not. Take the example of person:

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;

import java.io.Serializable;

public class Person implements Serializable {
private Long id;

private String name;

private String sirname;

public boolean equals(Object object) {
if (!(object instanceof Main)) {
return false;
}

if (object == this) {
return true;
}

Person person = (Person) object;
return new EqualsBuilder().append(this.id, person.id).append(this.name, person.name)
.append(this.sirname, person.sirname).isEquals();

// return EqualsBuilder.reflectionEquals(this, person);

}
}

Friday 13 May 2011

Classes helping in parsing the input

Some of the classes in the Java IO API are designed to help you parse input. These classes are:
  • PusbackInputStream
  • StreamTokenizer
  • PushbackReader
  • LineNumberReader
It is not the purpose of this text to give you a complete course in parsing of data. The purpose was rather to give you above quick list of classes related to parsing of input data.
If you have to parse data you will often end up writing your own classes that use some of the classes in this list. I know I did when I wrote the parser for the Butterfly Container Script. I used the PushbackInputStream at the core of my parser, because sometimes I needed to read ahead a character or two, to determine what the character at hand meant.

Tuesday 10 May 2011

Moving file or directory from one directory to another

Here we write function to copy file or directory from one place to other.

public static boolean moveFileOrDirectory(String src, String dst){
File source = new File(src);
if(!source.exists())
return false;


File destination = new File(dest);
if(!destination.exists()){
System.out.print("Mentioned directory does not exist.
\nDo you want to create a new directory(Y/N)? "
);

String chk = readString();
if(chk.equals("Y") || chk.equals("y")){
destination.mkdir();
return copyDirectory(source, destination);
}else{
return false;
}
}else //if file or directory already exists, we have to copy and
//overwrite the already existing one
{
System.out.println("Given file or folder name already exists.
\nDo you want to replace now?"
);
String chk = readString();
if("Y".equals(chk) )
return copyDirectory(source, destination);
else return false;
}
}



 


Now this function makes use of copyDirectory function which can be written like this:



public static boolean copyDirectory(File sourceDir, File destDir) throws
IOException{

if(!destDir.exists()){
destDir.mkdir();
}

File[] children = sourceDir.listFiles();
for(File sourceChild : children){

String name = sourceChild.getName();

File destChild = new File(destDir, name);

if(sourceChild.isDirectory()){

return copyDirectory(sourceChild, destChild);

}

else{

return copyFile(sourceChild, destChild);

}

}

}



Now this in turn makes use of copyFile function.



public static void copyFile(File source, File dest) throws IOException{

if(!dest.exists()){

dest.createNewFile();

}

InputStream in = null;

OutputStream out = null;

try{

in = new FileInputStream(source);

out = new FileOutputStream(dest);

byte[] buf = new byte[1024];

int len;

while((len = in.read(buf)) > 0){

out.write(buf, 0, len);

}

}

finally{

in.close();

out.close();

}
return true;

}