Tuesday, September 27, 2011

Introduction to Advance Java : An starter for Interviewes



Introduction:

This post will introduce the concept of advance java classes. This post introduces several java classes which are highly required during coding in JAVA programming language. This is the first part of “Introduction to Advance JAVA”. This post will discuss the classes, its details and a sample program that how to use these classes in JAVA code.

In this post we are talking about Arrays, File Reader and Writer and a map interface classes. In coming post we will be discussing several other useful classes like database connectivity, transaction management classes and other important things.

   

1.     Arrays Class
Public class Arrays extends Object

This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The methods in this class all throw a NullPointerException if the specified array reference is null, except where noted.

The documentation for the methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementers should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort (Object []) does not have to be a merge sort, but it does have to be stable.) The following function definition searches the specified array of bytes for the specified value using the binary search algorithm.

static int binarySearch(byte[] a, byte key)


The following program illustrates Array Class implementation.

import java.util.Arrays;
public class ArrayInt {
       public static void main(String[] args) {
int[] a1 = new int[]{4,3,5};
int[] a2 = new int[]{1,3,8,4,5,7};
             
boolean check=Arrays.equals(a1, a2);
System.out.println(check);
System.out.println("The Contents of the array are as follows");
for(float i:a1){
System.out.println(" ====== "+i);
}
     
Arrays.sort(a2);
for(float i:a2){
                                    }
int index=Arrays.binarySearch(a2,3);
System.out.println("The Index of the given names"+index);

int index1=Arrays.binarySearch(a2,9);
System.out.println("Search is not Successful"+index1);

Arrays.fill(a2, 4, 6,9);

for(int i:a1){
                System.out.println(" ##### " + i);}
}





2.     File Reader and File Writer

FileInputstream:

This class is a subclass of Inputstream class that reads bytes from a specified file name. The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throwsFileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as below. Sample function signature is as below which should be used during coding

FileInputstream (File filename);


FileOutputStream:

This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriterBufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as below. Sample function signature is as below which should be used during coding

FileOutputStream (File filename);


The following program illustrates Reading data from the File and writes data into the file.

File Read Program
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
            FileReader fr = new FileReader("out.txt");
            BufferedReader br = new BufferedReader(fr);
            String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
   fr.close();
}
}



File Write Program
package AdvancedIO;
import java.io.*;
class FileWrite
{
   public static void main(String args[])
  {
      try{
        FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("Hello Java");
        out.close();
        }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Relevant AD
This ad may be helpful, if relevant to your search.


3.     Map Interface

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets. The following constructors are defined:

HashMap( )
HashMap(Map
 m)
HashMap(int
 capacity)
HashMap(int
 capacity, float fillRatio)

HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator. The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapExample {
    public static void main(String[] args) {
        Map<Object,String> mp=new HashMap<Object, String>();
        mp.put(new Integer(2), "100");
        mp.put(new Integer(1), "200");
        mp.put(new Integer(3), "300");
        mp.put(new Integer(4), "400");
        mp.put(new Integer(7), "777");
        mp.put(new Integer(6), "666");
        mp.put(new Integer(5), "333");
       
        Set s=mp.entrySet();
        Iterator it=s.iterator();

        while(it.hasNext())
        {
           Map.Entry m =(Map.Entry)it.next();

            // getKey is used to get key of Map
            int key=(Integer)m.getKey();

            // getValue is used to get value of key in Map
            String value=(String)m.getValue();

                     System.out.println("Key :"+key+"  Value :"+value);
        }
    }
}