Sunday, December 9, 2012

java.net.BindException: Address already in use: JVM_Bind:8080

There are many ways to come out of this Tomcat port address problem.....some say kill the port...some say change the port number by going to server.xml and giving a different port number.....and etc....

But I would say just exit from eclipse and start again this way you would get back that port address again....
and another thing I observed was in your Tomcat Manager once you go to your application there would be options like start stop etc...dont press the stop or other links (buttons) as it would in my understanding just stop the session and would not kill it...and hence the Tomcat port will be left hanging

Saturday, December 8, 2012

System.out.println


public class Sysout_class {
   
    public static void main(String[] args) {

    System.out.println("Hello");
    //As you can see from the Oracle Spec the following lines are written
    /*
    * %W% %E%
    *
    * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
    * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    */

    //(A) In System Class it calls the PrintStream class
    /*       
    System is a final class defined in java.lang.*
       
    public final class System {
    }

    * The "standard" output stream. This stream is already
    * open and ready to accept output data. Typically this stream
    * corresponds to display output or another output destination
    * specified by the host environment or user.
    * <p>
    * For simple stand-alone Java applications, a typical way to write
    * a line of output data is:
    * <blockquote><pre>
    *     System.out.println(data)
    * </pre></blockquote>
    * <p>
    * See the <code>println</code> methods in class <code>PrintStream</code>.
    *
    * @see     java.io.PrintStream#println()
    * @see     java.io.PrintStream#println(boolean)
    * @see     java.io.PrintStream#println(char)
    * @see     java.io.PrintStream#println(char[])
    * @see     java.io.PrintStream#println(double)
    * @see     java.io.PrintStream#println(float)
    * @see     java.io.PrintStream#println(int)
    * @see     java.io.PrintStream#println(long)
    * @see     java.io.PrintStream#println(java.lang.Object)
    * @see     java.io.PrintStream#println(java.lang.String)
   
    public final static PrintStream out = nullPrintStream();
   
    private static PrintStream nullPrintStream() throws NullPointerException {
    if (currentTimeMillis() > 0) {
        return null;
    }
    throw new NullPointerException();
    }
   
               
    (B)It goes to the PrintStream class
    public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
    }
   
    (B1)
    public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
    }
   
    (B2)
    private void write(String s) {
    try {
        synchronized (this) {
        ensureOpen();
        textOut.write(s);
        textOut.flushBuffer();
        charOut.flushBuffer();
        if (autoFlush && (s.indexOf('\n') >= 0))
            out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
    }   
   
    public void write(String str) throws IOException {
    write(str, 0, str.length());
    }
   
    (B3)
    public void write(String str) throws IOException {
    write(str, 0, str.length());
    }
   
    (C)   
    private BufferedWriter textOut;
   
    BufferedWriter's Super class is Writer Class and in that class it calls the write method
    print(x) finally goes to private BufferedWriter textOut;
 
    public void write(String str) throws IOException {
    write(str, 0, str.length());
    }
   
    (D)
    Similarly for newLine() from PrintStream class (B) the same procedures as (B1), (B2), (B3) and (C) follows;
    */
    }
}

Clone

(a)

public class CloneFirst implements Cloneable{
   
    int a;
    String b;
    //As you can see from the Oracle Spec the following lines are written
    public CloneFirst cloneMethod() throws CloneNotSupportedException{
       
        /*
         * %W% %E%
         *
         * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
         * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
        */       
        /**
         * Creates and returns a copy of this object.  The precise meaning
         * of "copy" may depend on the class of the object. The general
         * intent is that, for any object <tt>x</tt>, the expression:
         * <blockquote>
         * <pre>
         * x.clone() != x</pre></blockquote>
         * will be true, and that the expression:
         * <blockquote>
         * <pre>
         * x.clone().getClass() == x.getClass()</pre></blockquote>
         * will be <tt>true</tt>, but these are not absolute requirements.
         * While it is typically the case that:
         * <blockquote>
         * <pre>
         * x.clone().equals(x)</pre></blockquote>
         * will be <tt>true</tt>, this is not an absolute requirement.
         * <p>
         * By convention, the returned object should be obtained by calling
         * <tt>super.clone</tt>.  If a class and all of its superclasses (except
         * <tt>Object</tt>) obey this convention, it will be the case that
         * <tt>x.clone().getClass() == x.getClass()</tt>.
         * <p>
         * By convention, the object returned by this method should be independent
         * of this object (which is being cloned).  To achieve this independence,
         * it may be necessary to modify one or more fields of the object returned
         * by <tt>super.clone</tt> before returning it.  Typically, this means
         * copying any mutable objects that comprise the internal "deep structure"
         * of the object being cloned and replacing the references to these
         * objects with references to the copies.  If a class contains only
         * primitive fields or references to immutable objects, then it is usually
         * the case that no fields in the object returned by <tt>super.clone</tt>
         * need to be modified.
         * <p>
         * The method <tt>clone</tt> for class <tt>Object</tt> performs a
         * specific cloning operation. First, if the class of this object does
         * not implement the interface <tt>Cloneable</tt>, then a
         * <tt>CloneNotSupportedException</tt> is thrown. Note that all arrays
         * are considered to implement the interface <tt>Cloneable</tt>.
         * Otherwise, this method creates a new instance of the class of this
         * object and initializes all its fields with exactly the contents of
         * the corresponding fields of this object, as if by assignment; the
         * contents of the fields are not themselves cloned. Thus, this method
         * performs a "shallow copy" of this object, not a "deep copy" operation.
         * <p>
         * The class <tt>Object</tt> does not itself implement the interface
         * <tt>Cloneable</tt>, so calling the <tt>clone</tt> method on an object
         * whose class is <tt>Object</tt> will result in throwing an
         * exception at run time.
         *
         * @return     a clone of this instance.
         * @exception  CloneNotSupportedException  if the object's class does not
         *               support the <code>Cloneable</code> interface. Subclasses
         *               that override the <code>clone</code> method can also
         *               throw this exception to indicate that an instance cannot
         *               be cloned.
         * @see java.lang.Cloneable
         */
        return (CloneFirst)super.clone();
       
    }
}

