Thursday, April 5, 2012

Java Singleton design pattern tutorial


Java Singleton design pattern is one of the design pattern that governs the instantiation of an object in Java. This design pattern suggest that only one instance of a Singleton object is created by the JVM. This pattern is useful when exactly one object is needed to coordinate actions across the system. Also it can be generalized to restrict the objects to certain number of instances like say 5 objects only.
Related: Free Design Pattern Reference Card

Class diagram of Singleton class

Following is the class diagram of a singleton class. The constructor is kept private to avoid normal instantiation of objects and all the instantiations are done only through getInstance() method.

How the Singleton pattern works?

Following is the source of simple class that follows singleton pattern.
01
02
03
04
05
06
07
08
09
10
11
12
13
public class SimpleSingleton {
    private static SimpleSingleton INSTANCE = new SimpleSingleton();
 
    //Marking default constructor private
    //to avoid direct instantiation.
    private SimpleSingleton() {
    }
 
    //Get instance for class SimpleSingleton
    public static SimpleSingleton getInstance() {
        return INSTANCE;
    }
}
In above code snippet, we have declared a static object reference to SimpleSingleton class called INSTANCE and is returned every time getInstance() is called. In this design, the object will be instantiate when the class will be loaded and before the method getInstance() is being called. Demand loading (lazy loading) also called initialization on demand holder idiom is not seen in this implementation.
We can change this code to add lazy init (Instantiate only when first time getInstance() is called) into this. Following is the code snippet for that.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
public class SimpleSingleton {
    private SimpleSingleton singleInstance = null;
 
    //Marking default constructor private
    //to avoid direct instantiation.
    private SimpleSingleton() {
    }
 
    //Get instance for class SimpleSingleton
    public static SimpleSingleton getInstance() {
 
        if(null == singleInstance) {
            singleInstance = new SimpleSingleton();
        }
 
        return singleInstance;
    }
}

Do you need Singleton pattern?

Singletons are useful only when you need one instance of a class and it is undesirable to have more than one instance of a class.
When designing a system, you usually want to control how an object is used and prevent users (including yourself) from making copies of it or creating new instances. For example, you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.
The Singleton pattern is often used in conjunction with the factory method pattern to create a systemwide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Abstract Windowing Toolkit (AWT). In GUI applications, you often need only one instance of a graphical element per application instance, like the Print dialog box or the OK button.

Problems with Singletons

A simple design pattern like Singleton also has few problem:

Construct in a multi-thread environment

It may happen that in a multi-threaded environment two or more threads enter the method getInstance() at the same time when Singleton instance is not created, resulting into simultaneous creation of two objects.
Such problems can be avoided by defining getInstance() method synchronized.
1
public static synchronized SimpleSingleton getInstance() { }

Cloning can spoil the game

Although we have taken enough precaution to make the Singleton object work as singleton, Cloning the object can still copy it and result into duplicate object. The clone of the singleton object can be constructed using clone() method of the object. Hence it is advisable to overload clone() method of Object class and throw CloneNotSupportedException exception.

1
2
3
4
5
public Object clone() throws CloneNotSupportedException {
 
      throw new CloneNotSupportedException();
 
}
The Singleton pattern is widely used and has proved its usability in designing software. Although the pattern is not specific to Java, it has become a classic in Java programming.

Wednesday, April 4, 2012

Difference between ServletRequest.getRequestDispatcher and ServletContext.getRequestDispatcher


  • request.getRequestDispatcher(“url”) means the dispatch is relative to the current HTTP request.
    Example code: RequestDispatcher reqDispObj = request.getRequestDispatcher("/home.jsp"); 
  •  
  • getServletContext().getRequestDispatcher(“url”) means the dispatch is relative to the root of the ServletContext.
    Example code:RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/ContextRoot/home.jsp");

Difference between ServletConfig and ServletContext

  • Signature: public interface ServletConfig
    ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.
Example code:
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-value>
</init-param>
</servlet>

  • Signature: public interface ServletContext
    ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web applicationa is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.
The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file.
Example code:
<context-param>
<param-name>globalVariable</param-name>
<param-value>javapapers.com</param-value>
</context-param>

Difference between JSP include directive and JSP include action

<%@ include file=”filename” %> is the JSP include directive.
  • At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers. The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output.
  • <jsp:include page=”relativeURL” /> is the JSP include action element.
    The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page. When the included JSP page is called, both the request and response objects are passed as parameters. If there is a need to pass additional parameters, then jsp:param element can be used. If the resource is static, its content is inserted into the calling JSP file, since there is no processing needed.

    there is a limit of 64kb size in JVM for method. So the include directive can run into trouble as its all one method. Whereas the action is considered a separate process.

Tuesday, April 3, 2012

can overloaded methods be overridden too ?

Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.

What's the difference between display: none and visibility: hidden?

