Friday, November 26, 2010

Java Collections

Collections

The Collections Framework in Java, which took shape with the release of JDK 1.2 and was expanded in 1.4 and again in Java 5, gives you lists, sets, maps, and queues to satisfy most of your coding needs. They've been tried, tested, and tweaked. Pick the best one for your job and you'll get—at the least—reasonable performance. And when you need something a little more custom, the Collections Framework in the java.util package is loaded with interfaces and utilities.

So What Do You Do with a Collection?

There are a few basic operations you'll normally use with collections
  •  Add objects to the collection.
  •  Remove objects from the collection.
  • Find out if an object (or group of objects) is in the collection.
  • Retrieve an object from the collection (without removing it).
  • Iterate through the collection, looking at each element (object) one after another.
 Key Interfaces and Classes of the Collections Framework 

The collections API begins with a group of interfaces, but also gives you a truckload of concrete classes.

MapsSetsListsQueuesUtilities
HashMapHashSetArrayListPriorityQueueCollections
HashtableLinkedHashSetVectorArrays
TreeMapTreeSetLinkedList
LinkedHashMap

Not all collections in the Collections Framework actually implement the Collection interface. In other words, not all collections pass the IS-A test for Collection. Specifically, none of the Map-related classes and interfaces extend from Collection. So while SortedMap, Hashtable, HashMap, TreeMap, and LinkedHashMap are all thought of as collections, none are actually extended from Collection-with-a-capital-C (see below Figure). To make things a little more confusing, there are really three overloaded uses of the word "collection":
  • collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over.
  • Collection (capital C), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That's right, extend, not implement.
    There are no direct implementations of Collection.)
  • Collections (capital C and ends with s) is the java.util.Collections class that holds a pile of static utility methods for use with collections.
The interface and class hierarchy for collections

Collections come in four basic flavors:

  • Lists Lists of things (classes that implement List).
  • Sets Unique things (classes that implement Set).
  • Maps Things with a unique ID (classes that implement Map).
  • Queues Things arranged by the order in which they are to be processed.
The structure of a List, a Set, and a Map
Ordered When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order.

Sorted A sorted collection means that the order in the collection is determined according to some rule or rules, known as the sort order.

List Interface
A List cares about the index. The one thing that List has that non-lists don't have is a set of methods related to the index. Those key methods include things like get(int index), indexOf(Object o), add(int index, Object obj), and so on. All three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end. The three List implementations are described in the following sections.

1 . ArrayList Think of this as a growable array. It gives you fast iteration and fast random access. To state the obvious: it is an ordered collection (by index), but not sorted. You might want to know that as of version 1.4, ArrayList now implements the new RandomAccess interface—a marker interface (meaning it has no methods) that says, "this list supports fast (generally constant time) random access." Choose this over a LinkedList when you need fast iteration but aren't as likely to be doing a lot of insertion and deletion.

2 . Vector Vector is a holdover from the earliest days of Java; Vector and Hashtable were the two original collections, the rest were added with Java 2 versions 1.2 and 1.4. A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety. You'll normally want to use ArrayList instead of Vector because the synchronized methods add a performance hit you might not need. And if you do need thread safety, there are utility methods in class Collections that can help. Vector is the only class other than ArrayList to implement RandomAccess.

3. LinkedList A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek(), poll(), and offer().


Set Interface
A Set cares about uniqueness—it doesn't allow duplicates. Your good friend the equals() method determines whether two objects are identical (in which case only one can be in the set). The three Set implementations are described in the following sections.

1. HashSet A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

2. LinkedHashSet A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

3. TreeSet The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure (but you knew that), and guarantees that the elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.

Map Interface
A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects. You're probably quite familiar with Maps since many languages support data structures that use a key/value or name/value pair. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

1. HashMap The HashMap gives you an unsorted, unordered Map. When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead. Where the keys land in the Map is based on the key's hashcode, so, like HashSet, the more efficient your hashCode() implementation, the better access performance you'll get.HashMap allows one null key and multiple null values in a collection.