(b)

public class CloneCallingFirst extends CloneFirst{

    public static void main(String[] args) throws CloneNotSupportedException {
      
        CloneFirst cf1 = new CloneFirst();
        cf1.a=10;
        cf1.b="Ten";
        CloneFirst cf2;
        cf2 = cf1.cloneMethod();
      
        System.out.println("The Answer for a is " + cf2.a);
        System.out.println("The Answer for b is " + cf2.b);
      
    }

Tuesday, November 6, 2012

If two classes are within the same package you dont have to use import statement

(a)
package pack1;
public class ClassA extends ClassB {

    public static void main(String[] args) {
        /*
          You can see from here when we are importing a class within the same package
          say pack1 you need not explicitly import the package say import pack1.ClassB
          also in the class A if you see we have not given any declaration for the integer
          variable i (without any declaration it will take it as default or else protected or public)
        */
        ClassB obj = new ClassB();
        System.out.println("The Output in Class A is " + obj.i);

    }

}

(b)
package pack1;
public class ClassB {
    //Note : If you declare it as private it will show error in ClassA as the classes are not same
    //Can be declared protected, public or (just like that..that is default)
    int i=10;
}

Answer
----------
The Output in Class A is 10

How to use size method in java

import java.util.*;
public class size {

    public static void main(String[] args) {
        ArrayList a1 = new ArrayList();
        a1.add("1");
        a1.add("2");
        a1.add("3");
        System.out.println("\n ArrayList size is "+a1.size());
    }

}

Answer
----------
ArrayList size is 3

retainAll method of Collection interface in java

import java.util.*;
public class retainAll {
    public static void main(String[] args) {


        ArrayList a1 = new ArrayList();
        a1.add(1);
        a1.add(2);
       
        ArrayList a2 = new ArrayList();
        a2.add(3);
        a2.add(4);       
       
        a2.add(a1);
        for(int i=0;i<a2.size();i++)
        {
            System.out.println("a2 list is " + a2.get(i));
        }       
        System.out.println("");
        boolean retainCheck;
       
        retainCheck = a2.retainAll(a1);
        /*
        a2.retainAll(a1) will delete all the elements of the invoked collection (a1) and will retain 
        all the elements of the invoking collection a2
        */
       
        for(int i=0;i<a1.size();i++)
        {
            System.out.println("a1 list is " + a1.get(i));
        }
        System.out.println("");
        System.out.println("a2's size is " + a2.size());
        for(int i=0;i<a2.size();i++)
        {
            System.out.println("a2 list is " + a2.get(i));
        }       
       
    }
}

Answer
----------
a2 list is 3
a2 list is 4
a2 list is [1, 2]

a1 list is 1
a1 list is 2

a2's size is 0

How to use iterator method in java

/*
iterator() method is defined as  - Iterator iterator in Collection interface
*/
import java.util.*;
public class iteratorMethod {
    public static void main(String[] args) {


        ArrayList a1 = new ArrayList();
        a1.add("a");
        a1.add("b");
        a1.add("c");
        a1.add("d");
       
        Iterator itr = a1.iterator();
        while(itr.hasNext())
        {
            Object instance = itr.next();
            System.out.println("The Output is " + instance);
        }
       
    }
}

Answer
----------
The Output is a
The Output is b
The Output is c
The Output is d

isEmpty method of Collection interface in java

/*
   isEmpty() method is defined as - boolean isEmpty() in Collection interface
*/
import java.util.*;
public class isEmpty {

