Auto AdSense

Showing posts with label Java Programs. Show all posts
Showing posts with label Java Programs. Show all posts

Saturday, 29 November 2014

Java Program to Write file using FileOutputStream

      public class WriteFile
   {
     public static void main(String[] args)
     {
       String strFilePath = "C://FileIO//demo.txt";
       try
       {
         FileOutputStream fos = new FileOutputStream(strFilePath);
         byte b = 01;
         /*
         * To write byte data to a file, use
         * void write(int i) method of Java FileOutputStream class.
         * This method writes given byte to a file.
         */
        
         fos.write(b);
        
         /*
         * Close FileOutputStream using,
         * void close() method of Java FileOutputStream class.
         *
         */
         fos.close();
       }
       catch(FileNotFoundException ex)
       {
         System.out.println("FileNotFoundException : " + ex);
       }
       catch(IOException ioe)
       {
          System.out.println("IOException : " + ioe);
       }
     }
   }   

Java Program to Write byte array to file using BufferedOutputStream

       public class WriteByteArrayToFile
   {
     public static void main(String[] args)
     {
       String strFileName = "C:/FileIO/BufferedOutputStreamDemo";
       BufferedOutputStream bos = null;
       try
       {
         //create an object of FileOutputStream
         FileOutputStream fos = new FileOutputStream(new File(strFileName));
        
         //create an object of BufferedOutputStream
         bos = new BufferedOutputStream(fos);
        
         String str = "BufferedOutputStream Example";
        
         /*
         * To write byte array to file use,
         * public void write(byte[] b) method of BufferedOutputStream
         * class.
         */
         System.out.println("Writing byte array to file");
        
         bos.write(str.getBytes());
        
         System.out.println("File written");
       }
       catch(FileNotFoundException fnfe)
       {
         System.out.println("Specified file not found" + fnfe);
       }
       catch(IOException ioe)
       {
         System.out.println("Error while writing file" + ioe);
       }
       finally
       {
         if(bos != null)
         {
           try
           {
            
             //flush the BufferedOutputStream
             bos.flush();
            
             //close the BufferedOutputStream
             bos.close();
            
           }
           catch(Exception e){}
         }
       }
     }
   }   

Java Vector Example

       public class SimpleVectorExample
   {
     public static void main(String[] args)
     {
      
       //create a Vector object
       Vector v = new Vector();
      
       /*
       Add elements to Vector using
       boolean add(Object o) method. It returns true as a general behavior
       of Collection.add method. The specified object is appended at the end
       of the Vector.
       */
       v.add("1");
       v.add("2");
       v.add("3");
      
       /*
       Use get method of Java Vector class to display elements of Vector.
       Object get(int index) returns an element at the specified index in
       the Vector
       */
      
       System.out.println("Getting elements of Vector");
       System.out.println(v.get(0));
       System.out.println(v.get(1));
       System.out.println(v.get(2));
     }
   }    

Java Example on TreeSet

      public class SimpleJavaTreeSetExample
   {
     public static void main(String[] args)
     {
      
       //create object of TreeSet
       TreeSet tSet = new TreeSet();
      
       /*
       Add an Object to TreeSet using
       boolean add(Object obj) method of Java TreeSet class.
       This method adds an element to TreeSet if it is not already present in TreeSet.
       It returns true if the element was added to TreeSet, false otherwise.
       */
      
       tSet.add(new Integer("1"));
       tSet.add(new Integer("2"));
       tSet.add(new Integer("3"));
      
       /*
       Please note that add method accepts Objects. Java Primitive values CAN NOT
       be added directly to TreeSet. It must be converted to corrosponding
       wrapper class first.
       */
      
       System.out.println("TreeSet contains.." + tSet); }
   }   

