Thursday, October 30, 2014

Java Program to demonstrate Exception Handling using try-catch block



public class MyExceptionHandle {
    public static void main(String a[]){
        try{
            for(int i=5;i>=0;i--){
                System.out.println(10/i);
            }
        } catch(Exception ex){
            System.out.println("Exception Message: "+ex.getMessage());
            ex.printStackTrace();
        }
        System.out.println("After for loop...");
    }
}


Output:

2
2
3
5
10
Exception Message: / by zero
java.lang.ArithmeticException: / by zero
        at com.myjava.exceptions.MyExceptionHandle.main(MyExceptionHandle.java:12)
After for loop...

Java Program to read integers from file with Scanner class


import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class ReadIntegers
{
    public static void main(String[] args)
    { try
{   Scanner s = new Scanner( new File("integers.dat") );
   while( s.hasNextInt() )
   { System.out.println( s.nextInt() );
   }
}
catch(IOException e)
{ System.out.println( e );
}
    }
}

Java Program to write 100 random integers to a file, 1 per line


import java.io.PrintStream;
import java.io.IOException;
import java.io.File;

import java.util.Random;

public class IntegersToFile
{ public static void main(String[] args)
{ try
{ PrintStream writer = new PrintStream( new File("randInts.txt"));
Random r = new Random();
final int LIMIT = 100;

for(int i = 0; i < LIMIT; i++)
{ writer.println( r.nextInt() );
}
writer.close();
}
catch(IOException e)
{ System.out.println("An error occured while trying to write to the file");
}
}
}

Java program to take input from Keyboard with Scanner class


import java.util.Scanner;

public class KeyboardInput
{

public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.print( "Enter your name: "  );
String name = s.nextLine();
System.out.println( "Hello " + name + "!" );
}
}

Sunday, October 26, 2014

Java Program to demonstrate Set


SetExample.java:

import java.util.*;

public class SetExample {

   public static void main(String args[]) {

       // We create a new, empty set
       Set mySet1 = new HashSet();
       // We add a few elements
       mySet1.add("A");
       mySet1.add("C");
       mySet1.add("A");
       mySet1.add("B");
       // Print the elements of the Set
       System.out.println("mySet1: " + mySet1);

       // Create a list and add some elements
       List list = new ArrayList();
       list.add("A");
       list.add("C");
       list.add("A");
       list.add("A");
       list.add("B");
       list.add("C");
       // Now create the set using the appropriate constructor
       Set mySet2 = new HashSet(list);
       // Print the elements of the list an the the set
       System.out.println("list: " + list);
       System.out.println("mySet2: " + mySet2);

       // Compare the two sets
       System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

       // Now we will remove one element from mySet2 and compare again
       mySet2.remove("A");
       System.out.println("mySet2: " + mySet2);
       System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

       // Lets check if our sets contain all the elements of the list
       System.out.println("MySet1 contains all the elements: " + mySet1.containsAll(list));
       System.out.println("MySet2 contains all the elements: " + mySet2.containsAll(list));

       // Use of Iterator in Set
       Iterator iterator = mySet1.iterator();
       while (iterator.hasNext()) {
           System.out.println("Iterator loop: " + iterator.next());
       }

       // Use of for-each in Set
       for (String str : mySet1) {
           System.out.println("for-each loop: " + str);
       }

       // Clearing all the elements
       mySet1.clear();
       System.out.println("mySet1 is Empty: " + mySet1.isEmpty());

       // Checking the number of elements
       System.out.println("mySet1 has: " + mySet1.size() + " Elements");
       System.out.println("mySet2 has: " + mySet2.size() + " Elements");

       // Creating an Array with the contents of the set
       String[] array = mySet2.toArray(new String[mySet2.size()]);
       System.out.println("The array:" + Arrays.toString(array));
   }
}
Output:
mySet1: [A, B, C]
list: [A, C, A, A, B, C]
mySet2: [A, B, C]
MySet1 matches mySet2: true
mySet2: [B, C]
MySet1 matches mySet2: false
MySet1 contains all the elements: true
MySet2 contains all the elements: false
Iterator loop: A
Iterator loop: B
Iterator loop: C
for-each loop: A
for-each loop: B
for-each loop: C
mySet1 is Empty: true
mySet1 has: 0 Elements
mySet2 has: 2 Elements
The array:[B, C]

Java Program to demonstrate ConcurrentHashMap