    public static void main(String[] args) {
       
        ArrayList a1 = new ArrayList();
        a1.add("One");
        a1.add("Two");
        a1.add("Three");   
       
        boolean removeCheck;
        removeCheck = a1.remove(a1);
        removeCheck = a1.remove(a1);
        //.....
       
        System.out.println("The ArrayList on performing the a1.remove(a1) method) " + a1.isEmpty());
        for(int i=0;i<a1.size();i++)
        {
            System.out.println("The ArrayList elements (after the remove() method) are " + a1.get(i));
        }
        /*
        because a1.remove(a1) tries to remove the entire elements present in a1 but since boolean 
        remove(Object obj) is intended to remove only one instance object from the invoking  
        collection something like this...below would be the correct code
        */
        removeCheck = a1.remove(a1.get(0));
        removeCheck = a1.remove(a1.get(1));
        for(int i=0;i<a1.size();i++)
        {       
            System.out.println("\n The ArrayList will now decrease (after performing the remove(a1.get(i)) method) " + a1.get(i) + "\n");
        }
       
        a1.add("Four");
        a1.add("Five");
        a1.add("Six");       
        removeCheck = a1.removeAll(a1);
        System.out.println("The ArrayList should be empty (after removeAll() method) " + a1.isEmpty() + " as the size is now " +a1.size() + "\n");
       
        //The below does not gets displayed because the
        for(int i=0;i<a1.size();i++)
        {
            System.out.println("The ArrayList elements (after the removeAll() method) are" + a1.get(i));
        }       
               
    }

}

Answer
--------
The ArrayList on performing the a1.remove(a1) method) false
The ArrayList elements (after the remove() method) are One
The ArrayList elements (after the remove() method) are Two
The ArrayList elements (after the remove() method) are Three

The ArrayList will now decrease (after performing the remove(a1.get(i)) method) Two

The ArrayList should be empty (after removeAll() method) true as the size is now 0

indexOf method in List Interface in Java

/*
indexOf method is defined as  - int indexOf(Object obj) in List Interface
*/

import java.util.*;
public class indexOf {

    public static void main(String[] args) {
       
        ArrayList a1 = new ArrayList();
        a1.add(0,"a");
        a1.add(1,"b");
        a1.add(2,"c");
        a1.add(3,"d");
       
        System.out.println("The size of a1 is " + a1.size());
        System.out.println("The Value of a1 is " + a1.indexOf("c"));
    }

}

Answer
----------
The size of a1 is 4
The Value of a1 is 2

hashCode in Java

import java.util.ArrayList;
public class hashCode {

    public static void main(String[] args) {

        ArrayList a1 = new ArrayList();
        a1.add("One");
        a1.add("Two");
        a1.add("Three");
       
        int hashCodeforInvokingCollection = 0;
        for(int i=0;i<a1.size();i++)
        {
            //hashCodeforInvokingCollection = a1.get(i).hashCode();
            hashCodeforInvokingCollection = a1.get(i).hashCode();
            System.out.println(" a1's "+a1.get(i)+" " +hashCodeforInvokingCollection);
        }       
       
    }
}

Answer
----------
a1's One 79430
a1's Two 84524
a1's Three 80786814

How to use get Method in ArrayList in Java

/*
List interface defines the method as - Object get(int index)
*/
import java.util.ArrayList;
public class getMethod {

    public static void main(String[] args) {
        ArrayList a1 = new ArrayList();
        for(int i=1;i<=3;i++)
        {
            a1.add(i);
        }
       
        System.out.println("The size of a1 is " + a1.size());
        for(int i=0;i<a1.size();i++)
        {
            System.out.println("The Value of a1 is " + a1.get(i));
        }
    }

}

Answer
----------
The size of a1 is 3
The Value of a1 is 1
The Value of a1 is 2
The Value of a1 is 3

IndexOutOfBoundsException in add Method of List Interface in Java

import java.util.*;
public class addError {
    public static void main(String[] args) {

    //Error (a)
    ArrayList a1 = new ArrayList();
    a1.add(0, "0");
    a1.add(1, "after 0 ");
    a1.add(2, "after 1 ");
    a1.add(4, "after 2 ");
    /*
       a1.add(4) ? what is this ?....
    */
       
    /*
       The above and below Array add method will show an IndexOutOfBoundsException because 
       in list (interface) the method's index should follow sequentially starting from 0 to n but in the 
       list above we have added the 4th index directly after 2nd index and hence the list adds upto 
       0,1,2 but after 2 when it is expecting the 3rd index to be entered in the memory storage... the 
       4th element is entered in memory and hence it throws IndexOutOfBoundsException as list 
       stores in memory only sequentially.
   
       Index should start from 0 and not from 1, the below add method shows error since the first 
       index should be 0 and following sequentially
    */
    //Error (b)
    a1.add(1, "1");
    a1.add(2, "after 1 ");
    a1.add(3, "after 2 ");
    a1.add(4, "after 3 ");
   
  }
}

