Friday, 30 December 2016

Breadth-First Search/Level order Traversal in a Binary Tree

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package levelordertraversalbfs;

/* Write a program for Level order traversal in Binary tree

Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root and explores the neighbor nodes first, before moving to the next level neighbors.

Here we are using Linked List queue to Store tree node for Level order traversing

*/

import java.util.Scanner;

/**
 *
 * @author shabhatn
 */

class LLNode
{
    LLNode link;
    Node data;
   
    public LLNode()
    {
        link = null;
        data = null;
    }
    public LLNode(Node data , LLNode n)
    {
        this.data = data;
        link = n;
    }

    public LLNode getLink() {
        return link;
    }

    public void setLink(LLNode link) {
        this.link = link;
    }

    public Node getData() {
        return data;
    }

    public void setData(Node data) {
        this.data = data;
    }
   
}

class LL_Queue
{
    LLNode front , rear;
   
    int size;
   
    public LL_Queue()
    {
        front =null;
        rear =null;
        size = 0;
    }
    public int getSize()
    {
        return size;
    }
    public boolean isEmpty()
    {
        return front==null;
    }
   
    public void enqueue(Node data)
    {
        LLNode nptr = new LLNode(data,null);
       
        if(front==null)
        {
            front = nptr;
            rear = nptr;
           
        }
        else
        {
            rear.setLink(nptr);
            rear = nptr;
           
        }
        size++;
       
    }
    public Node dequeue()
    {
        if(isEmpty())
        {
         return null;
        }
        else
        {
            Node d = front.getData();
            front = front.getLink();
            return d;
        }
       
    }
}

class Node
{
    Node Left , Right;
    int data;
   
    public Node()
    {
        Left = null;
        Right = null;
        data = 0;
    }
    public Node(int d)
    {
        Left = null;
        Right = null;
        data = d;
    }

    public Node getLeft() {
        return Left;
    }

    public void setLeft(Node Left) {
        this.Left = Left;
    }

    public Node getRight() {
        return Right;
    }

    public void setRight(Node Right) {
        this.Right = Right;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }
   
}

class Binary_tree
{
    Node root;
   
    public Binary_tree()
    {
        root = null;
    }
    public boolean isEmpty()
    {
        return root ==null;
    }
    public void insert(int data)
    {
        root = insert_tree(root,data);
    }
    public Node insert_tree(Node node, int data)
    {
        if(node==null)
        {
            node  = new Node(data);
        }
        else
        {
            if(node.getLeft()==null)
            {
                node.Left = insert_tree(node.Left,data);
            }
            else
            {
                node.Right = insert_tree(node.Right,data);
            }
        }
        return node;
    }
   
    public void Level_order()
    {
        Level_order_traversal(root);
    }
    public void Level_order_traversal(Node root)
    {
        Node temproot;
        LL_Queue lq = new LL_Queue();
        if(root==null)
        {
            System.out.print("No data");
        }
        else
        {
        lq.enqueue(root);
        while(!lq.isEmpty())
        {
            temproot = lq.dequeue();
            System.out.print("-->"+temproot.getData());
            if(temproot.getLeft()!=null)
            {
                lq.enqueue(temproot.getLeft());
            }
            if(temproot.getRight()!=null)
            {
                lq.enqueue(temproot.getRight());
            }
        }
        }
    }
   
}



public class LevelOrderTraversalBFS {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       
        Binary_tree bt = new Binary_tree();
       
        char ch;
        Scanner sc = new Scanner(System.in);
        do
        {
     
        System.out.println("enter data");
       
        int data = sc.nextInt();
       
        bt.insert(data);
        System.out.println("enter y to add more values to binary tree");
       
        ch = sc.next().charAt(0);
        }while(ch=='y'||ch=='Y');
        System.out.println();
        System.out.print("Level order traversal :->");
        bt.Level_order();
    }
   
}

Thursday, 29 December 2016

Linked List Queue Implementation

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.

Write a Program for Linked List queue Implementation

 */
package linkedlistqueue;

import java.util.Scanner;

/**
 *
 * @author shabhatn
 */

class Node
{
    Node link;
    int data;
   
    public  Node()
    {
        link = null;
        data = 0;
    }
    public Node(int data , Node n)
    {
        this.data = data;
        link = n;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }
   
}

class LL_queue
{
    Node front, rear;
    int size;
   
