Auto AdSense

Sunday, 30 November 2014

A First Python Program

  • First Python Program:
    #!/usr/bin/python

    print "Hello, Python!";
  • Quotation in Python:
    word = 'word'
    sentence = "This is a sentence."
    paragraph = """This is a paragraph. It is
    made up of multiple lines and sentences."""
  • Comments in Python:
    #!/usr/bin/python

    # First comment
    print "Hello, Python!"; # second comment
  • Waiting for the User:
    #!/usr/bin/python

    raw_input("\n\nPress the enter key to exit.")
  • Multiple Statement Groups as Suites:
    if expression :
    suite
    elif expression :
    suite
    else :
    suite
  • Assigning Values to Variables:
    #!/usr/bin/python

    counter = 100 # An integer assignment
    miles = 1000.0 # A floating point
    name = "John" # A string

    print counter
    print miles
    print name
  • Multiple Assignment:
    a = b = c = 1
    a, b, c = 1, 2, "john"
  • Python Strings:
    #!/usr/bin/python

    str = 'Hello World!'

    print str # Prints complete string
    print str[0] # Prints first character of the string
    print str[2:5] # Prints characters starting from 3rd to 5th
    print str[2:] # Prints string starting from 3rd character
    print str * 2 # Prints string two times
    print str + "TEST" # Prints concatenated string
  • Python Lists:
    #!/usr/bin/python

    list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
    tinylist = [123, 'john']

    print list # Prints complete list
    print list[0] # Prints first element of the list
    print list[1:3] # Prints elements starting from 2nd till 3rd
    print list[2:] # Prints elements starting from 3rd element
    print tinylist * 2 # Prints list two times
    print list + tinylist # Prints concatenated lists
  • Python Tuples:
    #!/usr/bin/python

    tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
    tinytuple = (123, 'john')

    print tuple # Prints complete list
    print tuple[0] # Prints first element of the list
    print tuple[1:3] # Prints elements starting from 2nd till 3rd
    print tuple[2:] # Prints elements starting from 3rd element
    print tinytuple * 2 # Prints list two times
    print tuple + tinytuple # Prints concatenated lists
  • Python Dictionary:
    #!/usr/bin/python

    dict = {}
    dict['one'] = "This is one"
    dict[2] = "This is two"

    tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


    print dict['one'] # Prints value for 'one' key
    print dict[2] # Prints value for 2 key
    print tinydict # Prints complete dictionary
    print tinydict.keys() # Prints all the keys
    print tinydict.values() # Prints all the values

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);
       }
     }
   }   

Java Program to Determine whether the number is Prime or not

      class PrimeNo
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]);
       int flag=0;
       for(int i=2;i< num;i++)
       {
         if(num%i==0)
         {
           System.out.println(num+" is not a Prime Number");
           flag = 1;
           break;
         }
       }
       if(flag==0)
       System.out.println(num+" is a Prime Number");
     }
   }   

Java Program on Polymorphism

      class Box
   {
     int w,h;
     void info()
     {
       System.out.println("This is a simple box");
       System.out.println("width = "+ w + " hieght "+ h);
     }
   }
   class WoddenBox extends Box
   {
     int life;
     void info( )
     {
       System.out.println("This is a Wodden box");
     }
   }
   class SteelBox extends Box
   {
     int wg;
     void info( )
     {
       System.out.println("This is a steel box");
     }
   }
   class LargeWoddenBox extends WoddenBox
   {
     void info()
     {
       System.out.println("This is a Huge Wodden box");
     }
   }
   class BoxDemo
   {
     public static void main ( String ary[ ] )
     {
       Box x;
       Box b1 =new Box( );
       WoddenBox wb=new WoddenBox( );
       SteelBox s1=new SteelBox( );
       LargeWoddenBox p1=new LargeWoddenBox( );
       b1.info( );
       wb.info( );
       s1.info( );
       p1.info( );
     }
   }   

