Monday, January 13, 2014

Java util package programming Examples

//Note:  Analysis the programs errors,outputs and Understand util package classes   in Java 


//[1]
import java.util.*;
class Demo1{
public static void main(String arg[]){
HashSet hs=new HashSet();
hs.add(new String("amar"));
hs.add(new Integer(75));
hs.add(new Float(75.8f));
hs.add(new Double(78.8));
System.out.println(hs);
}
}



//[2]
import java.util.*;
class Demo2{//ArrayList
public static void main(String arg[]){
ArrayList hs=new ArrayList();
hs.add(new String("amar"));
hs.add(new Integer(75));
hs.add(new Float(75.8f));
hs.add(new Double(78.8));
hs.add(new String("amar"));
hs.add(new StringBuilder("hai"));
System.out.println(hs);
}
}



//[3]
import java.util.*;
class Demo3{//ArrayList
public static void main(String arg[]){
ArrayList<String> hs=new ArrayList<String>();
hs.add(new String("amar"));
hs.add(new String("75"));
hs.add(new String("75.8f"));
hs.add(new String("78.8"));
hs.add(new String("amar"));
System.out.println(hs);
hs.add(3,"sun");
System.out.println("The value of the fourth index is"+hs.get(4));
hs.set(4,"micro");
System.out.println(hs.indexOf("sun"));
}
}



//[4]
import java.util.*;
class Demo4{//Generic Hashset
public static void main(String arg[]){
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(new Integer(16));
hs.add(new Integer(75));
hs.add(new Integer(75));
hs.add(new Integer(78));
System.out.println(hs);
}
}



//[5]
import java.util.*;
class Demo77{//Iterating the elements
public static void main(String arg[]){
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(new Integer(16));
hs.add(new Integer(75));
hs.add(new Integer(75));
hs.add(new Integer(78));
int sum=0;
for(Integer i:hs)
{
System.out.println(i);
sum=sum+i;
}
System.out.println(sum);
}
}



//[6]
import java.util.*;
class Demo6{//Iterating the elements
public static void main(String arg[]){
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(new Integer(16));
hs.add(new Integer(75));
hs.add(new Integer(75));
hs.add(new Integer(78));
int sum=0;
Iterator i=hs.iterator();
Integer m;
while(i.hasNext()){
m=(Integer)i.next();
System.out.println(m);
sum=sum+m;
}
System.out.println(sum);
}
}




//[7]
import java.util.*;
class Demo7{//Hashset 
public static void main(String arg[]){
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(new Integer(16));
hs.add(new Integer(75));
hs.add(new Integer(75));
hs.add(new Integer(78));
hs.add(new Integer(99));
boolean b=hs.contains(new Integer(99));
System.out.println("That element is available"+b);
b=hs.remove(new Integer(99));
System.out.println("That element is removed"+b);
System.out.println("The size of the hash set is"+hs.size());
}
}



//[8]
import java.util.*;
class Demo80{//HashMap
public static void main(String arg[]){
HashMap hm=new HashMap();
hm.put(new Integer(5),"sun");
hm.put(new Integer(6),"micro");
System.out.println(hm.get(new Integer(6)));
}
}

No comments: