Sunday, July 31, 2011

Java Questions - 28

What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
    // Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) {
    // Synchronized code here.
  }
}

Insert all elements of other Collection to Specified Index of Java ArrayList

    package org.best.examples;

    /*
      Insert all elements of other Collection to Specified Index of Java ArrayList Example
      This Java Example shows how to insert all elements of other Collection object
      at specified index of Java ArrayList object using addAll method.
    */
    
    import java.util.ArrayList;
    import java.util.Vector;
    
    public class InsertAllElementsOfOtherCollectionToArrayListExample {
    
    public static void main(String[] args) {
    
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
    
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    
    //create a new Vector object
    Vector v = new Vector();
    v.add("4");
    v.add("5");
    
    /*
      To insert all elements of another Collection to sepcified index of ArrayList
      use
      boolean addAll(int index, Collection c) method.
      It returns true if the ArrayList was changed by the method call.
      */
    
    //insert all elements of Vector to ArrayList at index 1
    arrayList.addAll(1,v);
    
    //display elements of ArrayList
    System.out.println("After inserting all elements of Vector at index 1,
    ArrayList contains..");
    for(int i=0; i<arrayList.size(); i++)
    System.out.println(arrayList.get(i));
    
    }
    }
    
    /*
    Output would be
    After inserting all elements of Vector at index 1, ArrayList contains..
    1
    4
    5
    2
    3
    */

Saturday, July 30, 2011

Java Questions - 27

How can a subclass call a method or a constructor defined in a superclass?

Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.


Get Sub List of Java ArrayList

    package org.best.examples;

      /*
      Get Sub List of Java ArrayList Example
      This Java Example shows how to get sub list of java ArrayList using subList
      method by providing start and end index.
    */
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class GetSubListOfJavaArrayListExample {
    
    public static void main(String[] args) {
    
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
    
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    
    /*
      To get a sub list of Java ArrayList use
      List subList(int startIndex, int endIndex) method.
      This method returns an object of type List containing elements from
      startIndex to endIndex - 1.
      */
    
    List lst = arrayList.subList(1,3);
    
    //display elements of sub list.
    System.out.println("Sub list contains : ");
    for(int i=0; i< lst.size() ; i++)
    System.out.println(lst.get(i));
    
    /*
      Sub List returned by subList method is backed by original Arraylist. So any
      changes made to sub list will also be REFLECTED in the original Arraylist.
      */
    //remove one element from sub list
    Object obj = lst.remove(0);
    System.out.println(obj + " is removed from sub list");
    
    //print original ArrayList
    System.out.println("After removing " + obj + " from sub list, original ArrayList contains : ");
    for(int i=0; i< arrayList.size() ; i++)
    System.out.println(arrayList.get(i));
    
    }
    
    }
    /*
    Output would be
    Sub list contains :
    2
    3
    2 is removed from sub list
    After removing 2 from sub list original ArrayList contains :
    1
    3
    4
    5
    */

Friday, July 29, 2011

Get Size of Java ArrayList and loop through elements

    package org.best.examples;

        /*
      Get Size of Java ArrayList and loop through elements Example
      This Java Example shows how to get size or number of elements currently
      stored in ArrayList. It also shows how to loop through element of it.
    */
    
    import java.util.ArrayList;
    
    public class GetSizeOfArrayListExample {
    
    public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
    
    //Add elements to Arraylist using
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    
    //To get size of Java ArrayList use int size() method
    int totalElements = arrayList.size();
    
    System.out.println("ArrayList contains...");
    //loop through it
    for(int index=0; index < totalElements; index++)
    System.out.println(arrayList.get(index));
    
    }
    }
    
    /*
    Output would be
    ArrayList contains...
    1
    2
    3
    */

Java Questions - 26

When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching thread.

Thursday, July 28, 2011

Copy all elements of Java ArrayList to an Object Array

    package org.best.examples;

    /*
      Copy all elements of Java ArrayList to an Object Array Example
      This Java Example shows how to copy all elements of Java ArrayList object to an
      array of Objects using toArray method.
    */
    
    import java.util.ArrayList;
    
    public class CopyElementsOfArrayListToArrayExample {
    
    public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
    
    //Add elements to ArrayList
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    
    /*
      To copy all elements of java ArrayList object into array use
      Object[] toArray() method.
      */
    
    Object[] objArray = arrayList.toArray();
    
    //display contents of Object array
    System.out.println("ArrayList elements are copied into an Array.
    Now Array Contains..");
    for(int index=0; index < objArray.length ; index++)
    System.out.println(objArray[index]);
    }
    }
    
    /*
    Output would be
    ArrayList elements are copied into an Array. Now Array Contains..
    1
    2
    3
    4
    5
    */