    public LL_queue()
    {
        front = rear = null;
        size = 0;
    }
    public int getSize()
    {
        return size;
    }
    public boolean isEmpty()
    {
        return front==null;
    }
    public void enqueue(int data)
    {
        Node nptr = new Node(data , null);
       
        if(front==null)
        {
            front = rear = nptr;
        }
        else
        {
            rear.setLink(nptr);
            rear = nptr;
        }
    }
   
    public void dequeue()
    {
        if(isEmpty())
        {
            System.out.println("No data present");
        }
        else
        {
            int data = front.getData();
            System.out.println("Dequeued data is :"+data);
            front  = front.getLink();
        }
    }
   
    public void display()
    {
        Node current = front;
        while(current.getLink()!=null)
        {
            System.out.println("->"+current.getData());
            current = current.getLink();
        }
        System.out.println("->"+current.getData());
    }
   
}



public class LinkedListQueue {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        Scanner sc = new Scanner(System.in);
        char choice;
        LL_queue lq = new LL_queue();
       
        do
        {
        System.out.println("Press 1 for enqueue");
        System.out.println("Press 2 for dequeue");
        System.out.println("Press 3 for display");
        int option = sc.nextInt();
        switch(option)
        {
            case 1:
                do
                {
                    System.out.println("Insert data:->");
                int data = sc.nextInt();
                lq.enqueue(data);
                System.out.println("If you want to insert more data press Y");
                choice = sc.next().charAt(0);
                }while(choice=='Y'||choice=='y');
                break;
                case 2:
                do
                {
               
                lq.dequeue();
                System.out.println("If you want to delete more data press Y");
                choice = sc.next().charAt(0);
                }while(choice=='Y'||choice=='y');
                break;
                case 3:
                lq.display();
                break;
                default:
                System.out.println(" no valid option -- exit");
                break;
       
           
        }
        System.out.println("Do you want to go to main menu");
        choice = sc.next().charAt(0);
        }while(choice=='Y'||choice=='y');
       
       
        // TODO code application logic here
    }
   
}

Wednesday, 28 December 2016

Dynamic Circular Array Queue

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

 /* Write a Program for dynamic circular array queue */
package dynamic_array_queue;

import java.util.Scanner;

/**
 *
 * @author shabhatn
 */

class dynamic_circular_queue
{
    int queue[];
    int size ;
    int front;
    int length;
    int rear;
   
    public dynamic_circular_queue(int size)
    {
        this.size = size;
        queue = new int[size];
        front = rear = -1;
        length =0;
    }
   
    public boolean isEmpty()
    {
        return front==-1;
    }
   
    public boolean isFull()
    {
        return (rear+1)%size==front;
    }
   
    public int getsize()
    {
        return length;
    }
   
    public void resize_array()
    {
        int old_array[];
        int oldsize = size;
        size = 2*size;
        old_array = queue;
        queue = new int[size];
       
        for(int i=0;i<old_array.length;i++)
        {
            queue[i] = old_array[i];
        }
       
        if(rear<front)
        {
            for(int i =0;i<front;i++)
            {
                queue[i+oldsize] = this.queue[i];
            }
            rear = rear+oldsize;
        }
    }
    public void enqueue(int data)
    {
        if(isFull())
        {
            resize_array();
            rear = (rear+1)%size;
            queue[rear] = data;
        }
        else
        {
            if(front==-1)
            {
                front=0;
                rear=0;
                queue[rear]=data;
            }
            else
            {
                rear = (rear+1)%size;
                queue[rear] = data;
               
                System.out.println(data);
            }
            length++;
        }
    }
   
    public void dequeue()
    {
        if(isEmpty())
        {
            System.out.println("Queue is empty");
        }
        else
        {
            int data = queue[front];
            System.out.println("Dequeued data--->" + data);
            length--;
           
            if(front==rear)
            {
                front =-1;
                rear = -1;
            }
            else
            {
                front = (front+1)%size;
            }
        }
    }
    public void display()
    {
        char choice;
        Scanner sc = new Scanner(System.in);
       
        char ch;
       
        do
        {
        System.out.println("press 1 to enqueue");
        System.out.println("press 2 to dequeue");
        System.out.println("press 3 to see all inserted data");
        int c = sc.nextInt();
        switch(c)
                {
        case 1:
        do
        {
            System.out.print("Insert data");
            int data = sc.nextInt();
            enqueue(data);
            System.out.print("Do you want to insert more data");
          choice = sc.next().charAt(0);
        }while(choice =='Y'||choice=='y');
        break;
        case 2:
        do
        {
            dequeue();
            System.out.print("Do you want to delete more data");
          choice = sc.next().charAt(0);
        }while(choice =='Y'||choice=='y');
        break;
        case 3:
            if(front>=0)
            {
               
        for(int i=front;i<queue.length && front!=-1;i++)
        {
            System.out.println("-->"+queue[i]);
        }
            }
           if(front>=0&&rear<=front)
            {
       for(int i=0;i<=rear;i++)
        {
            System.out.println("-->"+queue[i]);
        }
               
                }
           
        break;
        default:
        System.out.print("invalid input exit");
            break;
           
                }
        System.out.print("Do you want to go back to menu press y");
         ch = sc.next().charAt(0);
        }while(ch=='Y'||ch=='y');
    }
   
}