The display: none and visibility: hidden CSS properties appear to be the same thing, but they aren't.
Answer: These two style properties do two different things.
visibility: hidden hides the element, but it still takes up space in the layout.
display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code.

what does load-on-startup do in web.xml ?

  1. <servlet>  
  2.         <servlet-name>action</servlet-name>  
  3.         <servlet-class>  
  4.             org.apache.struts.action.ActionServlet  
  5.         </servlet-class>  
  6.         <init-param>  
  7.             <param-name>config</param-name>  
  8.             <param-value>/WEB-INF/struts-config.xml</param-value>  
  9.         </init-param>  
  10.         <load-on-startup>1</load-on-startup>  
  11.     </servlet>  
 Servlets are not loaded until they are first accessed by a request. This may result in a slow access time for the first user. The load-on-startup tag allows you to force the container to load and initialize the servlet at startup. 

The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive 128 integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.

Thursday, March 29, 2012

Java Streams Basics

Most of the programs work with external data stored either in local files or coming from other computers on the network. Java has a concept of working with so-called streams of data. After a physical data storage is mapped to a logical stream, a Java program reads data from this stream serially - byte after byte, character after character, etc. Some of the types of streams are byte streams (InputStream, OutputStream) and character streams (Reader and Writer). The same physical file could be read using different types of streams, for example, FileInputStream, or FileReader.

Classes that work with streams are located in the package java.io. Java 1.4 has introduced the new package java.nio with improved performance, which is not covered in this lesson.

There are different types of data, and hence different types of streams.

Here's the sequence of steps needed to work with a stream:

Open a stream that points at a specific data source: a file, a socket, URL, etc.
  1. Read or write data from/to this stream.
  2. Close the stream.

Let's have a closer look at some of the Java streams.

Byte Streams
If a program needs to read/write bytes (8-bit data), it could use one of the subclasses of the InputStream or OutputStream respectively. The example below shows how to use the class FileInputStream to read a file named abc.dat. This code snippet prints each byte's value separated with white spaces. Byte values are represented by integers from 0 to 255, and if the read() method returns -1, this indicates the end of the stream.

import java.io.FileInputStream;
import java.io.IOException;
public class ReadingBytes {
public static void main(String[] args) {  FileInputStream myFile = null;  try {
  myFile = new FileInputStream("c:\\abc.dat");  // open the  stream
  boolean eof = false;
   while (!eof) {
    int byteValue = myFile.read();  // read  the stream
    System.out.println(byteValue);
    if (byteValue  == -1){
    eof = true;
    }
    //myFile.close();  // do not do it here!!!
   }
  }catch (IOException e) {
      System.out.println("Could not read file: " + e.toString());
  } finally{
   try{
     if (myFile!=null){
       myFile.close(); // close the stream
     }
   } catch (Exception e1){
    e1.printStackTrace();
   }
  }
 }
}

Please note that the stream is closed in the clause finally. Do not call the method close() inside of the try/catch block right after the file reading is done. In case of exception during the file read, the program would jump over the close() statement and the stream would never be closed!

The next code fragment writes into the file xyz.dat using the class FileOutputStream:

int somedata[]={56,230,123,43,11,37};
FileOutputStream myFile = null;
try {
  myFile = new  FileOutputStream("c:\xyz.dat");
  for (int i = 0; i <somedata.length;I++){
      myFile.write(data[I]);
  }
} catch (IOException e)
      System.out.println("Could not write to a file: " + e.toString()); }
finally
    // Close the file the same way as in example above }

Buffered Streams
So far we were reading and writing one byte at a time. Disk access is much slower than the processing performed in memory. That's why it's not a good idea to access disk 1000 times for reading a file of 1000 bytes. To minimize the number of time the disk is accessed, Java provides buffers, which are sort of "reservoirs of data". For example, the class BufferedInputStream works as a middleman between the FileInputStream and the file itself. It reads a big chunk of bytes from a file in one shot into memory, and, then the FileInputStream will read single bytes from there. The BufferedOutputStream works in a similar manner with the class FileOutputStream. Buffered streams just make reading more efficient.

You can use stream chaining (or stream piping) to connect streams - think of connecting two pipes in plumbing. Let's modify the example that reads the file abc.dat to introduce the buffering:

FileInputStream myFile = null;
BufferedInputStream buff =null
try {
  myFile = new  FileInputStream("abc.dat");
  BufferedInputStream buff = new BufferedInputStream(myFile);
  boolean eof = false;
  while (!eof) {
    int byteValue = buff.read();
    System.out.print(byteValue + " ");
    if (byteValue  == -1)
      eof = true;
  }
} catch (IOException e) {
  e.printStackTrace();
} finally{
  buff.close();
  myFile.close();
}

It's a good practice to call the method flush() when the writing into a BufferedOutputStream is done - this forces any buffered data to be written out to the underlying output stream.