ConcurrentHashMapExample.java:
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
   
   public static void main(String[] args) {
       ConcurrentHashMap vehicles = new ConcurrentHashMap();
       
       // Add some vehicles.
       vehicles.put("BMW", 5);
       vehicles.put("Mercedes", 3);
       vehicles.put("Audi", 4);
       vehicles.put("Ford", 10);
       
       System.out.println("Total vehicles: " + vehicles.size());
       
       // Iterate over all vehicles, using the keySet method.
       for(String key: vehicles.keySet())
           System.out.println(key + " - " + vehicles.get(key));
       System.out.println();
       
       String searchKey = "Audi";
       if(vehicles.containsKey(searchKey))
           System.out.println("Found total " + vehicles.get(searchKey) + " "
                   + searchKey + " cars!\n");
       
       Enumeration elems = vehicles.elements();
       while(elems.hasMoreElements())
           System.out.println(elems.nextElement());
       System.out.println();
       
       Integer val = vehicles.putIfAbsent("Audi", 9);
       if(val != null)
           System.out.println("Audi was found in the map and its value was updated!");
       
       val = vehicles.putIfAbsent("Nissan", 9);
       if(val == null)
           System.out.println("Nissan wasn't found in map, thus a new pair was created!");
       System.out.println();
       
       // The next statements throw a NullPointerException, if uncommented.
       //vehicles.put("Nissan", null);
       //vehicles.put(null, 6);
       
       // Clear all values.
       vehicles.clear();
       
       // Equals to zero.
       System.out.println("After clear operation, size: " + vehicles.size());
   }
}
A sample execution is shown below:
Total vehicles: 4
BMW - 5
Mercedes - 3
Audi - 4
Ford - 10
Found total 4 Audi cars!
5
3
4
10
Audi was found in the map and its value was updated!
Nissan wasn't found in map, thus a new pair was created!
After clear operation, size: 0

Java Program to demonstrate TreeMap


TreeMapExample.java:
import java.util.TreeMap;

public class TreeMapExample {

   public static void main(String[] args) {
       TreeMap vehicles = new TreeMap();
       
       // Add some vehicles.
       vehicles.put("BMW", 5);
       vehicles.put("Mercedes", 3);
       vehicles.put("Audi", 4);
       vehicles.put("Ford", 10);
       
       System.out.println("Total vehicles: " + vehicles.size());
       
       // Iterate over all vehicles, using the keySet method.
       for(String key: vehicles.keySet())
           System.out.println(key + " - " + vehicles.get(key));
       System.out.println();
       
       System.out.println("Highest key: " + vehicles.lastKey());
       System.out.println("Lowest key: " + vehicles.firstKey());
       
       System.out.println("\nPrinting all values:");
       for(Integer val: vehicles.values())
           System.out.println(val);
       System.out.println();
       
       // Clear all values.
       vehicles.clear();
       
       // Equals to zero.
       System.out.println("After clear operation, size: " + vehicles.size());
   }
}
A sample execution is shown below:
Total vehicles: 4
Audi - 4
BMW - 5
Ford - 10
Mercedes - 3

Highest key: Mercedes
Lowest key: Audi

Printing all values:
4
5
10
3

After clear operation, size: 0

Java Program to demonstrate HashTable


HashTableExample.java:
import java.util.Hashtable;
import java.util.Map;
 
public class HashTableExample {
 
   public static void main(String[] args) {
       Map vehicles = new Hashtable();
        
       // Add some vehicles.
       vehicles.put("BMW", 5);
       vehicles.put("Mercedes", 3);
       vehicles.put("Audi", 4);
       vehicles.put("Ford", 10);
        
       System.out.println("Total vehicles: " + vehicles.size());
        
       // Iterate over all vehicles, using the keySet method.
       for(String key: vehicles.keySet())
           System.out.println(key + " - " + vehicles.get(key));
       System.out.println();
        
       String searchKey = "Audi";
       if(vehicles.containsKey(searchKey))
           System.out.println("Found total " + vehicles.get(searchKey) + " "
                   + searchKey + " cars!\n");
        
       // Clear all values.
       vehicles.clear();
        
       // Equals to zero.
       System.out.println("After clear operation, size: " + vehicles.size());
 
       // The next statements throw a NullPointerException, if uncommented.
       //vehicles.put("Nissan", null);
       //vehicles.put(null, 6);
   }
}
A sample execution is shown below:
Total vehicles: 4
Audi - 4
Ford - 10
BMW - 5
Mercedes - 3
Found total 4 Audi cars!
After clear operation, size: 0

Java Program to demonstrate HashMap


HashMapExample.java:
import java.util.HashMap;
import java.util.Map;
 
public class HashMapExample {
    
   public static void main(String[] args) {
       Map vehicles = new HashMap();
        
       // Add some vehicles.
       vehicles.put("BMW", 5);
       vehicles.put("Mercedes", 3);
       vehicles.put("Audi", 4);
       vehicles.put("Ford", 10);
        
       System.out.println("Total vehicles: " + vehicles.size());
        
       // Iterate over all vehicles, using the keySet method.
       for(String key: vehicles.keySet())
           System.out.println(key + " - " + vehicles.get(key));
       System.out.println();
        
       String searchKey = "Audi";
       if(vehicles.containsKey(searchKey))
           System.out.println("Found total " + vehicles.get(searchKey) + " "
                   + searchKey + " cars!\n");
        
       // Clear all values.
       vehicles.clear();
        
       // Equals to zero.
       System.out.println("After clear operation, size: " + vehicles.size()); 
   }
}
A sample execution is shown below:
Total vehicles: 4
Audi - 4
Ford - 10
BMW - 5
Mercedes - 3
Found total 4 Audi cars!
After clear operation, size: 0

Java program to print the sum of array of elements



class SingleArray
{
    public static void main (String args[])
    {
  
        int number_array [] = {10,30,50,70,90,110};
        int result = 0;
        for (int ctr = 0; ctr < 6; ctr++)
               result = result + number_array [ctr];
System.out.println ("Sum of the array elements is : " +result);
}
}