Auto AdSense

Monday, 15 December 2014

Python Program - Database - Insert Operation






  • Database - Insert Operation
    #!/usr/bin/python

    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # Prepare SQL query to INSERT a record into the database.
    sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
         LAST_NAME, AGE, SEX, INCOME) \
         VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
         ('Mac', 'Mohan', 20, 'M', 2000)
    try:
       # Execute the SQL command
       cursor.execute(sql)
       # Commit your changes in the database
       db.commit()
    except:
       # Rollback in case there is any error
       db.rollback()

    # disconnect from server
    db.close()

Saturday, 13 December 2014

Python Program - Database - DELETE Operation:






  • Delete Example
    #!/usr/bin/python

    import MySQLdb

    # Open database connection

    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # Prepare SQL query to DELETE required records
    sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
    try:
         # Execute the SQL command
         cursor.execute(sql)
         # Commit your changes in the database
         db.commit()
    except:
         # Rollback in case there is any error
         db.rollback()

    # disconnect from server
    db.close()

Python Program - Creating Database Table






  • Creating Table
    #!/usr/bin/python

    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # Drop table if it already exist using execute() method.
    cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

    # Create table as per requirement
    sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME CHAR(20) NOT NULL,
         LAST_NAME CHAR(20),
         AGE INT,
         SEX CHAR(1),
         INCOME FLOAT )"""

    cursor.execute(sql)

    # disconnect from server
    db.close()

Python Program - Database Connection


Before connecting to a MySQL database make sure followings:
  1. You have created a database TESTDB.
  2. You have created a table EMPLOYEE in TESTDB.
  3. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
  4. User ID "testuser" and password "test123" are set to access TESTDB
  5. Python module MySQLdb is installed properly on your machine.
  6. You have gone through MySQL tutorial to understand MySQL Basics.



  • Example:
    Following is the example of connecting with MySQL database "TESTDB"

    #!/usr/bin/python

    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # execute SQL query using execute() method.
    cursor.execute("SELECT VERSION()")

    # Fetch a single row using fetchone() method.
    data = cursor.fetchone()

    print "Database version : %s " % data

    # disconnect from server
    db.close()

Python Program - Operators Precedence Example






  • #!/usr/bin/python

    a = 20
    b = 10
    c = 15
    d = 5
    e = 0

    e = (a + b) * c / d #( 30 * 15 ) / 5
    print "Value of (a + b) * c / d is ", e

    e = ((a + b) * c) / d # (30 * 15 ) / 5
    print "Value of ((a + b) * c) / d is ", e

    e = (a + b) * (c / d); # (30) * (15/5)
    print "Value of (a + b) * (c / d) is ", e

    e = a + (b * c) / d; # 20 + (150/5)
    print "Value of a + (b * c) / d is ", e
  • Output
    Value of (a + b) * c / d is 90
    Value of ((a + b) * c) / d is 90
    Value of (a + b) * (c / d) is 90
    Value of a + (b * c) / d is 50

Python Program - Membership Operators


  • #!/usr/bin/python

    a = 10
    b = 20
    list = [1, 2, 3, 4, 5 ];

    if ( a in list ):
       print "Line 1 - a is available in the given list"
    else:
       print "Line 1 - a is not available in the given list"

    if ( b not in list ):
       print "Line 2 - b is not available in the given list"
    else:
       print "Line 2 - b is available in the given list"

    a = 2
    if ( a in list ):
       print "Line 3 - a is available in the given list"
    else:
       print "Line 3 - a is not available in the given list"
  • Output
    Line 1 - a is not available in the given list
    Line 2 - b is not available in the given list
    Line 3 - a is available in the given list

Sunday, 7 December 2014

Python Program - Logical Operators



  • #!/usr/bin/python

    a = 10
    b = 20
    c = 0

    if ( a and b ):
       print "Line 1 - a and b are true"
    else:
       print "Line 1 - Either a is not true or b is not true"

    if ( a or b ):
       print "Line 2 - Either a is true or b is true or both are true"
    else:
       print "Line 2 - Neither a is true nor b is true"

    a = 0
    if ( a and b ):
       print "Line 3 - a and b are true"
    else:
       print "Line 3 - Either a is not true or b is not true"

    if ( a or b ):
       print "Line 4 - Either a is true or b is true or both are true"
    else:
       print "Line 4 - Neither a is true nor b is true"

    if not( a and b ):
       print "Line 5 - a and b are true"
    else:
       print "Line 5 - Either a is not true or b is not true"
  • Output
    Line 1 - a and b are true
    Line 2 - Either a is true or b is true or both are true
    Line 3 - Either a is not true or b is not true
    Line 4 - Either a is true or b is true or both are true
    Line 5 - a and b are true

Python Program - Identity Operators






  • #!/usr/bin/python

    a = 20
    b = 20

    if ( a is b ):
       print "Line 1 - a and b have same identity"
    else:
       print "Line 1 - a and b do not have same identity"

    if ( id(a) == id(b) ):
       print "Line 2 - a and b have same identity"
    else:
       print "Line 2 - a and b do not have same identity"

    b = 30
    if ( a is b ):
       print "Line 3 - a and b have same identity"
    else:
       print "Line 3 - a and b do not have same identity"

    if ( a is not b ):
       print "Line 4 - a and b do not have same identity"
    else:
       print "Line 4 - a and b have same identity"
  • Output
    Line 1 - a and b have same identity
    Line 2 - a and b have same identity
    Line 3 - a and b do not have same identity
    Line 4 - a and b do not have same identity

Python Program - Basic - Comparison Operators






  • #!/usr/bin/python

    a = 21
    b = 10
    c = 0

    if ( a == b ):
       print "Line 1 - a is equal to b"
    else:
       print "Line 1 - a is not equal to b"

    if ( a != b ):
       print "Line 2 - a is not equal to b"
    else:
       print "Line 2 - a is equal to b"

    if ( a <> b ):
       print "Line 3 - a is not equal to b"
    else:
       print "Line 3 - a is equal to b"

    if ( a < b ):
       print "Line 4 - a is less than b"
    else:
       print "Line 4 - a is not less than b"

    if ( a > b ):
       print "Line 5 - a is greater than b"
    else:
       print "Line 5 - a is not greater than b"

    a = 5;
    b = 20;
    if ( a <= b ):
       print "Line 6 - a is either less than or equal to b"
    else:
       print "Line 6 - a is neither less than nor equal to b"

    if ( b >= a ):
       print "Line 7 - b is either greater than or equal to b"
    else:
       print "Line 7 - b is neither greater than nor equal to b"
  • Output
    Line 1 - a is not equal to b
    Line 2 - a is not equal to b
    Line 3 - a is not equal to b
    Line 4 - a is not less than b
    Line 5 - a is greater than b
    Line 6 - a is either less than or equal to b
    Line 7 - b is either greater than or equal to b

Python Program - Bitwise Operators Example

       #!/usr/bin/python

a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c

c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c

c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c

c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Output

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Python Program - Basic - Assignment Operators Example

#!/usr/bin/python

a = 21
b = 10
c = 0

c = a + b
print "Line 1 - Value of c is ", c

c += a
print "Line 2 - Value of c is ", c

c *= a
print "Line 3 - Value of c is ", c

c /= a
print "Line 4 - Value of c is ", c

c = 200
c %= a
print "Line 5 - Value of c is ", c

c **= a
print "Line 6 - Value of c is ", c

c //= a
print "Line 7 - Value of c is ", c

Output

Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 11
Line 6 - Value of c is 1331
Line 7 - Value of c is 443

Python Program - Arithmatic Operators Example

#!/usr/bin/python

a = 21
b = 10
c = 0

c = a + b
print "Line 1 - Value of c is ", c

c = a - b
print "Line 2 - Value of c is ", c

c = a * b
print "Line 3 - Value of c is ", c

c = a / b
print "Line 4 - Value of c is ", c

c = a % b
print "Line 5 - Value of c is ", c

a = 2
b = 3
c = a**b #Exponent - Performs exponential (power) calculation on operators
print "Line 6 - Value of c is ", c

a = 10
b = 5
c = a//b #Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed.
print "Line 7 - Value of c is ", c

Output

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2

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