While the default buffer size varies depending on the OS, it could be controlled. For example, to set the buffer size to 5000 bytes do this:

BufferedInputStream buff = new BufferedInputStream(myFile, 5000);

Character Streams
Java uses two-byte characters to represent text data, and the classes FileReader and FileWriter work with text files. These classes allow you to read files either one character at a time with read(), or one line at a time with readLine().

The classes FileReader and FileWriter also support have buffering with the help of BufferedReader and BufferedWriter. The following example reads text one line at a time:

FileReader myFile = null;
BufferedReader buff = null;
try {
  myFile = new FileReader("abc.txt");
  buff = new BufferedReader(myFile);
  boolean eof = false;
  while (!eof) {
    String line = buff.readLine();
    if (line == null)
      eof = true;
    else
      System.out.println(line);
    }
    ....
}

For the text output, there are several overloaded methods write() that allow you to write one character, one String or an array of characters at a time.

To append data to an existing file while writing, use the 2-arguments constructor (the second argument toggles the append mode):

FileWriter fOut = new FileWriter("xyz.txt", true);

Below is yet another version of the tax calculation program (see the lesson Intro to Object-Oriented Programming with Java). This is a Swing version of the program and it populates the populate the dropdown box chState with the data from the text file states.txt.

import java.awt.event.*;
import java.awt.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class TaxFrameFile extends java.awt.Frame implements ActionListener {
  Label lblGrIncome;
  TextField txtGrossIncome = new TextField(15);
  Label lblDependents=new Label("Number of Dependents:");
  TextField txtDependents = new TextField(2);
  Label lblState = new Label("State: ");
  Choice chState = new Choice();

  Label lblTax = new Label("State Tax: ");
  TextField txtStateTax = new TextField(10);
  Button bGo = new Button("Go");
  Button bReset = new Button("Reset");

  TaxFrameFile() {
    lblGrIncome = new Label("Gross Income: ");
    GridLayout gr = new GridLayout(5,2,1,1);
    setLayout(gr);

    add(lblGrIncome);
    add(txtGrossIncome);
    add(lblDependents);
    add(txtDependents);
    add(lblState);
    add(chState);
    add(lblTax);
    add(txtStateTax);
    add(bGo);
    add(bReset);

    // Populate states from a file
    populateStates();
    txtStateTax.setEditable(false);

    bGo.addActionListener(this);
    bReset.addActionListener(this);

    // Define, instantiate and register a WindowAdapter
    // to process windowClosing Event of this frame

       this.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
                           System.out.println("Good bye!");
            System.exit(0);
        }});
    }

    public void actionPerformed(ActionEvent evt) {
       Object source = evt.getSource();
        if (source == bGo ){
           // The Button Go processing
             try{
               int grossInc =
                Integer.parseInt(txtGrossIncome.getText());
               int dependents   =
                 Integer.parseInt(txtDependents.getText());
               String state = chState.getSelectedItem();

               Tax tax=new Tax(dependents,state,grossInc);
               String sTax =
                       Double.toString(tax.calcStateTax());
               txtStateTax.setText(sTax);
             }catch(NumberFormatException e){
                 txtStateTax.setText("Non-Numeric Data");
             }catch (Exception e){
                txtStateTax.setText(e.getMessage());
             }
         }
         else if (source == bReset ){
            // The Button Reset processing
        txtGrossIncome.setText("");
        txtDependents.setText("");
                          chState.select("  ");
        txtStateTax.setText("");
             }
    }
   // This method will read the file states.txt and
   // populate the dropdown chStates
    private void populateStates(){
      FileReader myFile = null;
      BufferedReader buff = null;
        try {
            myFile = new FileReader("states.txt");
            buff = new BufferedReader(myFile);

            boolean eof = false;
            while (!eof) {
                String line = buff.readLine();
                if (line == null)
                   eof = true;
                else
                   chState.add(line);
         }
        }catch (IOException e){
           txtStateTax.setText("Can't read states.txt");
       }
       finally{
         // Closing the streams
         try{
            buff.close();
            myFile.close();
         }catch(IOException e){
            e.printStackTrace();
         }
       }
    }

    public static void main(String args[]){
       TaxFrameFile taxFrame = new TaxFrameFile();
       taxFrame.setSize(400,150);
       taxFrame.setVisible(true);
    }
}

Data Streams
If you are expecting to work with a stream of a known data structure, i.e. two integers, three floats and a double, use either the DataInputStream or the DataOutputStream. A method call readInt() will read the whole integer number (4 bytes ) at once, and the readLong() will get you a long number (8 bytes).

The DataInput stream is just a filter. We are building a "pipe" from the following fragments:

FileInputStream --> BufferedInputStream --> DataInputStream

FileInputStream myFile = new FileInputStream("myData.dat");
BufferedInputStream buff = new BufferedInputStream(myFile);
DataInputStream data = new  DataInputStream(buff);