Answer :
------------
/*
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)
    at java.util.ArrayList.add(ArrayList.java:426)
    at addError.main(addError.java:10)

    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)
    at java.util.ArrayList.add(ArrayList.java:426)
    at addError.main(addError.java:9)
*/

addAll method of List interface in Java

/*
addAll Method is defined as boolean addAll(int index, Collection c)
*/

import java.util.*;
public class addAll {

    public static void main(String[] args) {

        ArrayList a1 = new ArrayList();
        for(int i=1;i<=3;i++)
        {
            a1.add(i);
        }
       
        System.out.println("The size of a1 is " + a1.size());
        for(int i=0;i<a1.size();i++)
        {
            System.out.println("The Value of a1 is " + a1.get(i));
        }
       
        ArrayList a2 = new ArrayList();
        a2.addAll(0, a1);
        /*
          Here if you see even after adding the collection element a1 to addAll method of ArrayList a2
          the size and value of a2 collection element remains the same as a1 
        */
        System.out.println("\nThe size of a2 is " + a2.size());
        for(int i=0;i<a2.size();i++)
        {
            System.out.println("The Value of a2 is " + a2.get(i));
        }

        ArrayList a3 = new ArrayList();
        a3.addAll(0, a2);
        /*
          Not only that even if you add collection element a2 to addAll method of ArrayList a3
          the size and value of a3 collection element remains the same as a1 or a2.
        */
        System.out.println("\nThe size of a3 is " + a3.size());
        for(int i=0;i<a3.size();i++)
        {
            System.out.println("The Value of a3 is " + a3.get(i));
        }       
       
    }

}

Answer
--------

The size of a1 is 3
The Value of a1 is 1
The Value of a1 is 2
The Value of a1 is 3

The size of a2 is 3
The Value of a2 is 1
The Value of a2 is 2
The Value of a2 is 3

The size of a3 is 3
The Value of a3 is 1
The Value of a3 is 2
The Value of a3 is 3

Sunday, October 21, 2012

equals method of collection in java

import java.util.ArrayList;

public class equalsMethod {
    public static void main(String[] args) {

        ArrayList a1 = new ArrayList();
        a1.add("One");
        a1.add("Two");
        a1.add("Three");
        a1.add("Four");
        a1.add("Five");

        ArrayList a2 = new ArrayList();
        a2.add("10");
        a2.add("20");
        a2.add("Two");
        a2.add("Four");
        a2.add("5");
   
        boolean result;
       
        for(int i=0;i<a1.size();i++)
        {

            /*
               equals method of collection checks whether the index of one collection object has the 
               same value as the corresponding index of the other collection object.Here it checks for 
               whether a1.get(1) equals a2.get(1), a1.get(2) equals a2.get(2) or not...correspondingly 
               etc...
            */
            result = a1.get(i).equals(a2.get(i));
            System.out.println("a2's "+a2.get(i)+" and a1's "+a1.get(i)+" are equal ? " +result);
        }

    }
}

Answer
----------
a2's 10 and a1's One are equal ? false
a2's 20 and a1's Two are equal ? false
a2's Two and a1's Three are equal ? false
a2's Four and a1's Four are equal ? true

a2's 5 and a1's Five are equal ? false 

contains method of collection in java

import java.util.*;
import java.*;

public class containsMethodOfCollection {
    public static void main(String[] args) {       

        ArrayList a1 = new ArrayList();
        a1.add("One");
        a1.add("Two");
        a1.add("Three");
        a1.add("Four");
        a1.add("Five");
               
        ArrayList a2 = new ArrayList();
        a2.add("10");
        a2.add("20");
        a2.add("Two");
        a2.add("Four");
        a2.add("5");
   
        boolean result;
        /*
           From the result you can find out that  for each a2.get(i), index it does not check with the 
           corresponding index of a1, instead a2.get(i) only checks internally that whether all the 
           components of a2 index wise internally do have an component of the same in the a1 
           arraylist or not.
        */
        for(int i=0;i<a1.size();i++)
        {
            result = a1.contains(a2.get(i));
            System.out.println("a2's "+a2.get(i)+" and a1's "+a1.get(i)+" are equal ? " +result);
        }
        /*
          containsAll returns true only when all the componenets of a1 or a2 have a corresponding 
          equal component in the other collection object, even if one component mismatches the 
          boolean returns false 
        */
        for(int i=0;i<a1.size();i++)
        {
            result = a1.containsAll(a2);
            System.out.println("a2's "+a2.get(i)+" and a1's "+a1.get(i)+" are equal ? " +result);
        }
       
    }
}

Answer : 
------------

a2's 10 and a1's One are equal ? false
a2's 20 and a1's Two are equal ? false
a2's Two and a1's Three are equal
? true
a2's Four and a1's Four are equal ? true
a2's 5 and a1's Five are equal ? false


