Friday, May 15, 2009

Autoboxing and Unboxing in java example

Java is an Object Oriented programming language. We have to deal with primitive types and objects together.

Here autoboxing comes to play the role. It wraps the primitive data type into a object. There are wrapper classes for it.

For Example : -

 public class FormatPrint {

     public static void main(String[] args) {

       System.out.printf("There is only %d thing.", 1);

     }

   }


The signature of the printf() is

printf(String format, Object... args)

But, inthe above example i have printed a integer value. This is called as autoboxing. This can be used in Generics,too.

Here is java normal java generic example : -

 import java.util.ArrayList;

   public class ManualBoxing {

     public static void main(String[] args) {

        ArrayList list = new ArrayList();

        for(int i = 0; i < 10; i++){

            list.add(new Integer(i));

        }

     }

   }

But we don't need to "new Integer(i)". We can use autoboxing and simply the code as follow.

import java.util.ArrayList;

    public class Autoboxing {

      public static void main(String[] args) {

          ArrayList<Integer> list = new ArrayList<Integer>();

          for(int i = 0; i < 10; i++){

             list.add(i);

          }

      }

    }

For further details : -

http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html

Wednesday, May 13, 2009

Delete non empty directory in java

import java.io.File;

class DeleteDir {

public static void main(String args[]) {

deleteDirectory(new File(args[0]));

}

static public boolean deleteDirectory(File path) {

if( path.exists() ) {

File[] files = path.listFiles();

for(int i=0; i<files.length; i++) {

if(files[i].isDirectory()) {

deleteDirectory(files[i]);

}

else {

files[i].delete();

}

}

}

return( path.delete() );

}

}