Java example on Tree Map

       public class JavaTreeMapExample
   {
     public static void main(String[] args)
     {
      
       //create object of TreeMap
       TreeMap treeMap = new TreeMap();
      
       /*
       Add key value pair to TreeMap using,
       Object put(Object key, Object value) method of Java TreeMap 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.
       */
      
       treeMap.put("One", new Integer(1));
       treeMap.put("Two", new Integer(2));
      
       /*
       Please note that put method accepts Objects. Java Primitive values CAN NOT
       be added directly to TreeMap. It must be converted to corrosponding
       wrapper class first.
       */
      
       //retrieve value using Object get(Object key) method of Java TreeMap class
       Object obj = treeMap.get("Two");
       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.
       */
      
     }
  }   

Java Program on Thread Synchronization

         // File Name : Callme.java
     // This program uses a synchronized block.
     class Callme
     {
       void call(String msg)
       {
         System.out.print("[" + msg);
         try
         {
           Thread.sleep(1000);
         }
         catch (InterruptedException e)
         {
           System.out.println("Interrupted");
         }
         System.out.println("]");
       }
     }
     // File Name : Caller.java
     class Caller implements Runnable
     {
       String msg;
       Callme target;
       Thread t;
       public Caller(Callme targ, String s)
       {
         target = targ;
         msg = s;
         t = new Thread(this);
         t.start();
       }
       // synchronize calls to call()
       public void run()
       {
         synchronized(target)
         {
           // synchronized block
           target.call(msg);
         }
       }
     }
     // File Name : Synch.java
     class Synch
     {
       public static void main(String args[])
       {
         Callme target = new Callme();
         Caller ob1 = new Caller(target, "Hello");
         Caller ob2 = new Caller(target, "Synchronized");
         Caller ob3 = new Caller(target, "World");
        
         // wait for threads to end
         try
         {
           ob1.t.join();
           ob2.t.join();
           ob3.t.join();
         }
         catch(InterruptedException e)
         {
           System.out.println("Interrupted");
         }
       }
     }   

Java Program to Create a thread by implementing Runnable

      class MyThread implements Runnable
   {
     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.");
     }
   }
   class RunnableDemo
   {
     public static void main(String args[])
     {
       System.out.println("Main thread starting.");
       MyThread mt = new MyThread();
       Thread newThrd = new Thread(mt);
       newThrd.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.");
     }
   }  

Java Program to find Sum and Product of Digit

       class Sum_Product_ofDigit
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]); //taking value as command line argument.
       int temp = num,result=0;
       //Logic for sum of digit
       while(temp>0)
       {
         result = result + temp;
         temp--;
       }
       System.out.println("Sum of Digit for "+num+" is : "+result);
       //Logic for product of digit
       temp = num;
       result = 1;
       while(temp > 0)
       {
         result = result * temp;
         temp--;
       }
       System.out.println("Product of Digit for "+num+" is : "+result);
     }
   }   

Java Example to Convert String to primitive byte


   public class StringToPrimitiveByteExample
   {
      
     public static void main(String[] args)
     {
       //declare String object
       String str = new String("10");
      
       /*
       use parseInt method of Byte class to convert String into byte primitive
       data type. This is a static method.
       Please note that this method can throw a NumberFormatException if the string
       is not parsable to byte.
       */
      
       byte b = Byte.parseByte(str);
       System.out.println(b);
      
     }
   }   

Java Example on StringBuffer To File

         public class JavaStringBufferToFileExample
   {
     public static void main(String[] args) throws IOException
     {
       //create StringBuffer object
       StringBuffer sbf = new StringBuffer();
      
       //StringBuffer contents
       sbf.append("StringBuffer contents first line.");
       //new line
       sbf.append(System.getProperty("line.separator"));
       //second line
       sbf.append("StringBuffer contents second line.");
      
       /*
       * To write contents of StringBuffer to a file, use
       * BufferedWriter class.
       */
      
       BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("d:/demo.txt")));
      
       //write contents of StringBuffer to a file
       bwr.write(sbf.toString());
      
       //flush the stream
       bwr.flush();
      
       //close the stream
       bwr.close();
      
       System.out.println("Content of StringBuffer written to File.");
     }
   }  