Java Questions - 25

You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?

ArrayList

Wednesday, July 27, 2011

Append all elements of other Collection to Java ArrayList

    package org.best.examples;

        /*
      Append all elements of other Collection to Java ArrayList Example
      This Java Example shows how to append all elements of other Collection object
      at the end of Java ArrayList object using addAll method. This program shows
      how to append all elements of Java Vector to Java ArrayList object.
    */
    
    import java.util.ArrayList;
    import java.util.Vector;
    
    public class AppendAllElementsOfOtherCollectionToArrayListExample {
    
    public static void main(String[] args) {
    
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
    
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    
    //create a new Vector object
    Vector v = new Vector();
    v.add("4");
    v.add("5");
    
    /*
      To append all elements of another Collection to ArrayList use
      boolean addAll(Collection c) method.
      It returns true if the ArrayList was changed by the method call.
      */
    
    //append all elements of Vector to ArrayList
    arrayList.addAll(v);
    
    //display elements of ArrayList
    System.out.println("After appending all elements of Vector,
    ArrayList contains..");
    for(int i=0; i<arrayList.size(); i++)
    System.out.println(arrayList.get(i));
    
    }
    }
    
    /*
    Output would be
    After appending all elements of Vector, ArrayList contains..
    1
    2
    3
    4
    5
    */

Java Questions - 24

Name the containers which uses Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

Tuesday, July 26, 2011

Add an element to specified index of Java ArrayList

    package org.best.examples;

    /*
      Add an element to specified index of Java ArrayList Example
      This Java Example shows how to add an element at specified index of java
      ArrayList object using add method.
    */
    
    import java.util.ArrayList;
    
    public class AddElementToSpecifiedIndexArrayListExample {
    
    public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
    
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    
    /*
      To add an element at the specified index of ArrayList use
      void add(int index, Object obj) method.
      This method inserts the specified element at the specified index in the
      ArrayList.
      */
    arrayList.add(1,"INSERTED ELEMENT");
    
    /*
      Please note that add method DOES NOT overwrites the element previously
      at the specified index in the list. It shifts the elements to right side
      and increasing the list size by 1.
      */
    
    System.out.println("ArrayList contains...");
    //display elements of ArrayList
    for(int index=0; index < arrayList.size(); index++)
    System.out.println(arrayList.get(index));
    
    }
    }
    
    /*
    Output would be
    ArrayList contains...
    1
    INSERTED ELEMENT
    2
    3
    */

ArrayList

Java ArrayList is a resizable array which implements List interface. ArrayList provides all operation defined by List interface. Internally ArrayList uses an array to store its elements. ArrayList provides additional methods to manipulate the array that actually stores the elements. ArrayList is equivalent to Vector, but ArrayList is not synchronized.

Java ArrayList Capacity

Capacity of an ArrayList is the size of the array used to store the list elements. It grows automatically as we add elements to it. Every time this happens, the internal array has to be reallocated. This increases the load.
We can set the initial capacity of the ArrayList using following method.
ArrayList arrayList = new ArrayList();
arrayList.ensureCapacity(100);

Java ArrayList Iterators

Java ArrayList provides two types of Iterators.
1) Iterator
2) ListIterator

                  Iterator iterator = arrayList.iterator();
Returns object of Iterator.
                  ListIterator listIterator = arrayList.listIterator();
Returns object of ListIterator.
                  ListIterator listIterator = arrayList.listIterator(int startIndex);
Returns object of ListIterator. The first next() method call on this ListIterator object will return the element at the specified index passed to get the ListIterator object.

Iterators returned by these methods are fail-fast. That means if the list is modified after getting the Iterator by using some other means rather than Iterators own add or remove method, Iterator will throw ConcurrentModificationException.

ArrayList Constructors

1) ArrayList()
Creates an empty ArrayList.
For example,
ArrayList arrayList = new ArrayList();