public class Dynamic_array_queue {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         System.out.print("Enter the  size of queue");
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        dynamic_circular_queue aq = new dynamic_circular_queue(size);
        aq.display();
    }
   
}

Circular Array Queue

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* Write a program for circular array queue */

package circular_array_queue;

import java.util.Scanner;

/**
 *
 * @author shabhatn
 */

class circular_queue
{
    int queue[];
    int size;
    int front;
    int rear;
    int length;
   
    public circular_queue(int size)
    {
        this.size = size;
        front = -1;
        rear = -1;
        length =0;
        queue = new int[size];
    }
   
    public boolean isEmpty()
    {
        return front==-1;
    }
   
    public boolean isFull()
    {
        return (rear+1)%size==front;
    }
    public void enqueue(int data)
    {
        if(isFull())
        {
            System.out.println("Buddy: you cannot insert mode data");
        }
        else
        {
            if(front==-1)
            {
                front =0;
                rear=0;
                queue[rear] = data;
            }
            else
            {
                rear = (rear+1)%size;
                queue[rear] = data;
            }
        }
         System.out.println("front value"+front+":rear value :"+rear);
        length++;
    }
   
    public int getSize()
    {
        return length;
    }
   
    public void dequeue()
    {
        if(isEmpty())
        {
            System.out.println("Queue is empty");
        }
        else
        {
            int data = queue[front];
            length--;
            System.out.println("Dequeued data--->" + data);
           
            if(front==rear)
            {
                front =-1;
                rear =-1;
            }
            else
            {
                front = (front+1)%size;
            }
        }
       
    }
    public void display()
    {
        char choice;
        Scanner sc = new Scanner(System.in);
       
        char ch;
       
        do
        {
        System.out.println("press 1 to enqueue");
        System.out.println("press 2 to dequeue");
        System.out.println("press 3 to see all inserted data");
        int c = sc.nextInt();
        switch(c)
                {
        case 1:
        do
        {
            System.out.print("Insert data");
            int data = sc.nextInt();
            enqueue(data);
            System.out.print("Do you want to insert more data");
          choice = sc.next().charAt(0);
        }while(choice =='Y'||choice=='y');
        break;
        case 2:
        do
        {
            dequeue();
            System.out.print("Do you want to delete more data");
          choice = sc.next().charAt(0);
        }while(choice =='Y'||choice=='y');
        break;
        case 3:
            if(front>=0)
            {
               
        for(int i=front;i<size && front!=-1;i++)
        {
            System.out.println("-->"+queue[i]);
        }
            }
           if(front>=0&&rear<=front)
            {
       for(int i=0;i<=rear;i++)
        {
            System.out.println("-->"+queue[i]);
        }
               
                }
           
        break;
        default:
        System.out.print("invalid input exit");
            break;
           
                }
        System.out.print("Do you want to go back to menu press y");
         ch = sc.next().charAt(0);
        }while(ch=='Y'||ch=='y');
    }
   
   
}
public class Circular_array_queue {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        System.out.print("Enter the  size of queue");
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        circular_queue aq = new circular_queue(size);
        aq.display();
        // TODO code application logic here
    }
   
}

Basic Array Queue

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

 /*Write a Program for Basic Array queue Implementation*/

package basic_queue_implementation;

import java.util.Scanner;

/**
 *
 * @author shabhatn
 */