Java Program to Determine whether the string is Palindrome or not

      class Palindrome
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]);
       int n = num; //used at last time check
       int reverse=0,remainder;
       while(num > 0)
       {
         remainder = num % 10;
         reverse = reverse * 10 + remainder;
         num = num / 10;
       }
       if(reverse == n)
         System.out.println(n+" is a Palindrome Number");
       else
         System.out.println(n+" is not a Palindrome Number");
     }
   }   

Java Program to determine Number is Even Or Odd with Average

         class EvenOdd_Avg
   {
     public static void main(String args[])
     {
       int n = Integer.parseInt(args[0]);
       int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;
       while(n > 0)
       {
         if(n%2==0)
         {
           cntEven++;
           sumEven = sumEven + n;
         }
         else
         {
           cntOdd++;
           sumOdd = sumOdd + n;
         }
         n--;
       }
       int evenAvg,oddAvg;
       evenAvg = sumEven/cntEven;
       oddAvg = sumOdd/cntOdd;
       System.out.println("Average of first N Even no is "+evenAvg);
       System.out.println("Average of first N Odd no is "+oddAvg);
     }
   }   

Java Program on Method Overriding

     class A
   {
     String name() { return "A"; }
   }
   class B extends A
   {
     String name() { return "B"; }
   }
   class C extends A
   {
     String name() { return "C"; }
   }
   public class Overriding
   {
     public static void main(String[] args)
     {
       A[] tests = new A[] { new A(), new B(), new C() };
       for (int i = 0; i < tests.length; i++)
       System.out.print(tests[i].name());
     }
   }   

Java Program on Merge Sort

       public class MergeSort
   {
     /**
     * Merges two arrays into one.
     * @param A array that contains the two arrays.
     * @param temp temporary array that we will work with
     * @param lo lowest index value in the array
     * @param mid middle index value in the array (represents break between low and high values)
     * @param hi highest index value in the array
     */
     private static void Merge(int[] A, int[] temp, int lo, int mid, int hi)
     {
       int i = lo;
       int j = mid;
       for (int k = lo; k < hi; k++)
       {
         if (i == mid) temp[k] = A[j++]; //if lo-mid array is empty
         else if (j == hi) temp[k] = A[i++]; //if mid-hi array is empty
         else if (A[j] > A[i]) temp[k] = A[i++]; //i is lower so we put it in the array first
         else temp[k] = A[j++]; //j is lower or equal to i, so we put it in the array first.
       }
       //now we need to copy back temp array to its place in A array
       for (int k = lo; k < hi; k++)
         A[k] = temp[k]; //we are copying only the numbers we just merged.
      
     }
     private static void MergeSort(int[] A, int lo, int hi)
     {
       if (hi - lo == 1) return; //only one element in the array, return.
       int mid = lo + (hi - lo) / 2; //find middle
       MergeSort(A, lo, mid); //sort first part
       MergeSort(A, mid, hi); //sort second part
       Merge(A, new int[A.length], lo, mid, hi); //merge both parts
     }
     /**
     * Sorts the given list. (Not in place)
     * Worst Case Performance O(nlogn)
     * Best Case Performance O(nlogn)
     * Average Case Performance O(nlogn)
     * @param A list of int array.
     */
     public static void sortNumbers(int[] A)
     {
       MergeSort(A, 0, A.length);
     }
     /**
     * Just for testing purposes.
     */
     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};
       sortNumbers(list);
       for (int i = 0;i< list.length;i++)
       {
         System.out.println(list[i]);
       }
     }
   }   

Java Program on LinkedList Example

      public class SimpleJavaLinkedListExample
   {
     public static void main(String[] args)
     {
      
       //create LinkedList object
       LinkedList lList = new LinkedList();
      
       //add elements to LinkedList
       lList.add("1");
       lList.add("2");
       lList.add("3");
       lList.add("4");
       lList.add("5");
      
       /*
       * Please note that primitive values can not be added into LinkedList
       * directly. They must be converted to their corrosponding wrapper class.
       */
      
       System.out.println("LinkedList contains : " + lList);
     }
   }   

Java Program LinkedHashSet Example

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

Tuesday, 25 November 2014

Simple Java LinkedHashMap example

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