a2's 10 and a1's One are equal ? false
a2's 20 and a1's Two are equal ? false
a2's Two and a1's Three are equal ? false
a2's Four and a1's Four are equal ? false
a2's 5 and a1's Five are equal ? false

Saturday, October 20, 2012

addAll Method Example in java

import java.util.*;
public class addAll
{
    public static void main(String[] args)
    {
        // Create ArrayList and LinkedList collections:
        ArrayList a1 = new ArrayList();
        //LinkedList c1 = new LinkedList();
       
        TreeSet ts = new TreeSet();
        // Initialize aList:
        a1.add("BalajiA");
        a1.add("PadmaB");
        a1.add("BalajiB");
        a1.add("PadmaA");
       
        ts.add("BalajiC");
        ts.add("BalajiD");       
        ts.add("PadmaS");
        ts.add("PadmaT");       
       
        // Add all the elements of aList to lList:
        /*
        c1.addAll(a1);
        */
        boolean result = ts.addAll(a1);
        System.out.println("The Result of TreeList is " + ts + " and TreeList's size is " + ts.size());
        System.out.println("The Result of ArrayList is " + a1 + " and ArrayList's size is " + a1.size());
        System.out.println("True or False ? " + result);
       
        //Create ArrayList and LinkedList collections:
        Collection aList = new ArrayList();
        Collection lList = new LinkedList();
        //Initialize aList:
        aList.add("NewBalaji");
        aList.add("NewPadma");
        //Add all the elements of aList to lList:
        lList.addAll(aList);
        //Display lList:
        System.out.println("Collection  ArrayList is " + aList);
        System.out.println("Collection LinkedList is " + lList);
       
       
        List<Integer> listA = new ArrayList<Integer>();
        List<Integer> listB = new ArrayList<Integer>();

        listA.add(1);
        listA.add(2);
        listA.add(3);
        listA.add(4);

        listB.add(1);
        listB.add(2);


        listA.addAll(listB);

        for(Integer i : listA){
        System.out.print(i);
        }
       
    }
}

Answer : 
-----------
The Result of TreeList is [BalajiA,BalajiB,BalajiC,BalajiD,PadmaA,PadmaB,PadmaS,PadmaT]  
and TreeList's size is 8
The Result of ArrayList is [BalajiA, PadmaB, BalajiB, PadmaA] and ArrayList's size is 4
True or False ? true
Collection  ArrayList is [NewBalaji, NewPadma]
Collection LinkedList is [NewBalaji, NewPadma]
123412

clear method Example in java

import java.util.*;
public class clearMethod {

    public static void main(String[] args) {
       
        ArrayList a1 = new ArrayList();
        a1.add(1);
        a1.add(2);
        a1.add(3);
        a1.add(4);
        a1.add(5);
       
        System.out.println("ArrayList size is " + a1.size());
        /*
          After the addition of 5 numbers to the ArrayList the size becomes 5
        */
        a1.clear();
        /*
          now after the clear method is invoked in the ArrayList its size becomes zero
        */
        System.out.println("ArrayList size is now " + a1.size());

    }

}


Answer : 
------------
ArrayList size is 5
ArrayList size is now 0

Saturday, October 13, 2012

Sum total in oracle

Lets say you are running sql plus and some records come, now you have to calculate the sum of a column.


compute sum of column on report
break on report

/


compute sum on report
break on report
/

For break on report you dont necessarily have to type until the last letter k, even if you just type brea
it will work.

Tuesday, October 2, 2012

IndexOutOfBoundsException Example in Java

IndexOutOfBoundsException occurs whenever the number(index) variable increases the ArraySize limit.

(a)
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class IndexOutOfBoundsException {
    public static void main(String args[]){       
        ArrayList a1 = new ArrayList();
           Employee obj = new Employee();
           a1  = (ArrayList)obj.displayRecord();
           Iterator itr = a1.iterator();
           int variable = 0;
           if(a1.size() > 0)
           {
                System.out.println(a1.size());
               /*
               The Arraysize is 10. that is the total number of records are 10., but the ArrayList 
               length starts from 0 until 9, that is internally the index in (b) class ArrayList                                      displayRecord() {} is from 0  to 9 but when it comes to (a) class for{} loop , the for                            loop is  set from 0 to 10....which means that when the for loop  in class(a) starts at                              0 it would be going to the first record in the ArrayIndex  ---  starting at 0(1st record), 
               and hence when the for loop reaches 9 The ArrayIndex  would have reached its full                       ull              strength of 9 (or 10th record) and when the                   class (a)'s for loop reaches 10, obj=(Employee)a1.get(i); will search for the (11th record !!)
               which is not available and hence will throw an IndexOutOfBoundsException
               */

               for(int i=0;i<=a1.size();i++)
               {   
                   obj=(Employee)a1.get(i);
                   variable = obj.getEmployeeNumber();
                   System.out.println(variable);
               }
           }
    }
}

(b)

import java.util.*;
public class Employee {
 