try {
   int num1 = data.readInt();
   int num2 = data.readInt();
   float num2 = data.readFloat();
   float num3 = data.readFloat();
   float num4 = data.readFloat();
   double num5 = data.readDouble();
} catch (EOFException eof) {...}

Class StreamTokenizer
Sometimes you need to parse a stream without knowing in advance what data types you are getting. In this case you want to get each "piece of data" (token) based on the fact that a delimiter such as a space, comma, etc separates the data elements.

The class java.io.StreamTokenizer reads tokens one at a time. It can recognize identifiers, numbers, quoted strings, etc. Typically an application creates an instance of this class, sets up the rules for parsing, and then repeatedly calls the method nextToken() until it returns the value TT_EOF (end of file).

Let's write a program that will read and parse the file customers.txt distinguishing strings from numbers.

Suppose we have a file customers.txt with the following content:

John Smith  50.24
Mary Lou  234.29
Alexander Popandopula  456.11

Here is the program that parses it:

import java.io.StreamTokenizer;
import java.io.FileReader;

public class CustomerTokenizer{
  public static void main(String args[]){

  StreamTokenizer stream =null;
  try{
    stream = new StreamTokenizer( new
                            FileReader("customers.txt"));
    while (true) {

         int token = stream.nextToken();
         if (token == StreamTokenizer.TT_EOF)
             break;
         if (token == StreamTokenizer.TT_WORD) {
             System.out.println("Got the string: " +
                                         stream.sval);
             }
         if (token == StreamTokenizer.TT_NUMBER) {
             System.out.println("Got the number: " +
                                         stream.nval);
             }
        }
      }catch (Exception e){
         System.out.println("Can't read Customers.txt: " +
                                             e.toString());
      }
      finally{
          try{
             stream.close();
          }catch(Exception e){e.printStackTrace();}        
      }
   }
}

After compiling and running the program CustomerTokenizer, the system console will look like this:

javac CustomerTokenizer.java

java CustomerTokenizer

Got the string: John
Got the string: Smith
Got the number: 50.24
Got the string: Mary
Got the string: Lou
Got the number: 234.29
Got the string: Alexander
Got the string: Popandopula
Got the number: 456.11

When a StreamTokenizer finds a word, it places the value into the sval member variable, and the numbers are placed into the variable nval.

You can specify characters that should be treated as delimiters by calling the method whitespaceChars(). The characters that represent quotes in the stream are set by calling the method quoteChar().

To make sure that certain characters are not misinterpreted, call a method ordinaryChar(), for example ordinaryChar('/');

Class StringTokenizer
The class java.util.StringTokenizer is a simpler version of a class StreamTokenizer, but it works only with strings. The set of delimiters could be specified at the creation time, i.e. comma and angle brackets:

StringTokenizer st = new StringTokenizer(
              "Yakov, 12 Main St., New York", ",<>");
while (st.hasMoreTokens()) {
    System.out.println(st.nextToken());
}

The above code fragment would print the following:

HTML
Yakov
12 Main St.
New York

The previous sample would not return the value of a delimiter - it just returned the tokens. But sometimes, in case of multiple delimiters, you may want to know what's the current delimiter. The 3-argument constructor will provide this information. The following example defines 4 delimiters: greater and less then signs, comma and a white space:

StringTokenizer st=new StringTokenizer( "...IBM...price<...>86.3", "<>, ", true);

If the third argument is true, delimiter characters are also considered to be tokens and will be returned to the calling method, so a program may apply different logic based on the delimiter. If you decide to parse HTML file, you'll need to know what's the current delimiter to apply the proper logic.

Class File
This class has a number of useful file maintenance methods that allow rename, delete, perform existence check, etc. First you have to create an instance of this class:

File myFile = new File("abc.txt");

The line above does not actually create a file - it just creates an instance of the class File that is ready to perform some manipulations with the file abc.txt.The method createNewFile() should be used for the actual creation of the file.

Below are some useful methods of the class File:

   1. createNewFile()creates a new, empty file named according to the file name used during the File instantiation. It creates a new file only if a file with this name does not exist
   2. delete() deletes file or directory
   3. renameTo() renames a file
   4. length() returns the length of the file in bytes
   5. exists() tests whether the file with specified name exists
   6. list() returns an array of strings naming the files and directories in the specified directory
   7. lastModified() returns the time that the file was last modified
   8. mkDir() creates a directory

The code below creates a renames a file customers.txt to customers.txt.bak. If a file with such name already exists, it will be overwritten.

File file = new File("customers.txt");
File backup = new File("customers.txt.bak");
if (backup.exists()){
 backup.delete();
}
file.renameTo(backup);

Wednesday, March 28, 2012

why java does not support multiple inheritance

Java supports multiple inheritence indirectly through the
use of interface. In case we are able to extend more than
one class then there would be a confusion of which method to
process in case both classes have same method name(Same
method signature also). 

