Java Tutorials 11-20/56


Java Tutorials


  1. Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.

  • Enumerate through a Vector using Java Enumeration Example
  • Exception Handling
  • Create a Thread by Extending Thread
  • Factorial
  • Fibonacci Series
  • File Reader/Writer
  • Java Float Compare Example
  • Generate Harmonic Series
  • HashMap 
  • Simple Java HashSet example

Name Code

Enumerate through a Vector using Java Enumeration Example

       public class EnumerateThroughVectorExample
   {
     public static void main(String[] args)
     {
       //create a Vector object
       Vector v = new Vector();
      
       //populate the Vector
       v.add("One");
       v.add("Two");
       v.add("Three");
       v.add("Four");
      
       //Get Enumeration of Vector's elements using elements() method
       Enumeration e = v.elements();
      
       /*
       Enumeration provides two methods to enumerate through the elements.
       It's hasMoreElements method returns true if there are more elements to
       enumerate through otherwise it returns false. Its nextElement method returns
       the next element in enumeration.
       */
      
       System.out.println("Elements of the Vector are : ");
      
       while(e.hasMoreElements())
         System.out.println(e.nextElement());
     }
   } 

Exception Handling

       public class ExcepTest
   {
     public static void main(String args[])
     {
       try
       {
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
       }
       catch(ArrayIndexOutOfBoundsException e)
       {
         System.out.println("Exception thrown :" + e);
       }
       System.out.println("Out of the block");
     }
   } 

Create a Thread by Extending Thread

       class MyThread extends Thread
   {
     int count;
     MyThread()
     {
       count = 0;
     }
     public void run()
     {
       System.out.println("MyThread starting.");
       try
       {
         do
         {
           Thread.sleep(500);
           System.out.println("In MyThread, count is " + count);
           count++;
         } while (count < 5);
       }
       catch (InterruptedException exc)
       {
         System.out.println("MyThread interrupted.");
       }
       System.out.println("MyThread terminating.");
     }
   }
   public class Main
   {
     public static void main(String args[])
     {
       System.out.println("Main thread starting.");
       MyThread mt = new MyThread();
       mt.start();
       do
       {
         System.out.println("In main thread.");
         try
         {
           Thread.sleep(250);
         }
         catch (InterruptedException exc)
         {
         System.out.println("Main thread interrupted.");
         }
       } while (mt.count != 5);
       System.out.println("Main thread ending.");
     }
   } 

Factorial

      class Factorial
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]); //take argument as command line
       int result = 1;
       while(num>0)
       {
         result = result * num;
         num--;
       }
       System.out.println("Factorial of Given no. is : "+result);
     }
   } 

Fibonacci Series

     class Fibonacci
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]);//taking no. as command line argument.
       System.out.println("*****Fibonacci Series*****");
       int f1, f2=0, f3=1;
       for(int i=1;i<=num;i++)
       {
         System.out.print(" "+f3+" ");
         f1 = f2;
         f2 = f3;
         f3 = f1 + f2;
       }
     }
   } 

File Reader/Writer

      public class FileRead
   {
     public static void main(String args[])throws IOException
     {
       File file = new File("Hello1.txt");
       // creates the file
       file.createNewFile();
      
       // creates a FileWriter Object
       FileWriter writer = new FileWriter(file);
      
       // Writes the content to the file
       writer.write("This\n is\n an\n example\n");
       writer.flush();
       writer.close();
      
       //Creates a FileReader Object
       FileReader fr = new FileReader(file);
       char [] a = new char[50];
       fr.read(a); // reads the content to the array
       for(char c : a)
         System.out.print(c); //prints the characters one by one
       fr.close();
     }
   }   

Java Float Compare Example

      public class JavaFloatCompareExample
   {
     public static void main(String[] args)
     {
       /*
       To compare two float primitive values use
       compare(float f1, float f2) method of Float class. This is a static method.
       It returns 0 if both the values are equal, returns value less than 0 if
       f1 is less than f2, and returns value grater than 0 if f2 is grater than f2.
       */
      
       float f1 = 5.35f;
       float f2 = 5.34f;
       int i1 = Float.compare(f1,f2);
      
       if(i1 > 0)
       {
         System.out.println("First is grater");
       }
       else if(i1 < 0)
       {
         System.out.println("Second is grater");
       }
       else
       {
         System.out.println("Both are equal");
       }
      
       /*
       To compare a Float object with another Float object use
       int compareTo(Float f) method.
       It returns 0 if both the values are equal, returns value less than 0 if
       this Float object is less than the argument, and returns value grater
       than 0 if this Float object is grater than f2.
       */
      
       Float fObj1 = new Float("5.35");
       Float fObj2 = new Float("5.34");
       int i2 = fObj1.compareTo(fObj2);
      
       if(i2 > 0)
       {
         System.out.println("First is grater");
       }
       else if(i2 < 0)
       {
         System.out.println("Second is grater");
       }
       else
       {
         System.out.println("Both are equal");
       }
     }
   } 

Generate Harmonic Series

      class HarmonicSeries
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]);
       double result = 0.0;
       while(num > 0)
       {
         result = result + (double) 1 / num;
         num--;
       }
       System.out.println("Output of Harmonic Series is "+result);
     }
   } 

 HashMap 

       public class JavaHashMapExample
   {
     public static void main(String[] args)
     {
       //create object of HashMap
       HashMap hMap = new HashMap();
      
       /*
       Add key value pair to HashMap using
       Object put(Object key, Object value) method of Java HashMap class,
       where key and value both are objects
       put method returns Object which is either the value previously tied
       to the key or null if no value mapped to the key.
       */
      
       hMap.put("One", new Integer(1));
       hMap.put("Two", new Integer(2));
      
       /*
       Please note that put method accepts Objects. Java Primitive values CAN NOT
       be added directly to HashMap. It must be converted to corrosponding
       wrapper class first.
       */
      
       //retrieve value using Object get(Object key) method of Java HashMap class
       Object obj = hMap.get("One");
       System.out.println(obj);
      
       /*
       Please note that the return type of get method is an Object. The value must
       be casted to the original class.
       */
      
     }
   } 

Simple Java HashSet example

      public class SimpleHashSetExample
   {
     public static void main(String[] args)
     {
       //create object of HashSet
       HashSet hSet = new HashSet();
      
       /*
       Add an Object to HashSet using
       boolean add(Object obj) method of Java HashSet class.
       This method adds an element to HashSet if it is not already present in HashSet.
       It returns true if the element was added to HashSet, false otherwise.
       */
      
       hSet.add(new Integer("1"));
       hSet.add(new Integer("2"));
       hSet.add(new Integer("3"));
      
       /*
       Please note that add method accepts Objects. Java Primitive values CAN NOT
       be added directly to HashSet. It must be converted to corrosponding
       wrapper class first.
       */
      
       System.out.println("HashSet contains.." + hSet);
     }
   } 
Java Tutorials 11-20/56 Java Tutorials 11-20/56 Reviewed by Abdul hanan on 04:57:00 Rating: 5
Powered by Blogger.