   private int employeeNumber=1;
   public int getEmployeeNumber()
   {
       return employeeNumber;
   }
   public void setEmployeeNumber(int employeeNumber)
   {
       this.employeeNumber=employeeNumber;
   }   
   public ArrayList displayRecord()
   {
       ArrayList showRecord=new ArrayList();
       /*Array Index for loop starts here*/
       for(int i=1;i<=10;i++)
       {
            Employee empObj=new Employee();
            empObj.setEmployeeNumber(i);
            showRecord.add(empObj);
       }
       return showRecord;        
       /*Array Index for loop ends here*/
    }

 }

Answer
----------
10
1
2
3
4
5
6
7
8
9
10
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.get(ArrayList.java:382)
    at pack1.IndexOutOfBoundsException.main(IndexOutOfBoundsException.java:19)

Use of Add Method in ArrayList

(a)

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListServeletforAddMethod {
    public static void main(String args[]){
       
           ArrayList a1 = new ArrayList();
           Employee obj = new Employee();
           a1  = (ArrayList)obj.displayRecord();
           Iterator itr = a1.iterator();
           int variable = 0;
           if(a1.size() > 0)
           {
               System.out.println(a1.size());
               for(int i=0;i<a1.size();i++)
               {   
                   obj=(Employee)a1.get(i);
                   variable = obj.getEmployeeNumber();
                   System.out.println(variable);
               }
           }

    }
}

(b)
import java.util.*;
public class Employee {
   
    private int employeeNumber=1;
   
    public int getEmployeeNumber()
    {
        return employeeNumber;
    }
    public void setEmployeeNumber(int employeeNumber)
    {
        this.employeeNumber=employeeNumber;
    }   
       
    public ArrayList displayRecord()
    {
        ArrayList showRecord=new ArrayList();
        for(int i=1;i<=10;i++)
        {
            Employee empObj=new Employee();
            empObj.setEmployeeNumber(i);
            showRecord.add(empObj);
        }
        return showRecord;       
    }

}


Answer
--------

10
1
2
3
4
5
6
7
8
9
10

OutOfMemoryError in ArrayList, Example

import java.util.*;
public class OutofMemoryErrorInArrayList {
    public static void main(String[] args) {
        ArrayList a1 = new ArrayList();
        for(int i=1;i<=99999999;i++)
        {
            try
            {
                a1.add("a");
            }
            catch(Exception e)
            {
                System.out.println("Array Size is " + a1.size());
            }
        }       
    }
}

Answer
--------
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:2245)
    at java.util.Arrays.copyOf(Arrays.java:2219)
    at java.util.ArrayList.grow(ArrayList.java:213)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:187)
    at java.util.ArrayList.add(ArrayList.java:411)
    at OutofMemoryErrorInArrayList.main(OutofMemoryErrorInArrayList.java:9)

ArrayIndexOutOfBoundsException Example in Java

import java.util.*;
public class ArrayIndexOutOfBoundsException {

    public static void main(String[] args) {
           
            String []array = new String[0];
            array[0] = "0";
            System.out.println("String []array ? " + array[0]);

    }

}

Answer
--------
The following error occurs

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ArrayIndexOutOfBoundsException.main(ArrayIndexOutOfBoundsException.java:7)

ArrayStoreException Example in Java

import java.util.*;
public class ArrayStoreException {
    public static void main(String[] args) {

        Object x[] = new String[3];
        x[0] = 0;       
        /*  
        List<String> myList = new ArrayList<String>(); 
        myList.add("Hello"); 
        myList.add("World"); 
        String[] myStrings = myList.toArray(new String[0]); 
        System.out.println("myStrings is " + myStrings.length + " long");
        */
   
    }
}

Answer
---------

On compiling the following error occurs

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
    at ArrayStoreException.main(ArrayStoreException.java:6)

Difference between Standard Arrays and ArrayList ?

import java.util.*;
public class StandardArrays_Vs_ArrayList {

    public static void main(String[] args) {
        /*
        We Cannot Define it this [] (i.e) we cannot give any empty declaration, declaring such will

        throw an CompiletimeException we have to start the declaration Starting from Numeric 
        Value 1, (i.e) we cannot declare as new String[0] as it will throw an RuntimeException
        String []array = new String[];
       
*/
        String []array = new String[1];
        array[0] = "0";
        System.out.println("String []array " + array[0]);
       
        /*
        The below programme proves that an ArrayList grows dynamically...
       
*/
        ArrayList a1 = new ArrayList();
        a1.add("One");
        /*
        ... as you can see here the ArrayList size has not been specified and the ArrayList size is 

        now 1
       
*/
        System.out.println("The Initial Size is " + a1.size());
        a1.add("Two");
        a1.add("Three");
        /*
        and here after adding 2 records the ArrayList size increases to 3.it can keep increasing to 

        the point of when there is an OutOfMemoryError due to insufficient heapspace.
       
*/
        System.out.println("Now The Size is " + a1.size());
    }

}