2. Hashtable Like Vector, Hashtable has existed from prehistoric Java times. For fun, don't forget to note the naming inconsistency: HashMap vs. Hashtable. Where's the capitalization of t? Oh well, you won't be expected to spell it. Anyway, just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the synchronized counterpart to HashMap. Remember that you don't synchronize a class, so when we say that Vector and Hashtable are synchronized, we just mean that the key methods of the class are synchronized. Another difference, though, is that while HashMap lets you have null values as well as one null key, a Hashtable doesn't let you have anything that's null.

3. LinkedHashMap Like its Set counterpart, LinkedHashSet, the LinkedHash-Map collection maintains insertion order (or, optionally, access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.

4. TreeMap You can probably guess by now that a TreeMap is a sorted Map. And you already know that by default, this means "sorted by the natural order of the elements." Like TreeSet, TreeMap lets you define a custom sort order (via a Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to one another when they're being ordered.

Queue Interface
A Queue is designed to hold a list of "to-dos," or things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

1. PriorityQueue This class is new with Java 5. Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.

Tuesday, November 9, 2010

Legal Java Identifiers

Technically, legal identifiers must be composed of only Unicode characters,numbers, currency symbols, and connecting characters (like underscores).

  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.
  • You can't use a Java keyword as an identifier. Below table lists all of the Java keywords including one new one for 5.0, enum.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
Examples of legal and illegal identifiers follow, first some legal identifiers:

  int _a;
  int $c;
  int ______2_w;
  int _$;
  int this_is_a_very_detailed_name_for_an_identifier;

The following are illegal:

  int :b;
  int -d;
  int e#;
  int .f;
  int 7g;

Complete List of Java Keywords (assert added in 1.4, enum added in 1.5)

abstractbooleanbreakbytecasecatch
charclassconstcontinuedefaultdo
doubleelseextendsfinalfinallyfloat
forgotoifimplementsimportinstanceof
intinterfacelongnativenewpackage
privateprotectedpublicreturnshortstatic
strictfpsuperswitchsynchronizedthisthrow
throwstransienttryvoidvolatilewhile
assertenum

Tuesday, August 31, 2010

Java : How to throw custom Exception

In java many times we required to throw our own custom Exception. We can throw our custom Exception by creation our own Exception class which will extend from class java.lang.Exception.

Before going to example lets look at few points about Exception Handling from book "Sun Certified Java Programmer SCJP 5" by Kathy sierra.

Handling Exceptions
  • Exceptions come in two flavors: checked and unchecked.
  • Checked exceptions include all subtypes of Exception, excluding classes
    that extend RuntimeException.
  • Checked exceptions are subject to the handle or declare rule; any method
    that might throw a checked exception (including methods that invoke methods
    that can throw a checked exception) must either declare the exception
    using throws, or handle the exception with an appropriate try/catch.
  • Subtypes of Error or RuntimeException are unchecked, so the compiler
    doesn't enforce the handle or declare rule. You're free to handle them, or to
    declare them, but the compiler doesn't care one way or the other.
  • If you use an optional finally block, it will always be invoked, regardless of
    whether an exception in the corresponding try is thrown or not, and regardless
    of whether a thrown exception is caught or not.
  • The only exception to the finally-will-always-be-called rule is that a finally
    will not be invoked if the JVM shuts down. That could happen if code
    from the try or catch blocks calls System.exit().
  • Just because finally is invoked does not mean it will complete. Code in the
    finally block could itself raise an exception or issue a System.exit().
  • Uncaught exceptions propagate back through the call stack, starting from
    the method where the exception is thrown and ending with either the first
    method that has a corresponding catch for that exception type or a JVM
    shutdown (which happens if the exception gets to main(), and main() is
    "ducking" the exception by declaring it).
  • You can create your own exceptions, normally by extending Exception or
    one of its subtypes. Your exception will then be considered a checked exception,
    and the compiler will enforce the handle or declare rule for that exception.
  • All catch blocks must be ordered from most specific to most general.
    If you have a catch clause for both IOException and Exception, you must
    put the catch for IOException first in your code. Otherwise, the IOException
    would be caught by catch(Exception e), because a catch argument
    can catch the specified exception or any of its subtypes! The compiler will
    stop you from defining catch clauses that can never be reached.
  • Some exceptions are created by programmers, some by the JVM.

Lets see a simple example which will throw a custom Exception.

In this example we have a method acceptsEvenNumber(int number) which accepts only even number, it it encounters odd number it throws our custom Exception ie "MyException".
Here our class MyException extends java.lang.Exception also observe the constructor MyException(String message) which calls its super constructor.

To know more look API.

/* MyException.java */

public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
  
    //This method throws custom Exception
    public static void acceptsEvenNumber(int number) throws MyException {
      
        if(number %2 == 0) {
          
            System.out.println("It is Even number");
        }
        else {
          
            throw new MyException("Odd number not allowed");
        }
      
    }

    public static void main(String[] args) {
      
        try {
           

            //acceptsEvenNumber(23); //odd number
            acceptsEvenNumber(22); //even number
          
        } catch (MyException e) {
          
            e.printStackTrace();
        }
    }

}



Output

When Even Number

#>java MyException
It is Even number

When Odd Number

#>java MyException
MyException: Odd number not allowed
        at MyException.acceptsEvenNumber(MyException.java:16)
        at MyException.main(MyException.java:25)

Friday, August 27, 2010

Java : Simple program to get system properties

If you want to know your system properties or you want to create properties file listing all properties of your system. Lets see a simple java program which lists all system properties of your computer.

/* MySystemProperties.java */

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class MySystemProperties {
  
    public static void main(String[] args) {
      
        System.out.println("# My System Properties");
      
        Properties properties = System.getProperties();
      
        Set<String> propertiesSet = properties.stringPropertyNames();
      
        Iterator<String> iterator =  propertiesSet.iterator();
      
        String name;
      
        while (iterator.hasNext()) {
          
            name = iterator.next();
            System.out.println(name+" = "+properties.getProperty(name));
        }
      
    }

}


Output (output may differ depending on your computers properties)

# My System Properties
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jre6\bin
java.vm.version = 17.0-b17
java.vm.vendor = Sun Microsystems Inc.
java.vendor.url = http://java.sun.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = Service Pack 3
java.vm.specification.name = Java Virtual Machine Specification
user.dir = C:\MY\Code\Test
java.runtime.version = 1.6.0_21-b07
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jre6\lib\endorsed
os.arch = x86
java.io.tmpdir = c:\temp\
line.separator =

java.vm.specification.vendor = Sun Microsystems Inc.
user.variant =
os.name = Windows XP
sun.jnu.encoding = Cp1252
java.library.path = C:\WINXP\system32;.;C:\WINXP\Sun\Java\bin;C:\WINXP\system32;C:\WINXP;C:\WINXP\system32;C:\WINXP\;C:\WINXP\System32\Wbem;C:\WINXP\system32\nls;C:\WINXP\system32\nls\ENGLISH;C:\Program Files\UltraEdit\;C:\Program Files\CA\SC\CAWIN\;C:\Program Files\IBM\Personal Communications\;C:\Program Files\IBM\Trace Facility\;C:\WINXP\system32;C:\WINXP;C:\WINXP\System32\Wbem;C:\WINXP\system32\nls;C:\WINXP\system32\nls\ENGLISH;c:\Program Files\Novell\ZENworks\;C:\PROGRA~1\CA\SC\CAM\bin;C:\Program Files\CA\DSM\bin;C:\Program Files\SSH\SecureCRT\;C:\Program Files\SSH\SecureFX\;C:\Program Files\Rational\common;C:\Program Files\SQLLIB\FUNCTION;C:\Program Files\SQLLIB\help\;C:\Program Files\SQLLIB\samples\repl\;C:\Program Files\IBM\IMNNQ\;C:\Program Files\SQLLIB\bin\;C:\PROGRA~1\IBM\SQLLIB\BIN;C:\PROGRA~1\IBM\SQLLIB\FUNCTION;C:\Program Files\Java\jre6\bin;C:\Program Files\Java\jdk1.6.0_21\bin;C:\Program Files\Java\jdk1.6.0_21\bin;C:\Program Files\Java\jre6\bin;Z:.;Y:.;X:.
java.specification.name = Java Platform API Specification
java.class.version = 50.0
sun.management.compiler = HotSpot Client Compiler
os.version = 5.1
user.home = C:\Documents and Settings\madan
user.timezone =
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.6
user.name = madan
java.class.path = .
java.vm.specification.version = 1.0
sun.arch.data.model = 32
java.home = C:\Program Files\Java\jre6
java.specification.vendor = Sun Microsystems Inc.
user.language = en
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode, sharing
java.version = 1.6.0_21
java.ext.dirs = C:\Program Files\Java\jre6\lib\ext;C:\WINXP\Sun\Java\lib\ext
sun.boot.class.path = C:\Program Files\Java\jre6\lib\resources.jar;C:\Program Files\Java\jre6\lib\rt.jar;C:\Program Files\Java\jre6\lib\sunrsasign.jar;C:\Program Files\Java\jre6\lib\jsse.jar;C:\Program Files\Java\jre6\lib\jce.jar;C:\Program Files\Java\jre6\lib\charsets.jar;C:\Program Files\Java\jre6\classes
java.vendor = Sun Microsystems Inc.
file.separator = \
java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi
sun.cpu.endian = little
sun.io.unicode.encoding = UnicodeLittle
sun.desktop = windows
sun.cpu.isalist = pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

Thursday, August 26, 2010

Java Decompiler : Simple Java Program to decompile .class files

I was wondering is there a java program to decompile a .class file of another java program or itself. I searched on internet but I didn't found any, latter I decided to write my own. but how..... lets see.

When we compile a java file, JVM creates .class file. But imagine you have a .class and you need to create its source .java file, in such case you can use java decompiler which creates .java file of a .class file.


However many times decompiled .java file is not 100% accurate but still more or less you will get idea about what the java file consist of.

There are many java decompiler available on internet.We will use JAD Java Decompiler to decompile our .class files because it can be easily integrated with our Java program.

To know more about JAD Decompiler click here, Also you can download latest version of JAD Decompiler. In our example we are using JAD 1.5.8 version ie jad158g.win.zip. Visit  http://www.varaneckas.com/jad to know more.

Installation

Unzip jad.zip file into any appropriate directory on your hard drive.
This will create two files:

    * an executable file named 'jad.exe' (Windows 9x/NT/2000) or 'jad' (UNIX)
    * README file 'Readme.txt', which contains the short user's manual

Note : You need to add jad.exe in your CLASS PATH
Simple way just put jad.exe in your java path For Eg : C:\Program Files\Java\jdk1.6.0_21\bin\jad.exe

To test your installation just type 'jad' in your command prompt, it should produce below output.




Now Lets see the decompile process and its command.

For example, lets say we have Test.class to which we need to decompile.

C:\Jad>jad Test.class
Parsing Test.class... Generating Test.jad

This will create Test.jad file which contains java code, don't worry .jad is default extension.

C:\Jad>jad -s .java Test.class
Parsing Test.class... Generating Test.java

using -s you can provide extension of the file. This will create Test.java.

Also you can provide destination folder where you want to decomiple the .class file.

C:\Jad>jad -s .java -d C:\Dest Test.class
Parsing Test.class... Generating C:\Dest\Test.java

This will create Test.java in our desire destination folder. To know more see the 'Readme.txt' file.

 Now we can write our java program which will use above mentioned system commands and can be used as Java decompiler program.

/* JadExample.java */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JadExample {

    public void runSystemCommand(String command) {
       
        try {
            Process p = Runtime.getRuntime().exec(command);
           
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
           
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
           
            String s = "";
           
            System.out.println("command :: "+command);
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
           
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }           
           
        } catch (IOException e) {
           
            e.printStackTrace();
        }       
    }
   
    public void decompile(String srcClassFile,String destFolder) {
       
        runSystemCommand("jad -s .java -d "+destFolder+" "+srcClassFile);
       
    }
   
    public static void main(String[] args) {
       
        JadExample obj = new JadExample();
       
        //obj.decompile("Test.class", "."); //Current directory
        obj.decompile("Test.class", "C:\\Test");
    }

}





Run the above program and see the output. If you like it do write comments or mail me madan712@gmail.com