In case of using interfaces to support multiple inheritance
we escape this problem as we define the methods that are
needed only.
 
Q. You can create an abstract class that contains only abstract methods.
 On the other hand, you can create an interface that declares the same 
methods. So can you use abstract classes instead of interfaces?

A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
 

Java Exceptions

What Is an Exception?

The term exception is shorthand for the phrase "exceptional event."

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).



The call stack.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

 

Searching the call stack for the exception handler.
Using exceptions to manage errors has some advantages over traditional error-management techniques.

The Catch or Specify Requirement

Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following:
Code that fails to honor the Catch or Specify Requirement will not compile.
Not all exceptions are subject to the Catch or Specify Requirement. To understand why, we need to look at the three basic categories of exceptions, only one of which is subject to the Requirement.

The Three Kinds of Exceptions

 

The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.
Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.
Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. For example, consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.
Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.
Errors and runtime exceptions are collectively known as unchecked exceptions.


http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html 

The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).


Q. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

Q. What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?
Ans) Compilation fails. The catch block for handling the most specific exceptions must always be placed above the catch block written to handle the more general exceptions.
e.g. The code below will not compile.
1 try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
The code below will compile successfully :-
try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only
}

Strings, Literally

String literals are a little "special" in Java in the way that they are treated.
What is a String Literal? A String literal is a sequence of characters between quotation marks, such as "string" or "literal".

Strings are Immutable

So what makes String literals so special? Well, first of all, it's very important to remember that String objects are immutable. That means that, once created, a String object cannot be changed (short of using something like reflection to get at private data). Immutable, you say? Unchangable? What about this code?

public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String start = "Hello";
        String end = start.concat(" World!");
        System.out.println(end);
    }
}

// Output

Hello World!
 
Well look at that, the String changed...or did it? In that code, no 
String object was ever changed. We start by assigning "Hello" to our 
variable, start. That causes a new String object to be created on the 
heap and a reference to that object is stored in start. Next, we invoke 
the method concat(String) on that object. Well, here's the trick, if we look
at the API Spec for String, you'll see this in the description of the 
concat(String) method:
Concatenates the specified string to the end of this string. 
If the length of the argument string is 0, then this String object is returned.
Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. Examples:     "cares".concat("s") returns "caress"     "to".concat("get").concat("her") returns "together" Parameters:     str - the String that is concatenated to the end of this String. Returns:     a string that represents the concatenation of this object's characters followed by
the string argument's characters.
Notice the part I've highlighted in bold. When you concatenate one String to another, it doesn't actually change the String object, it simply creates a new one that contains the contents of both of the original Strings, one after the other. That's exactly what we did above. 
 
The String object referenced by the local variable start never changed. 
In fact, if you added the statement System.out.println(start); after you 
invoked the concat method, you would see that start
still referenced a String object that contained just "Hello". And just 
in case you were wondering, the '+' operator does the exact same thing 
as the concat() method.

Strings really are immutable.
 

Storage of Strings - The String Literal Pool

 What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. Really, it's a collection of references to String objects. Strings, even though they are immutable, are still objects like any other in Java. Objects are created on the heap and Strings are no exception. So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.

Yeah, so that doesn't really explain what the pool is, or what it's for, does it? Well, because String objects are immutable, it's safe for multiple references to "share" the same String object. Take a look at this example:
 
public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String one = "someString";
        String two = "someString";
        
        System.out.println(one.equals(two));
        System.out.println(one == two);
    }
}

// Output

true
true 
 
In such a case, there is really no need to make two instances of an 
identical String object. If a String object could be changed, as a 
StringBuffer can be changed, we would be forced to create two separate 
objects. But, as we know that String objects cannot change, we can 
safely share a String object among the two String references, one and two.
This is done through the String literal pool. Here's how it is accomplished:


When a .java file is compiled into a .class file, any String literals 
are noted in a special way, just as all constants are. When a class is loaded
(note that loading happens prior to initialization), the JVM goes 
through the code for the class and looks for String literals. When it 
finds one, it checks to see if an equivalent String is already 
referenced from the heap. If not, it creates a String instance on the 
heap and stores a reference to that object in the constant table. Once a
reference is made to that String object, any references to that String 
literal throughout your program are simply replaced with the reference 
to the object referenced from the String Literal Pool.



So, in the example shown above, there would be only one entry in the 
String Literal Pool, which would refer to a String object that contained
the word "someString". Both of the local variables, one and two,
would be assigned a reference to that single String object. You can see
that this is true by looking at the output of the above program. While 
the equals() method checks to see if the String objects contain the same
data ("someString"), the == operator, when 
used on objects, checks for referential equality - that means that it 
will return true if and only if the two reference variables refer to the
exact same object. In such a case, the references are equal. From the 
above output, you can see that the local variables, one and two, not only 
refer to Strings that contain the same data, they refer to the same object.