Tuesday, September 18, 2012

StringBuilder Constructor with default argument as a String variable (i.e), initialized to the contents of the specified string, public StringBuilder(String str)

StringBuilder(String str)
Constructs a string builder initialized to the contents of the specified string.
The initial capacity of the string builder is 16 plus the length of the string argument.

Parameters:
str - the initial contents of the buffer.
Throws:
NullPointerException - if str is null

public class StringBuilderConstructorofSpecifiedString {
    public static void main(String[] args) {

        StringBuilder sb1 = new StringBuilder("1");
        System.out.println("Initial Capacity of sb1 : " + sb1.capacity());
        System.out.println("Initial Size of sb1 : " + sb1.length());       
       
        sb1.append("2");
        System.out.println("Capacity of sb1 After 2 Addition  : " + sb1.capacity());
        System.out.println("Size of sb1 After 2 Addition : " + sb1.length());       
       
        sb1.append("123456789012345");
        System.out.println("Capacity of sb1 When it Equals Seventeen Numbers : " + sb1.capacity());
        System.out.println("Size of sb1 When it Equals Seventeen Numbers : " + sb1.length());       

        sb1.append("6");
        System.out.println("Capacity of sb1 When it exceeds Seventeen Numbers : " + sb1.capacity());
        System.out.println("Size of sb1 When it exceeds Seventeen Numbers : " + sb1.length());           
       
        StringBuilder sb2 = new StringBuilder("");
        System.out.println("Initial Capacity of sb2 : " + sb2.capacity());
        System.out.println("Initial Size of sb2 : " + sb2.length());

        sb2.append("1");
        System.out.println("Capacity of sb2 After One Additions : " + sb2.capacity());
        System.out.println("Size of sb2 After One Additions : " + sb2.length());
       
        sb2.append("1234567890123456");
        System.out.println("Capacity of sb2 When it exceeds Sixteen Numbers : " + sb2.capacity());
        System.out.println("Size of sb2 When it exceeds Sixteen Numbers : " + sb2.length());
       
        sb2.append("1234567890123456789");
        System.out.println("Capacity of sb2 When it exceeds ThirtyFour Numbers : " + sb2.capacity());
        System.out.println("Size of sb2 When it is less than or Equal to ThirtyFour Numbers:"+sb2.length());          
    }
}

The  Answers Are :
----------------------
(a1)
Initial Capacity of sb1 : 17
        Initial Size of sb1 : 1

(b1)


Capacity of sb1 After 2 Addition  : 17
        Size of sb1 After 2 Addition  :
2
(c1)
Capacity of sb1 When it Equals Seventeen Numbers : 17
        Size of sb1 When it Equals Seventeen Numbers : 17

(d1)

Capacity of sb1 When it exceeds Seventeen Numbers : 36
        Size of sb1 When it exceeds Seventeen Numbers : 18

 

(a2)
Initial Capacity of sb2 : 16
        Initial Size of sb2 : 0

(b2)

Capacity of sb2 After One Additions : 16
        Size of sb2 After One Additions : 1

(c2)

Capacity of sb2 When it exceeds Sixteen Numbers : 34
        Size of sb2 When it exceeds Sixteen Numbers : 17

(d2)

Capacity of sb2 When it exceeds ThirtyFour Numbers : 70
Size of sb2 When it is less than or Equal to ThirtyFour Numbers : 36

 

Monday, September 17, 2012

StringBuilder() Constructor with no characters in it

public class StringBuilderConstructor {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
       
        //(a)
        System.out.println("Initial Capacity : " + sb.capacity());
        System.out.println("Initial Size : " + sb.length());
       
        sb.append("1234567890123456");
      
        //(b)
        System.out.println("Capacity After Sixteen Additions : " + sb.capacity());
        System.out.println("Size After Sixteen Additions : " + sb.length());
       
        sb.append("7");
      
        //(c)
        System.out.println("Capacity When it exceeds Sixteen Numbers : " + sb.capacity());
        System.out.println("Size When it exceeds Sixteen Numbers : " + sb.length());
       
        sb.append("12345678901234567");
      
        //(d)
        System.out.println("Capacity When it Equals ThirtyFour Numbers : " + sb.capacity());
        System.out.println("Size When it is less than or Equal to ThirtyFour Numbers : " + sb.length());       
   
    }
}

The  Answers Are :
----------------------
(a)
Initial Capacity : 16
       Initial Size : 0

 
(b)
Capacity After Sixteen Additions : 16
       Size After Sixteen Additions : 16
 
(c)
Capacity When it exceeds Sixteen Numbers : 34
       Size When it exceeds Sixteen Numbers : 17
 
(d)
Capacity When it exceeds ThirtyFour Numbers : 34
Size When it is less than or Equal to ThirtyFour Numbers : 34

Sunday, September 16, 2012