Java Program to find the Square Root of BigInteger

       public class SquareRootOfBigIntegerExample
   {
     public static void main(String[] args)
     {
       SquareRootOfBigIntegerExample SquareRootOfBigIntegerExample = new SquareRootOfBigIntegerExample();
       String n = "";
       MathContext mc = new MathContext(0, RoundingMode.DOWN);
       mc = MathContext.DECIMAL32;
       BigInteger my2P100000 = new BigInteger("0");
       BigInteger two = new BigInteger("2");
       BigInteger one = new BigInteger("1");
       my2P100000 = two.shiftLeft(2000 - 1);
       System.out.println("2^2000 -- Step 1");
       System.out.println("Value of 2^2,000 " + my2P100000 );
       System.out.println("");
       System.out.println("Finding the Square Root of 2^2000");
       String mys = my2P100000 + "";
       n = (mys) ;
       int firsttime = 0;
       BigDecimal myNumber = new BigDecimal(n);
       BigDecimal g = new BigDecimal("1");
       BigDecimal my2 = new BigDecimal("2");
       BigDecimal epsilon = new BigDecimal("0.0000000001");
       BigDecimal nByg = myNumber.divide(g, 9, BigDecimal.ROUND_FLOOR);
       //Get the value of n/g
       BigDecimal nBygPlusg = nByg.add(g);
       //Get the value of "n/g + g
       BigDecimal nBygPlusgHalf = nBygPlusg.divide(my2, 9, BigDecimal.ROUND_FLOOR);
       //Get the value of (n/g + g)/2
       BigDecimal saveg = nBygPlusgHalf;
       firsttime = 99;
       do
       {
         g = nBygPlusgHalf;
         nByg = myNumber.divide(g, 9, BigDecimal.ROUND_FLOOR);
         nBygPlusg = nByg.add(g);
         nBygPlusgHalf = nBygPlusg.divide(my2, 9, BigDecimal.ROUND_FLOOR);
         BigDecimal savegdiff = saveg.subtract(nBygPlusgHalf);
         if (savegdiff.compareTo(epsilon) == -1 )
         {
           firsttime = 0;
         }
         else
         {
           saveg = nBygPlusgHalf;
         }
       } while (firsttime > 1);
       System.out.println("For " + mys + "\nLength: " + mys.length() + "\nThe Square Root is " + saveg);
     }
   }   

Java Program on Shell Sort

        public class ShellSort
   {
     private long[] data;
     private int len;
     public ShellSort(int max)
     {
       data = new long[max];
       len = 0;
     }
     public void insert(long value)
     {
       data[len] = value;
       len++;
     }
     public void display()
     {
       System.out.print("Data:");
       for (int j = 0; j < len; j++)
         System.out.print(data[j] + " ");
       System.out.println("");
     }
     public void shellSort()
     {
       int inner, outer;
       long temp;
       //find initial value of h
       int h = 1;
       while (h <= len / 3)
       h = h * 3 + 1; // (1, 4, 13, 40, 121, ...)
       while (h > 0) // decreasing h, until h=1
       {
         // h-sort the file
         for (outer = h; outer < len; outer++)
         {
           temp = data[outer];
           inner = outer;
           // one subpass (eg 0, 4, 8)
           while (inner > h - 1 && data[inner - h] >= temp)
           {
             data[inner] = data[inner - h];
             inner -= h;
           }
           data[inner] = temp;
         }
         h = (h - 1) / 3; // decrease h
       }
     }
     public static void main(String[] args)
     {
       int maxSize = 10;
       ShellSort arr = new ShellSort(maxSize);
       for (int j = 0; j < maxSize; j++)
       {
         long n = (int) (java.lang.Math.random() * 99);
         arr.insert(n);
       }
       arr.display();
       arr.shellSort();
       arr.display();
     }
   }       