Graphically, our objects and references would look something like this: 
Note, however, that this is a special behavior for String Literals
Constructing Strings using the "new" keyword implies a different sort of behavior.
 
Let's look at an example:
 
 public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String one = "someString";
        String two = new String("someString");
        
        System.out.println(one.equals(two));
        System.out.println(one == two);
    }
}

// Output

true
false
 
In this case, we actually end up with a slightly different behavior 
because of the keyword "new." In such a case, references to the two 
String literals are still put into the constant table (the String 
Literal Pool), but, when you come to the keyword "new," the JVM is 
obliged to create a new String object at run-time, rather than using the
one from the constant table.

In such a case, although the two String references refer to String objects 
that contain the same data, "someString", they do not refer to the same object.
That can be seen from the output of the program. While the equals() method 
returns true, the == operator, which checks for referential equality, returns
false, indicating that the two variables refer to distinct String objects.

Once again, if you'd like to see this graphically, it would look 
something like this. Note that the String object referenced from the 
String Literal Pool is created when the class is loaded while the other 
String object is created at runtime, when the "new String..." line is 
executed.
 
If you'd like to get both of these local variables to refer to the same object, 
you can use the intern() method defined in String. Invoking two.intern()
will look for a String object referenced from the String Literal Pool 
that has the same value as the one you invoked the intern method upon. 
If one is found, a reference to that String is returned and can be 
assigned to your local variable. If you did so, you'd have a picture 
that looks just like the one above, with both local variables, one and two,
referring to the same String object, which is also referenced from the 
String Literal Pool. At that point, the second String object, which was 
created at run-time, would be eligible for garbage collection.
 

Garbage Collection

What makes an object eligible for garbage collection? If you're preparing for the SCJP exam (or even if you're not), the answer to that question should roll right off your tongue. An object is eligible for garbage collection when it is no longer referenced from an active part of the application. Anyone see what is special about garbage collection for String literals? Let's look at an example and see if you can see where this is going.

public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String one = "someString";
        String two = new String("someString");
        
        one = two = null;
    }
} 
Just before the main method ends, how many objects are available for garbage 
collection? 0? 1? 2? 

The answer is 1. Unlike most objects, String literals always have a 
reference to them from the String Literal Pool. That means that they always
have a reference to them and are, therefore, not eligible for garbage 
collection. This is the same example as I used above so you can see what
our picture looked liked originally there. Once we assign our 
variables, one and two, to null, we end up with a picture that looks like this:
 
 
 
As you can see, even though neither of our local variables, one or two,
refer to our String object, there is still a reference to it from the 
String Literal Pool. Therefore, the object is not elgible for garbage 
collection. The object is always reachable through use of the intern() 
method, as referred to earlier.

Conclusion

Like I said at the outset of this article, virtually none of this information is included on the SCJP exam. However, I constantly see this question coming up in the SCJP forum and on various mock exams. These are a few of the highlights you can keep in mind when it comes to String literals:
  • Equivalent String Literals (even those stored in separate classes in separate packages) will refer to the same String object.
  • In general, String Literals are not eligible for garbage collection. Ever.
  • Strings created at run-time will always be distinct from those created from String Literals.
  • You can reuse String Literals with run-time Strings by utilizing the intern() method.
  • The best way to check for String equality is to use the equals() method.
 

Object Reference Type Casting in Java

In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java.
How to Typecast Objects with a dynamically loaded Class ? – The casting of object references depends on the relationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object, because the Object class is a superclass of every Java class.
There can be 2 casting java scenarios
· Upcasting
· Downcasting


When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses, it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it is an upcast. We need not use a cast operator in this case.
The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship) At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is being cast to.
Below is an example showing when a ClassCastException can occur during object casting

//X is a supper class of Y and Z which are sibblings.
public class RunTimeCastDemo {

 public static void main(String args[]) {
  X x = new X();
  Y y = new Y();
  Z z = new Z();
  X xy = new Y(); // compiles ok (up the hierarchy)
  X xz = new Z(); // compiles ok (up the hierarchy)
  //  Y yz = new Z();   incompatible type (siblings)
  //  Y y1 = new X();   X is not a Y
  //  Z z1 = new X();   X is not a Z
  X x1 = y; // compiles ok (y is subclass of X)
  X x2 = z; // compiles ok (z is subclass of X)
  Y y1 = (Y) x; // compiles ok but produces runtime error
  Z z1 = (Z) x; // compiles ok but produces runtime error
  Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
  Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
  //  Y y3 = (Y) z;     inconvertible types (siblings)
  //  Z z3 = (Z) y;     inconvertible types (siblings)
  Object o = z;
  Object o1 = (Y) o; // compiles ok but produces runtime error
 }
}

Type Casting in Java

//Integer code1
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=Integer.parseInt(s);
System.out.println(i);
Float f=99.7f;
int i1=Integer.parseInt(f);
}
}

