Ad

Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Friday, 9 October 2009

To create and write data to CSV files in Java(using BufferedWriter)

CSV stands of comma separated values.csv files will have the data separated by the delimiter ','.we don't need to use the third party jars for writing data to the CSV files.A Simple straightforward approach is to use the BufferedWriter for writing data to csv files.Lets say we need to create a csv file which has employee details like employee id and name.
We can use the BufferdWriter for this as shown below

BufferedWriter br =new BufferedWriter(new FileWriter("D://test.CSV"));                                              
br.write("EMPID,EMPNAME");
br.write('\n');
br.write("E01,John");
br.write('\n');
br.write("E02,George");
br.close();


As shown in the above code,we used ',' delimiter to separate the data and '\n' operator to create the new line.when we run the above code,csv files will be generated in the specified directory and it will be as shown below

Saturday, 3 October 2009

Enhanced for loop in Java 5(To iterate the Collection objects)

Prior to version java 5 ,we can use only the Iterator interface to iterate the collections .The below code sample show us the typical use of iterator interface.

List strlist = new ArrayList();
strlist.add("one");
strlist.add("two");
strlist.add("three");
Iterator it=strlist.iterator();
while(it.hasNext())
{
System.out.println("String in Collections---"+it.next());                                                                          
}


Output:
String in Collections---one
String in Collections---two
String in Collections---three

But from version java 5,we can use the Enhanced for loops to iterate the collections instead of using iterator interface.Enhanced for loops will make the code looks easier and simpler as shown below


List<String> strlist = new ArrayList<String>();                                                                                        
strlist.add("one");
strlist.add("two");
strlist.add("three");
for(String str:strlist)
{
System.out.println("String in Collections---"+str);
}


Output:
String in Collections---one
String in Collections---two
String in Collections---three

Wednesday, 2 September 2009

java.util.ConcurrentModificationException in java


java.util.ConcurrentModificationException is thrown in collections,when one thread is iterating a collection and at the same time another thread is modifying it.This is also applicable to collection accessed by a single thread as well when it is being iterated and modified at the same time.Consider the below code where the arraylist is iterated by the for loop and being modified at the same time.


public class Test {  
                                                                                                                           
public static void main(String[] args) {
List<String> list= new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
for(String var:list) //Iterate the ArrayList
{
list.add(var.toUpperCase); //Add the new String to ArrayList
}

System.out.println("Elements:"+list);
}


}                                                                                                                                                             


when we try to run the above code,we will get the below exception

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at COM.Test.main(Test.java:17)


To avoid this exception,iterate the collection using the ListIterator and  for adding the object to the list use the add method of the ListIterator.Sample code is shown below:


public class Test {

public static void main(String[] args) {
List<String> list= new ArrayList<String>();                                                                                          
list.add("one");
list.add("two");
list.add("three");

ListIterator<String> itr=list.listIterator();
while(itr.hasNext())
{
   itr.add(itr.next().toUpperCase());
}
System.out.println("Elements:"+list);
}

}

When we run the above program,we will get the below output

Elements:[one, ONE, two, TWO, three, THREE]

Sunday, 30 August 2009

overriding hashcode and equals method

We need to override the hashcode and equals method for the object that has to be added in Collections which uses hash technique.Hence for collection like hashset,hashmap,linkedhashset and hashtable we need to override both the equals and hashcode method .

what does it really means overriding hashcode and equals method?why we need to do it?
    Map stores the object as Key-value pair.we will retrieve the value from Map,by passing key to it.when we add an key/value pair to the map,the hashcode of the Key(object) will be used to allocate a slot in the collection.Its something like an seat no where an object in the collection sits.To retrieve the value from Map,the same hashcode will be used to locate the object in Map.

Lets take a below sample class

Class Department
{
String name;
public Department(String name)
{
this.name=name;
}
public static void main (String [] args) {
HashMap map = new HashMap(); //Initialize the HashMap
Department d1= new Department("CHEMICAL"); //construct a Department Object
Department d2= new Department("PHYSICS"); //construct a Department Object
map.put(d1,"CHEMICALLAB"); //Add the String "CHEMICALLAB" to Map with key as d1
map.put(d2,"PHYSICSLAB"); //Add the String "PHYSICSLAB" to Map with key as d2
retrieveMap(map);
}
public void retrieveMap(HashMap map) //To retrive the value from Map
{
Department dep1= new Department("CHEMICAL");
Department dep2= new Department("PHYSICS");
System.out.prinntln("LABNAME1:"+map.get(dep1));//Retrieve the value by passing the Key
System.out.prinntln("LABNAME2:"+map.get(dep2));//Retrieve the value by passing the Key

}
}

when we run the above program,we will get the below output

LABNAME1:null
LABNAME2:null


But the expected output was
LABNAME1:CHEMICALLAB
LABNAME2:PHYSICSLAB


when we add the object d1 as key and Value as String "CHEMICALLAB" to HashMap,object(Superclass of all Classes)hashcode will be used to allocate a seat to key d1 in hashmap.The object hashcode method always return distinct integers for distinct objects.when we pass the key to retrieve the value associated ,it will locate the Key in the collection whose
(1) hashcode is same as the object hashcode which we passed
(2) key object in collection is same as passed key object according to the equals method.
Once the Key is found,the value associated with the key will be returned.