Java Program Simple Thread Example

      public class SimpleThread extends Thread
   {
     private int countDown = 5;
     private static int threadCount = 0;
     public SimpleThread()
     {
       super("" + ++threadCount); // Store the thread name
       start();
     }
     public String toString()
     {
       return "#" + getName() + ": " + countDown;
     }
     public void run()
     {
       while(true)
       {
         System.out.println(this);
         if(--countDown == 0)
           return;
       }
     }
     public static void main(String[] args)
     {
       for(int i = 0; i < 5; i++)
         new SimpleThread();
     }
   }    

Java Program on Selection Sort

       public class SelectionSort
   {
     /**
     * Sorts the given list in place.
     * Worst Case Performance O(n^2)
     * Best Case Performance O(n^2)
     * Average Case Performance O(n^2)
     * Insertion sort can be- and usually is a much faster sorting algorithm, than selection sort.
     * Selection sort is superior because it does less swaps.
     * @param list - int array that you want to sort.
     */
     public static void sortNumbers(Integer[] list)
     {
       //go through the list
       for (int i=0; i< list.length;i++)
       {
         //define min
         int min = i;
         //go through the remaining list and see if there is smaller number
         for (int j=i+1;j< list.length;j++)
         {
           //if there is a smaller number
           if (list[j] < list[min])
           {
             //remember its place
             min = j;
           }
         }
         if (i != min)
         {
           //swap the min element, moving it to its proper place in the list.
           int temp = list[min];
           list[min] = list[i];
           list[i] = temp;
         }
       }
     }
     /**
     * Just for testing purposes.
     */
     public static void main(String[] args)
     {
       Integer[] list = new Integer[5];
       list[0] = 32;
       list[1] = 24;
       list[2] = 235;
       list[3] = 1;
       list[4] = 0;
       sortNumbers(list);
       for (int i = 0;i< list.length;i++)
       {
         System.out.println(list[i]);
       }
     }
   }   

Java Program to Reverse Number

      class Reverse
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]); //take argument as command line
       int remainder, result=0;
       while(num>0)
       {
         remainder = num%10;
         result = result * 10 + remainder;
         num = num/10;
       }
       System.out.println("Reverse number is : "+result);
     }
   }      

Java Program on Reading Directories

      class DirList
   {
     public static void main(String args[])
     {
       String dirname = "/java";
       File f1 = new File(dirname);
       if (f1.isDirectory())
       {
         System.out.println( "Directory of " + dirname);
         String s[] = f1.list();
         for (int i=0; i < s.length; i++)
         {
           File f = new File(dirname + "/" + s[i]);
           if (f.isDirectory())
           {
             System.out.println(s[i] + " is a directory");
           }
           else
           {
             System.out.println(s[i] + " is a file");
           }
         }
       }
       else
       {
         System.out.println(dirname + " is not a directory");
       }
     }
   }     

Example to Read File Using Java Buffered Input Stream

       public class ReadFileUsingBufferedInputStream
   {
     public static void main(String[] args)
     {
       //create file object
       File file = new File("C://FileIO//ReadFile.txt");
       BufferedInputStream bin = null;
      
       try
       {
         //create FileInputStream object
         FileInputStream fin = new FileInputStream(file);
        
         //create object of BufferedInputStream
         bin = new BufferedInputStream(fin);
        
         /*
         * BufferedInputStream has ability to buffer input into
         * internal buffer array.
         *
         * available() method returns number of bytes that can be
         * read from underlying stream without blocking.
         */
        
         //read file using BufferedInputStream
         while( bin.available() > 0 )
         {
        
           System.out.print((char)bin.read());
         }
        
       }
       catch(FileNotFoundException e)
       {
         System.out.println("File not found" + e);
       }
       catch(IOException ioe)
       {
          System.out.println("Exception while reading the file " + ioe);
       }
       finally
       {
         //close the BufferedInputStream using close method
         try
         {
           if(bin != null)
             bin.close();
         }catch(IOException ioe)
         {
           System.out.println("Error while closing the stream : " + ioe);
         }
       }
     }
   }    