//Integer code2
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=(int)s;
System.out.println(i);
}
}


//Integer to String
int a=97;
String s=Integer.toString(a);

(or)
String s=””+a;


//Double to String
String s=Double.toString(doublevalue);

//Long to String
String s=Long.toString(longvalue);

//Float to String
String s=Float.toString(floatvalue);

//String to Integer
String s=”7”;
int i=Integer.valueOf(s).intValue();

(or)
int i = Integer.parseInt(s);

//String to Double
double a=Double.valueOf(s).doubleValue();

//String to Long
long lng=Long.valueOf(s).longValue();

(or)
long lng=Long.parseLong(s);

//String to Float
float f=Float.valueOf(s).floatValue();

//Character to Integer
char c=’9’;
int i=(int)c;

//String to Character
String s=”welcome”;
char c=(char)s;

Sunday, March 25, 2012

Java Collections

The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects.Rather than having to write your own collection classes, Java provides these ready-to-use collection classes for you.

In order to understand and use the Java Collections API effectively it is useful to have an overview of the interfaces it contains. So, that is what I will provide here.
There are two "groups" of interfaces: Collection's and Map's.
Here is a graphical overview of the Collection interface hierarchy:



And here is a graphical overview of the Map interface hierarchy:

 
In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys.
When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework.
  • The Collection interface is a group of objects, with duplicates allowed.
  • Set extends Collection but forbids duplicates.
  • List also extends Collection, allows duplicates and introduces positional indexing.
  • Map extends neither Set nor Collection

Interface
Implementation
Historical
Set
HashSet

TreeSet


List

ArrayList

LinkedList
Vector
Stack
Map
HashMap

Treemap

Hashtable
Properties

The historical collection classes are called such because they have been around since 1.0 release of the java class libraries. If you are moving from historical collection to the new framework classes, one of the primary differences is that all operations are synchronized with the new classes. While you can add synchronization to the new classes, you cannot remove from the old.

Iterable :

The Iterable interface (java.lang.Iterable) is one of the root interfaces of the Java collection classes. The Collection interface extends Iterable, so all subtypes of Collection also implement the Iterable interface.

The iterator() method of the Collection interface returns and Iterator. An Iterator is similar to the Enumeration interface, Iterators differ from enumerations in two ways:
1.Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
2. Method names have been improved.  


A class that implements the Iterable can be used with the new for-loop. Here is such an example:

List list = new ArrayList();

for(Object o : list){
    //do something o;    
}

Iteratable usage in java 5 with generics:

ArrayList<String> alist = new ArrayList<String>();
// . . . Add Strings to alist

for (Iterator<String> it = alist.iterator(); it.hasNext(); ) {
    String s = it.next();  // No downcasting required.
    System.out.println(s);
}

 Example pre Java 5, with explicit iterator and downcasting

An iterator might be used as follows :
ArrayList alist = new ArrayList(); // This holds type Object.
// . . . Add Strings to alist

for (Iterator it = alist.iterator(); it.hasNext(); ) {
    String s = (String)it.next();  // Downcasting is required pre Java 5.
    System.out.println(s);
}

Iterator Methods

Iterator defines three methods, one of which is optional.
ResultMethod Description
b = it.hasNext() true if there are more elements for the iterator.
obj = it.next() Returns the next object. If a generic list is being accessed, the iterator will return something of the list's type. Pre-generic Java iterators always returned type Object, so a downcast was usually required.
it.remove() Removes the most recent element that was returned by next. Not all collections support delete. An UnsupportedOperationException will be thrown if the collection does not support remove().

Q: What does this loop do? Note mixing of iterator with index.
 
ArrayList<String> alist = new ArrayList<String>();
// . . . Add Strings to alist

int i = 0;
for (Iterator<String> it = alist.iterator(); it.hasNext(); ) {
    System.out.println(alist.get(i++));
}
 
A: It throws an exception when it goes beyond the end.
After hasNext() returns true, the only way to advance the iterator is to call next(). But the element is retrived with get(), so the iterator is never advanced. hasNext() will continue to always be true (ie, there is a first element), and eventually the get() will request something beyond the end of the ArrayList. 
Use either the iterator scheme.
for (Iterator<String> it = alist.iterator(); it.hasNext(); ) {
    System.out.println(it.next());
}
Or the indexing scheme, but don't mix them.
for (int i=0; i < alist.size(); i++) {
    System.out.println(alist.get(i));
}

ListIterator methods

ListIterator is implemented only by the classes that implement the List interface (ArrayList, LinkedList, and Vector). ListIterator provides the following.
ResultMethod Description
Forward iteration
b = it.hasNext() true if there is a next element in the collection.
obj = it.next() Returns the next object.
Backward iteration
b = it.hasPrevious() true if there is a previous element.
obj = it.previous() Returns the previous element.
Getting the index of an element
i = it.nextIndex() Returns index of element that would be returned by subsequent call to next().
i = it.previousIndex() Returns index of element that would be returned by subsequent call to previous().
Optional modification methods. UnsupportedOperationException thrown if unsupported.
it.add(obj) Inserts obj in collection before the next element to be returned by next() and after an element that would be returned by previous().
it.set() Replaces the most recent element that was returned by next or previous().
it.remove() Removes the most recent element that was returned by next() or previous().


