Posts

Showing posts with the label Basic Java Tutorials

Simple Java Exception Handling Tips

Exceptions are errors that occur in runtime , that is , when the application is running. A careful developer should estimate and care about possible runtime errors. Let us give an example : String s = args[0]; int i = Integer.parseInt(s); this piece of code can cause some exceptions. For example args is an array of string. We want to read the first element of this array. What happens if args is null ? What happens if args is empty ? so we need to ensure that the array is not null and not empty.         String s = null ; // initialize s         // check the array is not null or empty         if ( args ! = null && args. length > 0 )             s = args [ 0 ] ;         int i = 0 ;         if ( s ! = null ) // if s is not null we can parse             i = Integer . parseInt ( s ) ;   ...

Get MimeType of A File

Use activation.jar to access javax.activation API. File file = new File("foo.jpg"); String mimeType = new MimetypesFileTypeMap().getContentType(file)); // image/jpeg alternatively , you can use filename to detech the mime type : String mimeType = new MimetypesFileTypeMap().getContentType("foo.jpg")); // image/jpeg

Java MD5 Hash Sample

MD5 (Message Digest) is an encryption algorithm that creates a unique hash from a given data which is completely reverseble. This means you cannot recalculate original data using its hash , and hash is universally unique. Here is a sample code that produces MD5 hash of a given string : package javacream ; import java.security.MessageDigest ; import java.security.NoSuchAlgorithmException ; public class MD5HashTest {     private static String getMD5Digest ( String str ) {         try {             byte [ ] buffer = str. getBytes ( ) ;             byte [ ] result = null ;             StringBuffer buf = null ;             MessageDigest md5 = MessageDigest . getInstance ( "MD5" ) ;             //allocate room for the hash ...

What is NullPointerException ?

NullPointerException is the most common exception of the Java world. It occurs when you try to call method or modify and attiribute of a null object. Here is an example : String strObject = null ; int len = strObject .length(); // throws a NullPointerException The code tried to access a null string's length() method so it is illegal. There is no strObject so there is no length() of it. To avoid NullPointerException you should check the of object if it is null before accessing it's members. For example in the jsp code below , we want to get userName from HTTP Post parameters , and print an error message if the length is less than 6 : String userName = request.getParameter( "userName" ); if ( userName.length() out.print( "Invalid Username" ); return ; } This code fails when the user in logon page sends an empty string for userName. The code will be better if we check the object is null before access its method : Str...

Sort a HashMap based on Keys or Values

Sort based on keys is simple , just dump the map into TreeMap (TreeMap is sorted by nature) Map myMap = new HashMap(); // put keys and values... ..... Map sortedMap = new TreeMap(myMap); If you want to sort your HashMap based on values : HashMap map1 = new HashMap(); map1.put("cat",5); map1.put("cow",4); map1.put("dog",3); map1.put("horse",2); List mpKeys = new ArrayList(map1.keySet()); List mpValues = new ArrayList(map1.values()); HashMap map = new LinkedHashMap(); TreeSet sortedSet = new TreeSet(mapValues); Object[] sortedArray = sortedSet.toArray(); int size = sortedArray.length; // descending for (int i=size-1; i>=0; i--) System.out.println(mpKeys.get(mpValues.indexOf(sortedArray[i]))+" "+sortedArray[i]); Any discussions will be appreciated.

Arrays in Java

Image
Arrays in java are objects that hold fixed numbers of values of single type. Length of the array must be given at initalization , arrays cannot grow or shrink. Each element has an index value starting from 0 , so if you want to reach element 3 , index is 2.. Simple array initializations : // array of integer with the capacity of 2 integers int[] intArray = new int[2]; or , // [] goes to intArray which makes intArray[] int intArray[] = new int[2]; Element indexes start from 0(zero) , so the last element index of array above is 1, intArray[0] = 1; intArray[1] = 2; there is no intArray[2] because there is no third element. Capacity is 2. System.out.println("the length of intArray="+ intArray.length()); gives : the length of intArray=2 You can initialize our sample intArray easily like that : int intArray[] = new int[]{1,2}; The length of the array will be the same with number of elements you specified. You can also use Array classes' fill() method like this Array.fill(in...