Java Program on Quick Sort

      public class QuickSort
   {
     /**
     * Sorts the given list in place.
     * Worst Case Performance O(n^2)
     * Best Case Performance O(nlogn)
     * Average Case Performance O(nlogn)
     * @param list - int array that you want to sort.
     */
     public void sortNumbers(int[] list)
     {
       Quicksort(list, 0,list.length-1);
     }
     public void Quicksort(int[] A, int start, int end)
     {
       if (start < end)
       {
         //we partition the list and get back two lists (lower than pivot, and bigger than pivot)
         int middle = Partition(A, start, end);
         //we then do a recursive call to sort out lower numbers than pivot
         Quicksort(A, start, middle-1);
         //and we do same with higher numbers than pivot
         Quicksort(A, middle+1, end);
         //NOTE: pivot is already in it's place, where he supposed to be (in a sorted list).
       }
     }
     public int Partition (int[] A, int start, int end)
     {
       int pivot = A[end]; //we define pivot (the number we will be comparing other numbers to
       int lo = start-1; // we define low value index
       for (int hi = start; hi < end; hi++)
       {
         //we go throug the list, compare other numbers to pivot
         if (A[hi] <= pivot)
         {
           //if pivot is lower that the current number
           lo++; //we increase lo value
           //and exchange current lo with hi (so we will have all lower numbers than pivot on one side)
           int temp = A[lo];
           A[lo] = A[hi];
           A[hi] = temp;
         }
       }
       //at the end we put in pivot right inbetween low and high values and we know that pivot element is in the right place.
       int temp = A[lo+1];
       A[lo+1] = A[end];
       A[end] = temp;
       return lo+1; //we return the pivot elements place
     }
     public static void main(String[] args)
     {
       int[] list = {156,344,54,546,767,23,34,64,234,
654,234,65,234,65,87,3,5,76,24,2,3,7,
9,5,34,32,4525,345,0};
       QuickSort qs = new QuickSort();
       qs.sortNumbers(list);
       for (int i = 0;i < list.length;i++)
       {
         System.out.println(list[i]);
       }
     }
   }  

Java Program to find All Real Solutions to the Quadratic Equation

      class Quadratic
   {
     public static void main(String args[])throws IOException
     {
       double x1,x2,disc,a,b,c;
       InputStreamReader obj=new InputStreamReader(System.in);
       BufferedReader br=new BufferedReader(obj);
       System.out.println("enter a,b,c values");
       a=Double.parseDouble(br.readLine());
       b=Double.parseDouble(br.readLine());
       c=Double.parseDouble(br.readLine());
       disc=(b*b)-(4*a*c);
       if(disc==0)
       {
         System.out.println("roots are real and equal ");
         x1=x2=-b/(2*a);
         System.out.println("roots are "+x1+","+x2);
       }
       else if(disc>0)
       {
         System.out.println("roots are real and unequal");
         x1=(-b+Math.sqrt(disc))/(2*a);
         x2=(-b+Math.sqrt(disc))/(2*a);
         System.out.println("roots are "+x1+","+x2);
       }
       else
       {
         System.out.println("roots are imaginary");
       }
     }
  }   

Java Program on Setting Priorities on the Thread objects

       public class Main
   {
     public static void main(String[] args) throws Exception
     {
       Thread thread1 = new Thread(new TestThread(1));
       Thread thread2 = new Thread(new TestThread(2));
       thread1.setPriority(Thread.MAX_PRIORITY);
       thread2.setPriority(Thread.MIN_PRIORITY);
       thread1.start();
       thread2.start();
       thread1.join();
       thread2.join();
     }
   }
   class TestThread implements Runnable
   {
     int id;
     public TestThread(int id)
     {
       this.id = id;
     }
     public void run()
     {
       for (int i = 1; i <= 10; i++)
       {
         System.out.println("Thread" + id + ": " + i);
       }
     }
   }