Friday, May 29, 2009

NavigableMap & NavigableSet interface

The NavigableMap interface extends the SortedMap interface in which the elements are ordered either by natural ordering or by using a Comparator. It contains methods to find out the closest matches for given search targets. All keys inserted into a sorted map must implement the Comparable interface and must be mutually comparable. The elements of the NavigableSet interface can be accessed and traversed in either ascending or descending order.

The NavigableSet interface extends the SortedSet interface in which the elements are ordered either by natural ordering or using a Comparator. It contains methods to find out the closest matches for given search targets. The elements of the NavigableSet interface must be mutually comparable. The elements of the NavigableSet interface can be accessed and traversed in either ascending or descending order.

Matcher class

Matcher is a final class present in the java.util.regex package. It is used to match a regular expression using the pattern defined by the Pattern class.

The Matcher class defines no public constructors. It is created from a pattern by invoking the Pattern's matcher method as follows:

public Matcher matcher(CharSequence input)

This method creates a matcher that will match the given input against the given pattern.

The other important methods of the Matcher class are as follows:

  • int start(): This method returns the index of the first character matched.

  • public int end(): This method returns the index of the last character matched, plus one.

  • boolean find(): This method searches the subsequence of the input sequence that matches the pattern. It returns true if the match is found; otherwise, it returns false.

  • boolean lookingAt(): This method searches through the input sequence to match the pattern. It returns true if the match is found; otherwise, it returns false.

Externalizable interface

The Externalizable interface allows a programmer to have a complete control over the serialization and deserialization processes.

The Externalizable interface has the following two methods:

  • public void writeExternal(ObjectOutput objout): This method is used to save the contents of an object by calling the methods of the DataOutput interface for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, arrays, etc.


  • public void readExternal(ObjectInput objin): This method is used to restore the contents of an object that was saved using the writeExternal() method. It calls the methods of the DataInput interface for primitive types and the readObject() method for objects, strings, arrays, etc.

Comparable & Comparator interface

The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

interface Comparable, where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:

int i = object1.compareTo(object2)

  • If object1 <>
  • If object1 > object2: The value of i returned will be positive.

  • If object1 = object2: The value of i returned will be zero.

The Comparator interface is used to sort the elements of collections and arrays. It differs from the Comparable interface in that the Comparable interface sorts the elements only in the natural order. In contrast, the Comparator interface sorts the collections and arrays in a number of different ways.

The Comparator interface has a single compare() method, which returns an integer. It has the following signature:

int Obj1.compare(Obj1, Obj2): This method compares the order of the method arguments and returns the following results:

  • negative if Obj1 <>
  • positive if Obj1 > Obj2

  • zero if Obj1 == Obj2
equals(Object obj): This method is used to compare the equality of two objects. The objects being compared must also implement the Comparator interface.

The Comparator interface can sort only the mutually comparable objects. It cannot be used to sort primitives. Sorting elements using the Comparator interface requires building a class separate from the class whose instances are to be sorted. This is in contrast to the Comparable interface, in which case the class to be sorted itself uses the Comparable interface.

Serializable

Serializable is a marker interface. (A marker interface is one without any method). The classes that do not implement this interface will not have any of their states serialized or deserialized. Serialization is the process of converting an object into byte stream, so that it can be transferred over a network and stored into a persistent medium such as a file.

Serialization is the process of converting the state of an object into a form that can be transported or stored. In this process, an object's state is written to a temporary or persistent storage. Later, the object can be recreated by deserializing or reading the object's state from the storage.

Coupling

Coupling is a term that describes the degree to which one module relies on another module for its proper functioning. Coupling is mainly of the following two types:

  • Loose coupling: Loose or weak coupling implies that a change in one module does not require changes in the implementation of another module.

  • Tight coupling: Tight or strong coupling implies that a module relies on another module so strongly that a small change in one will require an implementation change in the other.
For a good object-oriented design, loose coupling is desirable.

Cohesion

Cohesion is a measure of degree of how strongly a class focuses on its responsibilities. It is of the following two types:

  • High cohesion: This means that a class is designed to carry on a specific and precise task. Using high cohesion, methods are easier to understand, as they perform a single task.
  • Low cohesion: This means that a class is designed to carry on various tasks. Using low cohesion, methods are difficult to understand and maintain.
In object-oriented design, high cohesion is desirable, as it is easy to understand and maintain. Moreover, it is easier to reuse.

Differences between exceptions and assertions

ExceptionsAssertions
An exception tells the user of the program that something in the program went wrong.An assertion documents a program. When it fails, it informs that the program has a bug.
Exceptions are created to deal with problems that might occur in the program. Assertions are written to state the concepts of a program.
Exceptions are used to test input/output as well as whether parameters are legal or not.Assertions are documentations that can be checked by running the program.

checked and unchecked exceptions