But we could not able to retrieve the value from haspmap,since we didn't override both the method.while we try to retrieve the value from hashmap in the above example
(1)object hashcode will be executed.Since the object d1(Key in collection) and dep1(key we passed) are distict objects,the hashcode method will return distinct values
(2) object equals method will be executed and it will return false. The object equals method will return true only if the the two references refer the same object ie if d1==dep1

Add the below methods to Department Class to override the hashcode and equals method

public boolean equals(Object obj) {                                                                                                          
Department key = (Department)obj;
return name.equals(key.name()) ;
}

public int hashCode() {
return name.hashCode();
}


and now the output will be as expected

LABNAME1:CHEMICALLAB
LABNAME2:PHYSICSLAB

Friday, 21 August 2009

How to iterate the HashMap?

Map has a Keyset method,which return the set of Keys in the Map.Then by iterating this Set,we can iterate the hashMap values as shown below

Map strMap= new HashMap();
strMap.put("1","one");
strMap.put("2","two");
strMap.put("3","three"); //Construct a HahMap
for(String key:strMap.keySet()) //keySet will give the set of keys                                                               
{
System.out.println("Key - "+key+" Value - "+strMap.get(key));
}

Output will be:
Key - 3 Value - three
Key - 2 Value - two
Key - 1 Value - one

we can iterate the hash map values alone by the Map "values()" method as shown below.
Map "Values()" method will return the collection view of the values present in the hashmap.

for(String value:strMap.values())
{
System.out.println(" Value - "+value);                                                                                                        
}

Output will be
Value - three
Value - two
Value - one

Thursday, 20 August 2009

Can we make an object ineligigle for Garbage collection by using finalize method

An object will become eligible for garbage collection,when its not referred by any reference variable.so when the object is garbage collected,the object memory will be claimed by the JVM.The object finalize method will be called before an object is garbage collected.

Lets come to our discussion.can we use this finalize method to make this object ineligible for garbage collection by passing this object to some reference.The answer is Yes,but only once.

Let says we have a object 'A' whose finalize method is overridden to pass the object reference to some other reference Variable.At some point during program execution,when an object 'A' doesn't not have any reference variable, it becomes eligible for garbage collection.when this object is about to garbage collected,object's finalize method is called.since in finalize method we have passed the this object to some reference variable,it become ineligible for garbage collection(As this object has been referred).At some later point when the same object does not have any reference ,it will again become eligible for garbage collection.But this time finalize method wont be called at the time of garbage collection.so the object will be garbage collected and the object memory will be claimed.

Hence finalize method will be called only once for any object before the garbage collection.Thus we can't make any object permanently ineligible for garbage collection not more than once by using finalize method.

Wednesday, 19 August 2009

Why String is called as immutable object?

As everyone knows String is called as immutable object.what does immutable object means? An immutable object is the one, whose state can't be changed or modified after its initial construction.

Lets take the below code

String s1=new String ("immutable"); // A new String object will be created("immutable") and s1 refer to it.
System.out.println("String-"+s1);
s1=s1.toUpperCase(); //A new string object will be created("IMMUTABLE") and s1 refer to it.
System.out.println("String-"+s1);

Output will be
String-immutable
String-IMMUTABLE

So when we try to modify the string object("immutable") by calling the toUppercase method on reference s1,a new string object is created instead of applying the changes to the existing object. Thus s1 will refer to the new object("IMMUTABLE") created and the old object("immutable") will lose the reference.
Hence there will be two objects created in the memory:

  1. A string object "immutable" which has no reference(become eligible for garbage collection) and
  2. A new String object "IMMUTABLE" which is  referred by S1.

Hence if we try to alter/modify a string object,it creates a new string object instead of altering the existing object and the existing object will become eligible for garbage collection.

StringBuilder and StringBuffer classes are not immutable object.Hence if we try to make changes to these object,it will apply the changes to the same object instead of creating a new one.

Note:Wrapper classes(like Integer,Float etc) too have this immutable behaviour

Monday, 17 August 2009

Difference between StringTokenizer and String Split(StringTokenizer VS Split)

We all know that the StringTokenizer class and split method in String class will break the string into multiple tokens for the given delimiter .we will be thinking which one to use as both functionality are same.But there is a feature which makes split more advantageous than StringTokenizer.

Lets take a scenario where we have a string("This,is,,Test") and we need to break this string into tokens separated by a delimiter comma(,).

String Tokenizer:

First we will use the StringTokenizer to split this string as shown below

StringTokenizer st = new StringTokenizer("This,is,,Test",",");                                                                       while (st.hasMoreTokens()) {
System.out.println("Token-"+st.nextToken());
}

The output for this will be

Token-This
Token-is
Token-Test


As we can see in the above output, StringTokenizer discarded the tokens which are empty string between the delimiter and hence the number of tokens printed is only 3.

Split:

Now we will split the string using  split method as shown below

String[] strarray = ("This,is,,Test",").split(",");                                                                                            
for (String test:strarray)
System.out.println("Token-"+test);

The output for this will be

Token-This
Token-is
Token-
Token-Test


As we can see in the above output, split takes care of tokens which are empty string between the delimiter and hence the number of tokens printed is 4.

Thus Split method is more useful in the scenarios where the string to be split'ted can have empty spaces between the delimiter.