class array_queue
{
    int size;
    int queue[];
    int front;
    int rear;
    int length;
    public array_queue(int size)
    {
        this.size = size;
        queue = new int[size];
        front = -1;
        rear = -1;
        length = -1;
    }
    public boolean isEmpty()
    {
        return front==-1;
    }
    public boolean isFull()
    {
        return front==0 && rear==size-1;
    }
    public int getSize()
    {
        return length;
    }
    public void enqueue(int data)
    {
        if(isFull())
        {
            System.out.println("queue is full: no space to enter");
        }
        else
        {
            if(front==-1)
            {
                front =0;
                rear =0;
                queue[rear] = data;
            }
            else
            {
                queue[++rear] = data;              
            }
            length++;
        }
       
    }
    public void dequeue()
    {
        int data;
        if(isEmpty())
        {
            System.out.println("No more Items to remove");          
        }
        else
        {
           data  = queue[front];
            length--;
            if(front==rear)
            {
                front =-1;
                rear=-1;
            }
            else
            {
                front++;
            }
            System.out.print("Element which has been removed is :->" + data);
        }
       
    }
    public void display()
    {
        char choice;
        Scanner sc = new Scanner(System.in);
       
        char ch;
       
        do
        {
        System.out.println("press 1 to enqueue");
        System.out.println("press 2 to dequeue");
        System.out.println("press 3 to see all inserted data");
        int c = sc.nextInt();
        switch(c)
                {
        case 1:
        do
        {
            System.out.print("Insert data");
            int data = sc.nextInt();
            enqueue(data);
            System.out.print("Do you want to insert more data");
          choice = sc.next().charAt(0);
        }while(choice =='Y'||choice=='y');
        break;
        case 2:
        do
        {
            dequeue();
            System.out.print("Do you want to delete more data");
          choice = sc.next().charAt(0);
        }while(choice =='Y'||choice=='y');
        break;
        case 3:
        for(int i=front;i<=rear && front!=-1;i++)
        {
            System.out.println("-->"+queue[i]);
        }
        break;
        default:
        System.out.print("invalid input exit");
            break;
           
                }
        System.out.print("Do you want to go back to menu press y");
         ch = sc.next().charAt(0);
        }while(ch=='Y'||ch=='y');
    }
   
}



public class Basic_queue_implementation {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.print("Enter the  size of queue");
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        array_queue aq = new array_queue(size);
        aq.display();
    }
   
}

Friday, 2 September 2016

BufferedInputStream

                                       BufferedInputStream

My previous articles over Byte and character streaming use unbuffered I/o . It means we are directly interacting with operating system for each read and write request and make the program less efficient since for each and every request lot of overhead is required which includes accessing of disk, network activity etc.
To reduce this efforts , Java provides a functionality ,Buffered Input and Output Stream will read and write data from a memory known as buffer .
In order to achieve this , here the unbuffered stream object is passed to the constructor for a buffered stream class.
Example to use buffered I/O:
inputStream = new BufferedInputStream(new FileInputStream("file.txt"));
outputStream = new BufferedOutputStream(new FileOutputStream("newfile.txt"));

BufferedInputStream

BufferedInputStream will read the data from a memory known as buffer

Methods available:

1)      int available() :This method returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

2)      void close() :This method closes this input stream and releases any system resources associated with the stream.

3)      void mark(int readlimit) :This method see the general contract of the mark method of InputStream.
ReadLimit -- number of bytes to be read before the mark position gets invalid

4)      boolean markSupported() :This method tests if this input stream supports the mark and reset methods.

5)      int read() :This method reads the next byte of data from the input stream.

6)      int read(byte[] b, int off, int len) :This method reads bytes from this byte-input stream into the specified byte array, starting at the given offset.

Here b refers to a byte array to be populated ,off means starts storing from the offset and len means number of bytes to read.
7)      void reset(): This method repositions this stream to the position at the time the mark method was last called on this input stream.

8)      long skip(long n) :This method skips over and discards n bytes of data from this input stream

Example 1:
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shashank
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\FailedRecord.log"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
                
            while((i=bis.read())!=-1)
            {
               
              System.out.print((char)i);
            }
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   
}






Example 2:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shabhatn
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        Boolean bool;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\mark.txt"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
                bool = bis.markSupported();
         System.out.println("Support for mark() and reset() : "+bool);
               
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
            bis.mark(1);//In other words, readlimit is a suggestion; the stream is free to under-promise and over-deliver
            System.out.println("Before mark" + (char)bis.read());
            bis.reset();
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
            bis.reset();
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
           
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   
}



Example 3:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shabhatn
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        Boolean bool;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\mark.txt"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
         byte [] arr = new byte[available];
        
         bis.read(arr,3,1);
        
         for(byte b:arr)
         {
             System.out.print((char)b);
         }
        
           
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   
}



Example 4:
*/
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shabhatn
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        Boolean bool;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\mark.txt"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
         byte [] arr = new byte[available];
        
       
         bis.skip(2);
        
        
             System.out.print((char)bis.read());
        
        
           
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   

}


DOM Parser

                                                       DOM Parser