2) ArrayList(int capacity)
Creates an ArrayList with specified initial capacity.
For example,
ArrayList arrayList = new ArrayList(10);

3) ArrayList(Collection c)
Creates an ArrayList containing elements of the collection specified.

For example,
ArrayList arrayList = new ArrayList(myCollection);

Where myCollection is an object of the type Collection. This creates an ArrayList of elements contained in the myCollection, in the order returned by the myCollection’s Iterator.

Java Questions - 23

Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

Monday, July 25, 2011

Hash Set Example

    package org.best.example;

    /*
      Simple Java HashSet example
      This simple Java Example shows how to use Java HashSet. It also describes how to
      add something to HashSet object using add method.
    */
   
    import java.util.HashSet;
   
    public class SimpleHashSetExample {
   
    public static void main(String[] args) {
    //create object of HashSet
    HashSet hSet = new HashSet();
   
    /*
      Add an Object to HashSet using
      boolean add(Object obj) method of Java HashSet class.
      This method adds an element to HashSet if it is not already present in HashSet.
      It returns true if the element was added to HashSet, false otherwise.
      */
   
    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));
   
    /*
      Please note that add method accepts Objects. Java Primitive values CAN NOT
      be added directly to HashSet. It must be converted to corrosponding
      wrapper class first.
      */
   
    System.out.println("HashSet contains.." + hSet);
    }
    }
   
    /*
    Output of the program would be
    HashSet contains..[3, 2, 1]
    */

Java Questions - 22

What's the difference between J2SDK 1.5 and J2SDK 5.0?

There's no difference, Sun Microsystems just re-branded this version.

Sunday, July 24, 2011

Get Head Set from Java TreeSet

    /*
      Get Head Set from Java TreeSet example
      This Java Example shows how to get the portion of TreeSet containing the values
      less than the specified value using headSet method of Java TreeSet class.
    */
    package org.best.example;
    import java.util.SortedSet;
    import java.util.TreeSet;
    
    public class GetHeadSetFromTreeSetExample {
    
    public static void main(String[] args) {
    
    //create TreeSet object
    TreeSet tSet = new TreeSet();
    
    //add elements to TreeSet
    tSet.add("1");
    tSet.add("3");
    tSet.add("2");
    tSet.add("5");
    tSet.add("4");
    
    /*
      To get a Head Set from Java TreeSet use,
      SortedSet headSet(Object fromElement) method of Java TreeSet class.
    
      This method returns the portion of TreeSet containing elements less than
      fromElement.
    
      Please note that, the SortedSet returned by this method is backed by
      the original TreeSet. So any changes made to SortedSet will be
      reflected back to original TreeSet.
      */
    
    SortedSet sortedSet = tSet.headSet("3");
    
    System.out.println("Head Set Contains : " + sortedSet);
    
    }
    }
    
    /*
    Output would be
    Head Set Contains : [1, 2]
    */

Java Questions - 21

If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.javIn this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

Saturday, July 23, 2011

Copy all elements of Java TreeSet to an Object Array

    /*
      Copy all elements of Java TreeSet to an Object Array Example
      This Java Example shows how to copy all elements of Java TreeSet object to an
      array of Objects using toArray method.
    */
    
    package org.best.example;
    import java.util.TreeSet;
    
    public class CopyElementsOfTreeSetToArrayExample {
    
    public static void main(String[] args) {
    
    //create object of TreeSet
    TreeSet tSet = new TreeSet();
    
    //add elements to TreeSet object
    tSet.add(new Integer("1"));
    tSet.add(new Integer("2"));
    tSet.add(new Integer("3"));
    
    /*
      To copy all elements of java TreeSet object into array use
      Object[] toArray() method.
      */
    
    Object[] objArray = tSet.toArray();
    
    //display contents of Object array
    System.out.println("TreeSet elements are copied into an Array.
    Now Array Contains..");
    for(int index=0; index < objArray.length ; index++)
    System.out.println(objArray[index]);
    }
    }
    
    /*
    Output would be
    TreeSet elements are copied into an Array. Now Array Contains..
    1
    2
    3
    */

Java Questions - 20

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically. Can you write a Java class that could be used both as an applet as well as an application?

Yes. Add a main() method to the applet.

Friday, July 22, 2011

Java Questions - 19

How do you know if an explicit object casting is needed?

If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;