Java Program on Linear Search

      public class LinearSearch
   {
     public int find(final int[] data, final int key)
     {
       for (int i = 0; i < data.length; ++i)
       {
         if (data[i] > key)
           return -1;
         else if (data[i] == key)
           return i;
       }
       return -1;
     }
     public static void main(String[] args)
     {
       final int arr[] = new int[10];
       System.out.println("Enter 10 numbers");
       Scanner input = new Scanner(System.in);
       for (int i = 0; i < arr.length; i++)
       {
         arr[i] = input.nextInt();
       }
       LinearSearch search = new LinearSearch();
       System.out.print("Enter the element to search: ");
       int num=input.nextInt();
       int n = search.find(arr, num);
       if ((n >= 0) && (n < arr.length))
       {
         System.out.println("Found at index: " + n);
       }
       else
       {
         System.out.println("Not Found");
       }
     }
   }   

Sunday, 23 November 2014

Java Program Boolean Example

      public class JavaBooleanExample
   {
     public static void main(String[] args)
     {
       //Create an Boolean object using one the below given ways
       //1. Create an Boolean object from boolean value
       Boolean blnObj1 = new Boolean(true);
      
       /*
       2. Create an Boolean object from String. It creates a Boolean object
       representing true if the string is not null and equals to true. Otherwise
       it creates Boolean object representing false.
       */
       Boolean blnObj2 = new Boolean("false");
      
       //print value of Boolean objects
       System.out.println(blnObj1);
       System.out.println(blnObj2);
     }
   }   

Saturday, 22 November 2014

Iterate through a Collection using Java Iterator Example

       public class JavaIteratorExample
   {
     public static void main(String[] args)
     {
       //create an ArrayList object
       ArrayList aList = new ArrayList();
      
       //populate ArrayList object
       aList.add("1");
       aList.add("2");
       aList.add("3");
       aList.add("4");
       aList.add("5");
      
       /*
       Get Iterator object by invoking iterator method of collection.
       Iterator provides hasNext() method which returns true if has more
       elements. next() method returns the element in iteration.
       */
       Iterator itr = aList.iterator();
      
       //iterate through the ArrayList values using Iterator's hasNext and next methods
       while(itr.hasNext())
         System.out.println(itr.next());
      
       /*
       Please note that next method may throw a java.util.NoSuchElementException
       if iteration has no more elements.
       */
      
     }
   }     

Java Program on ArrayList using Iterator Example

        public class IterateThroughArrayListUsingIteratorExample
   {
     public static void main(String[] args)
     {
       //create an ArrayList object
       ArrayList arrayList = new ArrayList();
      
       //Add elements to Arraylist
       arrayList.add("1");
       arrayList.add("2");
       arrayList.add("3");
       arrayList.add("4");
       arrayList.add("5");
      
       //get an Iterator object for ArrayList using iterator() method.
       Iterator itr = arrayList.iterator();
      
       //use hasNext() and next() methods of Iterator to iterate through the elements
       System.out.println("Iterating through ArrayList elements...");
       while(itr.hasNext())
         System.out.println(itr.next());
     }
   }   

Java Program on InsertionSort

      public class InsertionSort
   {
     /**
     * Sorts the given list in place.
     * Worst Case Performance O(n^2)
     * Best Case Performance O(n)
     * Average Case Performance O(n^2)
     * @param list - int array that you want to sort.
     */
     public static void sortNumbers(int[] list)
     {
       //go through the list of the numbers, starting with number two (we say that number one is already sorted)
       for (int i=1; i< list.length -1; i++)
       {
         //store the value of the number we are dealing with (because it's place can be taken by other bigger numbers)
         int value = list[i];
         //define j (its a pointer to the already sorted list, starting at the largest number - back of the sorted list)
         int j = i-1;
         //as long as value is lower than the number in sorted list and we are still in the list
         while (j >= 0 && list[j] > value)
         {
           // we are going to move the higher number(from the sorted list) one step to the right (so it will make space for the current value number - witch is lower)
           list[j+1] = list[j];
           //and we move our pointer in the list to next place - lower number
           j--;
         }
         //once we come to the right spot, we insert our value number in there and start with next i value.
         list[j+1] = value;
       }
     }
   }      

