ArrayList in java example using iterator


import java.util.ArrayList;
import java.util.Iterator;

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

        ArrayList al = new ArrayList();
        al.add(“Santosh”);
        al.add(“Nag”);
        al.add(“Rajesh”);
        al.add(“Santosh”);
        Iterator it = al.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

Object Class


java.lang
Class Object

java.lang.Object

  *public class Object:

  • Class Object is the root of the class hierarchy.

  • Every class has Object as a superclass.

Version:

JDK1.0

*Methods of Oject Class:

           Object Class consists of following 11 methods

1. public boolean equals(Object obj)

    Indicates whether some other object is “equal to” this one.

  2. public int hashCode()

    Returns a hash code value for the object

  3. protected Object clone()        Throws CloneNotSupportedException

Creates and returns a copy of this object.

  4. public String toString()

   Returns a string representation of the object

   5. public final Class getClass()

     Returns the runtime class of this Object.

   6. protected void finalize()throws  Throwable

             Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

7. public final void wait()

                throws InterruptedException

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object

  8. public final void wait(long timeout)

                throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

  9. public final void wait(long timeout)

                throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

 10.public final void notify()

    Wakes up a single thread that is waiting on this object’s monitor.

  11. public final void notifyAll()

    Wakes up all threads that are waiting on this object’s monitor.

 

 

Explain about Java.util.ArrayList class?


java.util
Class ArrayList<E>

java.lang.Object

  java.util.AbstractCollection<E>

      java.util.AbstractList<E>

          java.util.ArrayList<E>

 All Implemented Interfaces:

 Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

public class ArrayList<E>

 extends AbstractList<E>

 implements List<E>, RandomAccess, Cloneable, Serializable

 Version:

   1.2

======================================================

Constructors of java.util.ArrayList class:

   1.ArrayList l = new ArrayList();

 Creates an empty ArrayList Object with default initial capacity is 10.

    Once ArrayList reaches its Max. Capacity then new ArrayList Object will be created with

      New Capacity = currentCapacity*(3/2)+1

     2. ArrayList l = new ArrayList( int initialcapacity);

                Creates an empty ArrayList Object with the specified initial capacity.

    3.ArrayList l = new ArrayList( Collection c);

                 Creates an equivalent ArrayList Object for the given Collection Object.

This constructor meant for interconversion between the Collection Object.

======================================================

Methods of java.util.ArrayList class :

    1.public int indexOf(Object o)

    2.public boolean addAll(Collection c)

     Throws:NullPointerException

    3.public void trimToSize()

   4. public void ensureCapacity(int    minCapacity)

  5.public int size()

  6.public boolean isEmpty()

  7.public boolean contains(Object o)

  8.public int lastIndexOf(Object o)

  9.public Object clone()

  10. public boolean add(E e)

  11.public void add(int index, E element)

     Throws:IndexOutOfBoundsException

  12. public Object[] toArray()

   13. public boolean remove(Object o)

  14.public void clear()

 15.public boolean addAll(int index, Collection c)

Throws:IndexOutOfBoundsExceptionNullPointerException

 16. public E remove(int index)

      Throws:IndexOutOfBoundsException

  17. public E get(int index)

      Throws:IndexOutOfBoundsException

 18. protected void removeRange(int fromIndex, int toIndex)

          Throws:IndexOutOfBoundsException

   19. public E set(int index, E element)

            Throws:IndexOutOfBoundsException

  20. public T[] toArray(T[] a)

 Throws:ArrayStoreExceptionNullPointerException

 ==================================

 Description of java.util.ArrayList class :

1.   ArrayList Object is dynamically resizable.

2.   ArrayList Object maintains the duplicate elements.

3.   ArrayList Object maintains in the list Insertion order.

4.   ArrayList Object also accepts the heterogeneous elements.

5.   ArrayList Object also maintains the elements based on index.

6.   ArrayList Object accepts null pointer constant any number of times.

Advantages:

      1. ArrayList Objects are Serializable Objects why because ArrayList       implements Serializable interface.

      2. ArrayList Objects are Cloneable Objects why because ArrayList       implements Cloneable interface.

     3. ArrayList also implements RandomAccess interface for frequent retrieval operations.

Disadvantages:

    1. ArrayList is not best suitable for frequent insertion and deletion operations as it requires internally lot of shifting operations.

 Example:

//ArraylistDemo.java

import java.util.*;

public class ArraylistDemo{