Unchecked Exceptions: Exceptions that are defined by the Error and RuntimeException classes and their subclasses are known as unchecked exceptions. It is not necessary that a method must deal with these kinds of exceptions. If the exceptions are irrecoverable, the program should not attempt to deal with them. The method can only deal with the exceptions that are recoverable.

Checked Exceptions: All exceptions except the Error and RuntimeException classes and their subclasses are known as checked exceptions. If a method throws a checked exception, it is necessary that the method must explicitly deal with the exception. The method must catch the exception and take the necessary action.

Closeable and Flushable interfaces

The Closeable and Flushable interfaces define a uniform way for specifying that a stream can be closed or flushed.

Closeable: The objects that implement the Closeable interface can be closed. This interface defines the close() method.

void close() throws IOException

It closes the invoking stream and releases all the resources. It is implemented by all the I/O classes that open a stream.

Flushable: The objects that implement the Flushable interface can force buffered output to be written to a stream to which the objects are attached. This interface defines the flush() method.

void flush() throws IOException

JavaBeans setter and getter methods

JavaBeans are Java classes that have properties. Properties are private instance variables. According to JavaBeans, the methods that set the values of these variables are known as setter methods, and the methods that retrieve the values of these variables are known as getter methods.

The naming convention for setter methods is that they should be prefixed with set and the name of the variable. The name of the variable should begin with upper case.

The naming convention for getter methods is similar to that of setter. It should begin with get and the name of the variable. The name of the variable should begin with upper case.

The setter method must be declared public, with a void return type and an argument that represents the property type.

The getter method must be declared public. It takes no arguments, and should have a return type that matches the argument type of the setter method for that property.

Properties of synchronization

Synchronization is a process through which multiple threads share access to common objects. Java coordinates the actions of multiple threads using synchronized methods and statements. Following are the properties of synchronization:

  1. If a thread contains some locks and goes to sleep, then it does not release the locks.
  2. Only methods can be synchronized, not variables and constants.
  3. If two threads invoke the same method, then only one thread at a time can invoke a method.
  4. A thread can invoke a synchronized method on multiple objects.
  5. A class can have both synchronized and non-synchronized methods.
  6. If a class has synchronized and non-synchronized methods, then multiple threads can still access the non-synchronized methods of the class.

Different states of a thread

The job of the thread scheduler is to move a thread from one state to another state. A thread can be in one of the following states:

  1. New: It is the state when the thread instance has been created, but the start method has not been invoked on the thread.


  2. Runnable: It is the state when the thread is eligible to run. In this state, the thread is not selected by the scheduler for execution. A thread enters the Runnable state when the start() method is invoked. A thread can return to the Runnable state from the blocked, waiting, or sleeping state.


  3. Running: It is the state when the thread scheduler selects the thread to be the currently executing process. A thread can transition out of a running state through the compiler.


  4. Waiting: It is also known as blocked or sleeping state. In this state, the thread is not eligible to run, but it might return to the runnable state if a particular event occurs. A thread can be blocked if it is waiting for a resource. It can be in the waiting state if its code causes it to wait.


  5. Dead: A thread is considered dead when its run() method completes. Once a thread is dead, it can never be brought back to life.

Differences between the BufferedReader and BufferedWriter

BufferedReaderBufferedWriter
It extends from the reader class.It extends from the writer class.
Its key constructor arguments are Reader.Its key constructor arguments are Writer.
It provides the read() and readLine() methods.It provides the close(), flush(), newLine(), and write() methods.
It implements the mark() and reset() methods. It does not implement the mark() and reset() methods.

Differences between the Comparable and Comparator interfaces

Comparable InterfaceComparator Interface
It uses the compareTo() method.

int objectOne.compareTo(objectTwo)
It uses the compare() method.

int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance is going to be sorted.A separate class can be created in order to sort the instances.
Only one sort sequence can be created. Many sort sequences can be created.
It is frequently used by the API classes.It it used by third-party classes to sort instances.

Differences between StringBuffer and String

StringBufferString
It provides a mutable character sequence. It provides an immutable character sequence.
It is possible to insert characters and substrings in the middle or at the end of the string.It is not possible to insert characters and substrings in the middle or at the end of the string.
It reserves room for 16 characters without reallocation.It does not reserve room for characters.
It uses the ensureCapacity(), delete(), deleteCharAt(), append(), insert(), and reverse() methods.It is not possible to use these methods on strings because they are immutable.

Differences between method overriding and method overloading

Method OverridingMethod Overloading
Arguments of overloaded methods cannot be changed.Arguments of overloaded methods can be changed.
Method return types cannot be changed except covariant return types. Return types can be changed.
Exceptions must not throw new or broader checked exceptions.Exceptions can be changed.
It happens at runtime.It happens at compile-time.
An object type determines which method is selected.A reference type determines which method is selected.