Java Generics - Implementing the Iterable Interface

It is possible to use your own collection type classes with the new for-loop. To do so, your class must implement the java.lang.Iterable<E> interface. Here is a very basic example:
public class MyCollection<E> implements Iterable<E>{

    public Iterator<E> iterator() {
        return new MyIterator<E>();
    }
}
And here is the corresponding implementation skeleton of the MyIterator class:
public class MyIterator <T> implements Iterator<T> {

    public boolean hasNext() {
    
        //implement...
    }

    public T next() {
        //implement...;
    }

    public void remove() {
        //implement... if supported.
    }
}
Here is how to use the MyCollection generified, and with the new for-loop:
public static void main(String[] args) {
    MyCollection<String> stringCollection = new MyCollection<String>();

    for(String string : stringCollection){

    }
}

Other Java Collections basics :

http://tutorials.jenkov.com/java-collections/sorting.html



Monday, March 19, 2012

Encapsulation is not information hiding

The principles of information hiding go beyond the Java language facility for encapsulation

Encapsulation is a language construct that facilitates the bundling of data with the methods operating on that data. Information hiding is a design principle that strives to shield client classes from the internal workings of a class. Encapsulation facilitates, but does not guarantee, information hiding. Smearing the two into one concept prevents a clear understanding of either.
The Java language manifestation of encapsulation doesn't even ensure basic object-oriented objects. The argument is not necessarily that it should, just that it doesn't. Java developers can blithely create bags of data in one class and place utility functions operating on that data in a separate class. So as a first rule: 

Encapsulation rule 1: Place data and the operations that perform on that data in the same class


This standard practice creates classes that adhere to the principles of abstract data types.
But you want more of your objects; you want them to represent cohesive, workable entities. A second rule concerns the manner of choosing the data and operations to encapsulate: 

Encapsulation rule 2: Use responsibility-driven design to determine the grouping of data and operations into classes


This second encapsulation rule actually pertains to information hiding as well: don't just bundle data and operations together; let design principles guide you. Ask yourself what actions an object of the class will be responsible for. Don't let the class encapsulate more or less than a comprehensive set of reasonable responsibilities.
As you have seen from the many examples above, the Java language encapsulation facility isn't enough to ensure a solid class design. The principle of information hiding stipulates that you shield an object's clients from the internal design decisions made for that class of objects. So as a first rule for information hiding: 

Information hiding rule 1: Don't expose data items


Make all data items private and use getters and setters. Don't fool yourself into believing no harm will result from directly accessing an object's internal data items. Even if only you code against those internals, future vulnerability still exists. You can't predict when you might need to change the internal data's nature, and brittle coupling with client objects sounds unnerving when shattered.
Go one step further when hiding design decisions concerning internal data. When possible, don't even reveal whether an attribute is stored or derived. Client objects don't need to know the difference. An attribute is a quality or characteristic inherent in a class of objects. From the client's perspective, object attributes correspond to responsibilities, not internal data structure. That brings us to the next rule: 

Information hiding rule 2: Don't expose the difference between stored data and derived data


For example, a client object only needs to know that an object has an attribute of speed. Use an accessor method named speed() or getSpeed() rather than calculateSpeed(). Whether the value is stored or derived is a design decision best kept hidden.
As a corollary to the first two information hiding rules, I place all internal data at the bottom of the class text, after the methods that operate on the data. When I examine a class to understand its code, looking first at its internal data leads me to ask the wrong initial questions. I strive to understand the responsibilities of a class before concerning myself with any data structure details. Placing data after methods in the class text reminds me, every time I look at the code, to think first about a class's behavior, not its structure.
The next rule concerns the choice of internal structure: 

Information hiding rule 3: Don't expose a class's internal structure


Clients should remain isolated from the design decisions driving the selection of internal class structure. For example, a client should not know whether a primitive array or an ArrayList is used to maintain an internal collection of objects. Internal structure is particularly apparent through the use of method names like getDataArray() or getTreeMap().
The final rule concerns choices of implementation details: 

Information hiding rule 4: Don't expose implementation details of a class


Don't allow clients to know or invisibly affect a class's implementation details. For example, a client should not be able to alter an internal calculation's result by changing the state of objects used in that supposedly hidden calculation.
Though not an exhaustive list, those rules help separate the concept of encapsulation provided by the language from the information hiding provided by design decisions. Each rule is fairly easy to follow, and each will assist in creating classes that are not only more resilient to change, but also more easily used by client objects.