 public static void main(String[] args){

ArrayList l = new ArrayList();

                  l.add(“A”);

                  l.add(10);

                  l.add(“A”);

                  l.add(null);

        System.out.println(l);

                  l.remove(2);

        System.out.println(l);

                  l.add(2,“M”);

                  l.add(“N”);

      System.out.println(l);

}//main

}//class

javac ArrayListDemo.java

java ArraylistDemo

OUTPUT:

[A,10,A,null]

[A,10,null]

[A,10,M,null]

[A,10,M,null,N]

NOTE: Here toString() method provides like [].

       ArrayList and Vector Classes implements RandomAccess interface so that we can access any random element with same speed.

 

Explain about String Class and its constructors with examples?


java.lang Class String

 java.lang.Object

          java.lang.String

 All Implemented Interfaces:

SerializableCharSequence,Comparable<String>.

 ¤ public final class String

extends Object  

implements Serializable, Comparable<String>, CharSequence

Since:

JDK1.0

Definition:

        In general String can be defined as it is a sequence of characters. Strings are constant; their values cannot changed in the same memory after they are created, so String is defined as it is an immutable sequence of characters.

¤What are the possible ways to create String Object?

              String object can be created in two ways

                    1. By assigning String literal directly

                    2.By using any one of the String class constructors

======================================================

 Constructors of  String Class:

             String class supports several constructors.

      1.String s = new String();

            To create an empty String object, no null String Object.

      2.String s = new String(String literal);

            To create an equivalent String Object for the given String literal on       the heap.

      3.String s = new String(StringBuffer sb)

            To create String Object with the StringBuffer Object value.

     4.String s = new String(StringBuilder sb)

            To create String Object with the StringBuilder Object value.

            Version:1.5

     5.String s = new String( Char [] ch)

          To create an equivalent String Object for the given Char[].

Example:

      public class SringDemo{

      public static void main(String[] args){

       Char[] ch =  {‘a’,’b’,’c’,’d’};

        String s = new String(ch);

        System.out.println(s);

       }//main

}//class

OutPut:abcd

6.String s = new String( byte[] b)

              To create String Object with the given byte array values.

Example:

      public class SringDemo{

      public static void main(String[] args){

       byte[] b =  {100,101,102,103 };

        String s = new String(b);

        System.out.println(s);

       }//main

}//class

OutPut : defg

7. String s = new String( Char [] ch, int offset, int count)

            To create String Object with the given char array values starts with offset by including with the given count of characters

 Throws:

IndexOutOfBoundsException

 Example:

       public class SringDemo{

         public static void main(String[] args){

       Char[] ch =  {‘a’,’b’,’c’,’d’,’e’,’f’};

        String s = new String(ch,2,3);

        System.out.println(s);

       }//main

}//class

Output:cde

 8. String s = new String( byte[] b, int offset, int count)

            To create String Object with the given byte array values starts with offset by including with the given count of bytes

 Throws:

IndexOutOfBoundsException

Version:

JDK1.1

 Example:

      public class SringDemo{

      public static void main(String[] args){

       byte[] b =  {65,66,67,68,69,70};

        String s = new String(s);

        System.out.println(s);

        String s1 = new String(b,2,3);

        System.out.println(s1);

     }//main

}//class

   OutPut: ABCDEF

                 CDE

======================================================

String Class Methods:

o charAt:

       1.public char charAt(int index)  

  • Returns the char value at the specified index. An index ranges from 0 to length() – 1.

  • The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

  • If the char value specified by the index is a surrogate, the surrogate value is returned.

Specified by:

Parameters:

  • index – the index of the char value.

Returns:

  • the char value at the specified index of this string. The first char value is at index 0.

Throws: IndexOutOfBoundsException

  • If the index argument is negative or not less than the length of this string.


 

Explain Throwable class in brief?


Throwable class is present in java.lang package.

Syntax:

public class Throwable

extends Object

implements Serializable

Throwable class is direct child class of Object class.

Throwable class extends Object class and implements Serializable interface.

Throwable class subclasses are Error class and Exception class.

Throwable class Constructors:

1.      public Throwable()

2.      public Throwable(String msg)

3.      public Throwable(String msg, Throwable cause)

4.      public Throwable(Throwable cause)

5.      protected Throwable(String message, Throwable cause,

                                                     boolean enableSuppression,

                                                     boolean writableStackTrace)

Throwable class Methods:

1.      public String getMessage()

2.      public String toString()

3.      public void printStackTrace()

4.      public String getLocalizedMessage()