StringBuilder Constructors

StringBuilder has 4 Constructor types for it

They are
1) StringBuilder()
2) StringBuilder(CharSequence seq)
3) StringBuilder(int capacity)
4) StringBuilder(String str)

After Writing the Program, in the Middle of the Constructors press CTRL + SPACE button toghether
Now We Can able to See which are and all the types of constructors available in StringBuilder.








Saturday, September 15, 2012

How to Convert Ascii to Character in Java ?

        (a)  
        For Example for Converting ascii to character in Java use the following code
        char characterValue = (char)asciiValue;
       
        class CharacterValue
        {
               public static void main(String[] args) {
               int asciiValue='100';
               char characterValue = (char)asciiValue;
               /*
                  The Above Statement Shows that the ascii value will be converted into its
                  Corresponding Character Value and hence the char character = (char)ascii;
                  will print out the value as 'd'
              */
               System.out.println("CharacterValue for ascii 100 is : " + characterValue);
               }
        }
       
        Answer : 
        CharacterValue for ascii 100 is : 'd'

        (b)
        For Example for Converting character to ascii in Java use the following code
        int asciiValue = (int)characterValue;
       
        class AsciiValue
        {
               public static void main(String[] args) {
               char characterValue='d';
               int asciiValue = (int)characterValue;
               /*
                  The Above Statement Shows that the character value will be converted into its
                  Corresponding Ascii Value and hence the int asciiValue = (int)characterValue;
                  will print out the value as '100'
              */
               System.out.println("AsciiValue for character 'd' is : " + asciiValue);
               }
        }
       
        Answer : 
        AsciiValue for character 'd' is :100

Saturday, September 8, 2012

Sample code for Sorting String in ascending order

Try out these Programs

(a)
package pack1;
import java.util.*;
import java.lang.*;
import pack1.Orderly;
public class Example{
   public static void main(String args[]){
        String name = "";
        ArrayList list=new ArrayList();
        Orderly orderly = new Orderly ();
        try
        {
              list=orderly.displayRecordNew();
              Collections.sort(list);
              /*
                 Sorts the array list
                 If We have to Sort the Name in Descending Order then we have to uncomment the 
                 below commented lines.
                 Comparator r = Collections.reverseOrder();
                 Collections.sort(list,r);
              */
              Iterator l1 = list.iterator();        
              while(l1.hasNext()){
                  orderly  = (Orderly)l1.next();
                  name = orderly.getOrderlyName();
                  System.out.println("Name is " + name);
              }
        }
        catch(Exception e)
        {
        }
   }
}

(b)
package pack1;
import java.util.*;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
class Orderly implements Comparable<Orderly>{
    public String nameDesig = "a";
    private String name;
    public void setOrderlyName(String name){
        this.name = name;
    }
    public String getOrderlyName(){
        return name;
    }
    //Overriding the compareTo method
    public int compareTo(Orderly o){
        return (this.name).compareTo(o.name);
    }       
    public ArrayList displayRecordNew() throws Exception
    {
        File file = new File("C://Users//Radio1//Desktop//Names.txt");
        FileInputStream fis = null;
        StringTokenizer st;

        ArrayList showRecord=null;           
        try {
            showRecord=new ArrayList();               
            fis = new FileInputStream(file);
            /*
               FileInputReader since we have to sort out the names in ascending order from the file                        Names.txt
            */
            BufferedReader d = new BufferedReader(new InputStreamReader(fis));
            String readingFromFile = "";
            String intoArrayList = "";
            while((readingFromFile = d.readLine()) != null)
            {
                /*
                   Now We are using StringTokenizer to read the names from the FileList since  the Names  are separated using comma in the File and the resultant one by one we will store it in the ArrayList which we will sort it out using Collections.sort(list); 

                   Since this class (Orderly) is imported in the class Example it will automatically sort out the List  and we will get the Names in Ascending Order on further iteration of the List
                */
                st = new StringTokenizer(readingFromFile, ",");
                while (st.hasMoreTokens())
                {
                    Orderly orderly=new Orderly();
                    intoArrayList = st.nextToken();
                    orderly.setOrderlyName(intoArrayList);
                    showRecord.add(orderly);
                }
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return showRecord;
    }
}

(c)Names.txt will have the following contents
Seshadri,Lakshmi,Padma,Balaji,Koushick,Hari,Sudarshan,Anirudh,Sriram,Rajagopalan,Mahesh,Zombia,Karthick,Raghavendra,Mahati,Kamran

(d)Now on running the Example.java file we get the following as Result(Sorted Out)
Name is Anirudh
Name is Balaji
Name is Hari
Name is Kamran
Name is Karthick
Name is Koushick
Name is Lakshmi
Name is Mahati
Name is Mahesh
Name is Padma
Name is Raghavendra
Name is Rajagopalan
Name is Seshadri
Name is Sriram
Name is Sudarshan
Name is Zombia