Java Program on HeapSort

         public class HeapSort
   {
     private static int heapSize; //this will help us to stop sorting list numbers that are already sorted.
     /**
     * Sorts the given list in place.
     * Worst Case Performance O(nlogn)
     * Best Case Performance O(nlogn)
     * Average Case Performance O(nlogn)
     * @param A - list that needs to be sorted.
     */
     public void sortNumbers(int[] A)
     {
       HeapSort(A);
     }
     /**
     * Read sortNumbers method description.
     * @param A - list that needs to be sorted.
     */
     private void HeapSort(int[] A)
     {
       heapSize = A.length; //we need to sort all the list so heapSize == A.length
       BuildMaxHeap(A); //first we build max heap
       //now we have the biggest element in the heap on the top
       //we will exchange it with the last element in the list
       //reduce heapSize so this (biggest) element wont be sorted anymore
       //and we will call MaxHeapify once again to get new biggest element on the top
       //and once again we place it at the current end of the list, we do it all the way
       //til we will have only one element left in the heap (which will be the lowest number)
       //this way our array will get sorted, from smallest (at the start of the list) to biggest (at the end of the list).
       for (int i = A.length-1; i>0; i--)
       {
         //exchange biggest number with the current last one
         int temp = A[0];
         A[0] = A[i];
         A[i] = temp;
         //reduce the heap size
         heapSize--;
         //find new biggest
         MaxHeapify(A,0);
       }
     }
     /**
     * Builds MaxHeap (runs in linear time so: O(n) )
     * if n = amount of numbers in the list, then n/2 = amount of leaves (nodes that have no children)
     * We need to call MaxHeapify from bottom and up, but we can skip all leaves so we start at index = n/2 and go up.
     * @param A - list that we will build MaxHeap of.
     */
     private void BuildMaxHeap(int[] A)
     {
       for(int i = A.length/2-1;i>=0;i--)
       {
         MaxHeapify(A, i);
       }
     }
     /**
     * Takes O(logn) or we can also say that if subtree with root at index i has height of h
     * then running time of algorithm is O(h) (note that a binary tree with n elements has height = logn)
     * Sorts the array at the given index so that subtree meets heap requirements.
     * @param A array list
     * @param i index of the root of subtree that might be smaller than its children.
     */
     private void MaxHeapify(int[] A, int i)
     {
       int l = Left(i); //lets find left child of the given index.
       int r = Right(i);//lets find right child of the given index.
       int max;
       if (l < heapSize)
       {
         //lets check if left child is an existing child
         //if it is an existing child
         if (A[l] > A[i])
         {
           //if left child is bigger than parent
           max = l; //left child becomes maximum
         }
         else
         {
           max = i; //otherwise parent is maximum
         }
       }
       else
       {
         //if this index does not have left child
         max = i;
       }
       if (r < heapSize)
       {
         //lets check if the right child is an existing child
         //if it is existing child
         if(A[r] > A[max])
         {
           //if right child is bigger than our current maximum
           max = r; //right child becomes our new maximum
         }
       }
       if (max != i)
       {
         //if our parent is not maximum
         //we need to swap max with parent
         int temp = A[i];
         A[i] = A[max];
         A[max] = temp;
         //at the end we need to run MinHeapify on the child that was just swapped
         //and see if it is supposed to go even further down the list
         MaxHeapify(A, max);
       }
     }
     /**
     * Returns Left child index of the given parent index.
     * @param i - parent index.
     * @return - index of parents left child.
     */
     private int Left(int i)
     {
       return 2 * i;
     }
     /**
     * Returns Right child index of the given parent index.
     * @param i - parent index.
     * @return - index of parents right child.
     */
     private int Right(int i)
     {
       return (2 * i) + 1;
     }
     /**
     * Just for testing purposes.
     */
     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};

       HeapSort hs = new HeapSort();
       hs.sortNumbers(list);
       for (int i = 0;i < list.length;i++)
       {
         System.out.println(list[i]);
       }
     }
    
   }