DOM – Document Object Model
It Parse the document by loading the complete contents of the xml document along with its hierarchical tree in memory
We should use DOM parser when we need to learn about document Structure ,It provides an interface which enables the programs to access and update the style, structure and contents of XML documents. XML parsers that support the DOM will implements that interface.
XML File
<?xml version="1.0"?>
<company>
   <employee empid="393">
      <firstname>shashank</firstname>
      <lastname>bhatnagar</lastname>
      <nickname>shashank</nickname>
      <salary>85000</salary>
   </employee>
   <employee empid="493">
      <firstname>Raj</firstname>
      <lastname>Gupta</lastname>
      <nickname>Raju</nickname>
      <salary>95000</salary>
   </employee>
   <employee empid="593">
      <firstname>Deepak</firstname>
      <lastname>Kumar</lastname>
      <nickname>Deep</nickname>
      <salary>90000</salary>
   </employee>
</company>

Document Object Model Interfaces :
Node :  The base datatype of the model. 
  • In above example root node is company


Elements :  The vast majority of the objects .

ATTR :  It will represent an attribute of an element
  • In above example we will consider attribute as empid


Text :  The actual content of an element or an attribute

Document :  Represent entire XML document.

Common Document object model methods:
  1. Document.getDocumentElement() – it will return the root element of the document.
  2. Node.getFirstChild() – It will return the first child of a given Node.
  3. Node.getLastChild() – It will return the last child of a given Node.
  4. Node.getNextSibling() – It will return the next sibling of a given Node.
  5. Node.getPreviousSibling() – It will return the previous sibling of a given Node.
  6. Node.getAttribute(attrName) – it willl returns the attribute with the requested name for a given node.
Dom Parser steps :
Following are the steps used while parsing a document using DOM Parser.
1.   Import XML-related packages.
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
1.    Create a DocumentBuilder
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbbuilder = dbfactory.newDocumentBuilder();
2.    Create a Document from a file or stream
File inputFile = new File("D://Articles//XML//company.xml");
Document doc = DBbuilder.parse(inputFile);
doc.getDocumentElement().normalize();
Normalize method : Normalize the root element of the XML document. This ensures that all Text nodes under the root node are put into a "normal" form, which means that there are neither adjacent Text nodes nor empty Text nodes in the document.
3.    Extract the root element
Element root = doc.getDocumentElement();
System.out.println("Root Element is " +  root.getNodeName());
Examine attributes
//returns specific attribute ---- getAttribute("attributeName");
System.out.println("Emplyee id :-" + element.getAttribute("empid"));
//returns a Map (table) of names/values --- getAttributes();
4.    Examine sub-elements
            //returns a list of subelements of specified name

NodeList nList = doc.getElementsByTagName("employee");

System.out.println("Salary is :-" + element.getElementsByTagName("salary").item(0).getTextContent());
The node list keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated.
Note: In a node list, the nodes are returned in the order in which they are specified in the XML document.

getChildNodes(); -- //returns a list of all child nodes 

                Java Program to read above XML
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package domxmlparser;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author shashank
 */
public class Domxmlparser {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try
        {
            File inputFile = new File("D://Articles//XML//company.xml");
            DocumentBuilderFactory DBfactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder DBbuilder = DBfactory.newDocumentBuilder();
            Document doc = DBbuilder.parse(inputFile);
            Element root = doc.getDocumentElement();
            System.out.println("Root Element is " +  root.getNodeName());
             NodeList nList = doc.getElementsByTagName("employee");
             System.out.println("*******");
             for(int temp=0;temp<nList.getLength();temp++)
             {
                 //Get the current node
                 Node Currentnode = nList.item(temp);
                 System.out.println("Current Element is :" + Currentnode.getNodeName());
                 if(Currentnode.getNodeType()==Node.ELEMENT_NODE)/*getNodeType()A code representing the type of the underlying object, as defined above.*/
                 {
                     Element element = (Element)Currentnode;
System.out.println("Emplyee id :-" + element.getAttribute("empid"));
   
System.out.println("First name is :-" + element.getElementsByTagName("firstname").item(0).getTextContent());
                    
System.out.println("Last name is :-" + element.getElementsByTagName("lastname").item(0).getTextContent());
                     
System.out.println("Nick name is :-" + element.getElementsByTagName("nickname").item(0).getTextContent());
                     
System.out.println("Salary is :-" + element.getElementsByTagName("salary").item(0).getTextContent());
                 }
             }
        }catch(Exception e){e.printStackTrace();}
    }
   


}