Implementing a Stack in Java



In this section, you will learn how to implement a stack in Java. A Stack is like a bucket in which you can put elements one-by-one in sequence and retrieve elements from the bucket according to the sequence of the last entered element. Stack is a collection of data and follows the LIFO (Last in, first out) rule that mean you can insert the elements one-by-one in sequence and the last inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved to/from the stack through the push() and pop() method.

JAVA


This program implements a stack and follows the LIFO rule. It asks you for the number of elements which have to be entered in the stack and then it takes elements for insertion in the stack. All the elements present in the stack are shown from the last inserted element to the first inserted element.
Stack<Integer>(): 
Above constructor of the Stack class creates a empty stack which holds the integer type value which is mention with the creation of stack. The Stack class extends the Vector class and both classes are implemented from the java.util.*; package.
Stack.push(Object obj):
Above method is used to insert  or push the data or element in the stack. It takes an object like: data or elements and push its onto the top of the stack.
Stack.pop():
This is the method to removes the objects like: data or elements at the top positions of stack.
Here is the code of program:
import java.io.*;
import java.util.*;

public class StackImplement{
  Stack<Integer> stack;
  String str;
  int num, n;
  public static void main(String[] args){
  StackImplement q = new StackImplement();
  }
  public StackImplement(){
  try{
  stack = new Stack<Integer>();
  InputStreamReader ir = new InputStreamReader(System.in);
  BufferedReader bf = new BufferedReader(ir);
  System.out.print("Enter number of elements : ");
  str = bf.readLine();
  num = Integer.parseInt(str);
  for(int i = 1; i <= num; i++){
  System.out.print("Enter elements : ");
  str = bf.readLine();
  n = Integer.parseInt(str);
  stack.push(n);
  }
  }
  catch(IOException e){}
  System.out.print("Retrieved elements from the stack : ");
  while (!stack.empty()){
  System.out.print(stack.pop() + "  ");
  }
  }
}

Exceptions in Java
Posted on: October 15, 2008 at 12:00 AM
Exception is a run-time error which arises during the execution of java program. The term exception in java stands for an exceptional event.

Exceptions in Java

     
Introduction
Exception is a run-time error which arises during the execution of  java program. The  term exception in java stands  for an exceptional event. It can be defined as abnormal event that  arises during the execution and  normal flow of  program. The exceptional event can also be error in the program. 
Error in Java are of two type-
1.Compile-time Error-Compile -time Error are those error which occurs when you don't follow the Syntax of the code or do wrong in writing a code of the Programming language. The Compiler detect the Syntax  error in the code of the Programming language during its execution. For example in normal java coding ,you need your every statement to be terminated with semicolon(;).if you don't follow the rule, this will give you Compile-time error.
2.Run -time Error-Run-time error are the error which arises during the execution of a program. For example. The program runs out of the memory, result in Run-time error.

Why  Exceptions Occur-

An Exception is Run-time error that arises during the normal execution of Java program. In case of Run-time error, if you divide a number by zero or unable to open a file which does not exist, an exception is raised. In java exception are handled by Run-time System or user-defined code. A run-time error throws an exception.
Error handling plays a important role while developing an application. Following are the situation in which run-time error arises-
  1. Search a file which does not exist.
  2. Dividing a number by zero.
  3. Allocating Memory error.
  4. Problem in accessing Network Connectivity.

What is Exception Class-

Object Class is the base class of the exception hierarchy.. Object class is the super class of Throwable class.Throwable class is the super class of all the exceptional class and error class. In java you can throw exception Object which are derived from throwable class. The following Syntax for declaring a throwable class .
Throwable()
The Syntax represent a constructor of throwable class with no arguments.
In the same way we can declare a constructor of Throwable class with a userdefined Parameter.
Throwable(String Parameter)
Parameter can be message that may be userdefined included in Throwable class.

Exceptional Class-

  1. ClassNot Found Exception- Exception arises when a class is being reffered,but no such definition of class name is being found.
  2. Runtime Exception- handles the Exception arises during the runtime execution of the program.
  3. Illegal Access Exception-This Exception is thrown when method is not found.

Exceptional Hierarchy

Exception Hierarchy

Built in Exception-

The built-in exception in java are of following types classified on the basis of exception handled by the java compiler.
1.Checked Exception-These exception are the objects of the Exception class and its subclasses. It don't include the Run time Exception. These exception occurs due to invalid user input, problem in the network connectivity database connection). This also arises when we forget to import the packages. For Example java.sql.sqlexception,java.io.ioexception.The Exception problem can be overcome by implementing Try-Catch block which u see in Example in exception.
2.Unchecked Exception-These exception are the run-time errors that arises due to incorrect arguments passed to the public method written by the programmer. The Compiler never checks the Unchecked exception during the program compilation. For example, Dividing any number by zero is an unchecked exception.







Exceptional Example in Java
Posted on: October 15, 2008 at 12:00 AM
When an error occurs in a method, Java creates an object of the Exception method. On making an object of exception method, java send it to the program by throwing the object of exception method.

Exceptional Example in Java

     
When an error occurs in a method, Java creates an object of the Exception method. On making an object of exception method, java send it to the program by throwing the object of exception method. The Exception Object states the information of type of error and status of program during the exception Occurred.
Following are the Keyword used in implementing Exceptional-Handling-
  1. Try
  2. Catch
  3. Throw
  4. Throws
  5. Finally

How to implement Try-Catch Block

The Try Block contain a set of statements  that raise an exception-event within  the scope of  method.  If the exception arises in Try-Block. the appropriate handler with the Try Block proceed the exception.
As We Know, the Catch Block is used as exceptional-handler. The Exception that arises in the try block is handled by the Catch -Block. Each Try block preceded by one Catch block. The catch block specifies the type of exception need to catch.

Let Us Understand With Example

class Exception Unhandled
{
Public static void main(String args[])
{
int num1=0; 
int num2=8;
int num3=num2/num1;
System.out.println("The num3  =  " +num3);
}

The above code contain a class Exception Unhandled, Which on Compile gives us Arithmetical exception with no exception being handled .In this code the Java run-time a exception when a number is divided by zero. The output of the code shows that the exception thrown is the object of the subclass of exceptional class.

Output in Command Prompt


C:\Documents and Settings\Administrator>cd\

C:\>cd new folder\

C:\New Folder>javac ExceptionUnhandled.java

C:\New Folder>java ExceptionUnhandled
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionUnhandled.main(ExceptionUnhandled.java:7)

See How we going to implement Try-Catch Block in the above coding

Inorder to handle exception ,you need to implement the Try-Catch. If an exception arises within a try block, the appropriate exception handler  associated with try block handles the exception. The Catch block catches the object of the exception class as a parameter. Once the exception is caught in catch-block, the expression within the corresponding block is executed.
class ArithmeticException
{
public static void main(String args[])
{
int num1 = 0;
int num2=10;
int num3=0;
try
{
num3=num2/num1;
System.out.println("The result =" +num3);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero is done");
}
}
}

Output in Command Prompt
C:\java>javac ArithmeticExcep.java
C:\java>java ArithmeticExcep
Division by Zero is done

Using the Throw

The throw an exception can be explicitly used by using the keyword throw statement. For example you have entered wrong username and password in login form need to thrown an exception. The throw expression normally causes the code to stop or terminate during normal flow of java code.The Throw proceed the controls to nearest catch block. If  there is no catch block, then program terminates.
The Syntax used to declare the throw statement:
throw Throwable objt
The above Syntax ,Throwableobjt is an object of the class Throwable.The Throwableobj object is created  using the new operator.The compiler gives you an error if the throwableobjt does not belong to a valid class of Exception.
The following Example help you to understand  the throw -
class ThrowState
{
static void throwdemostration()
{
try
{
throw new IllegalStateException();
}
catch (NullPointerException objetB)
{
System.out.println("Not caught by catch block inside throwdemostration().");
}
}
public static void main(String args[])
{
try
{
throwdemostration();
}
catch(IllegalStateException objetC)
{
System.out.println("Exception Caught in:"+ objetC);
}
}
}

In the above given code, the new operator create an object of IllegalStateException.In the throwdemostration() method, an exception IllegalStateException is thrown. 
Output of the code in Command Prompt
C:\java>javac ThrowState.java
C:\java>java ThrowState
Exception Caught in:java.lang.IllegalStateException
C:\java>

Related Tags for Exceptional Example in Java:
javacexceptionerrorormformobjectiomethodformattypeuristatecreaterowstatusforprogramsendtoraminformationethrowitpeceinrminfostamjstatesesendmehrobjprowhensatkinfeaduexceptandstatccwingvassriringthavstatiinforminformatjeprndonogro
Number Format Exception
Posted on: October 22, 2008 at 12:00 AM
NumberFormatException is a subclass of the Runtime Exception class. A Number Format Exception occurs in the java code when a programmer tries to convert a String into a number.

Number Format Exception

     
NumberFormatException is a subclass of the Runtime Exception class.  A Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values. 

Understand Number Format Exception

The conversions are done by the functions Integer.parseInt and Integer.parseDouble.  Consider the function call Integer.parseInt(str) where str is a variable of type String. Suppose the value of str is  "60", then the function call  and convert the string into the int 60. However, if you give the value of str is "saurabh", the function call will fail to compile because "saurabh" is not a legal string representation of an int value. In such case,  NumberFormatException will occurs



public class ConvertStringToNumber
{

   public static void main(String[] args)
{

   try

{

   String s = "saurabh";

   int i = Integer.parseInt(s);

  // this line of code will never be reached//

   System.out.println("int value = " + i);
}

   catch (NumberFormatException nfe)

{

  nfe.printStackTrace();
}

}

}

Output on Command Prompt

 
C:\Documents and Settings\Administrator>cd\
 
C:\>cd saurabh\
 
C:\saurabh>javac ConvertStringToNumber.java
 
C:\saurabh>java  ConvertStringToNumber
java.lang.NumberFormatException: For input string: "saurabh"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at ConvertStringToNumber.main(ConvertStringToNumber.java:9)


Null Pointer Exception
Posted on: October 22, 2008 at 12:00 AM
Null pointer exceptions are the most common run time exception error arises during execution of java program.

Null Pointer Exception

     
 Null pointer exceptions are the most common run time  exception error arises during execution of java program. All values in Java programs are  references to objects, and all the value in variable are default one. Usually in the case of object references, it is null. Object references are same as pointers in C. In C pointer refers to the memory location of variable, while in a Java object reference refers to an object of known type, or be null. On making a call to a method  
y.method( );
there are two things that can be wrong, y refers to a different object or the reference of object y is null. Normally, the latter one is more common.

Rule for Debugging Null Pointer Exception

1.Point out the error in line of code.
2.Indicate the object or an array to declare null whose reference is not given.
3.Point out the reason for null.

Understand Null Pointer Exception

Suppose we have a class Wide.
class Wide
{
        private int value;
 
        public Wide (int v)
{
        value = v;
}
 
public int getValue()
{ 
       return value;
}
}
public class Large 
{
 
       private Wide theWide;
 
       public static void main(String[] args)
{
         Large inst = new Large();
        System.out.println(inst.theWide.getValue()); 
}
}

Obviously, when you  run this code, you  get a null pointer Exception  ,the Wide has default value of null, corresponding to the default value of  constructor for class large.
Output on Command Prompt
C:\saurabh>javac Large.java

C:\saurabh>java Large
Exception in thread "main" java.lang.NullPointerException
at Large.main(Large.java:27)
There are few things to be noticed here
1.You required to place appropriate constructor, which takes a wide as a parameter. 
   public large (Wide the Wide);
{
   the Wide= the Wide;

}

2.You required to change the main program as we are getting default constructor in it.

Large inst = new Large (new wide(50));
3. The Wide refers to the parameter  not to the instance variable. The only way to overcome this problem by using explicitly 'this' on the left hand side. 
    public large(Wide theWide) 
{
     this.theWide = theWide;
}

4. Again both side of the assignment refers to the same instance variable, because this. is redundant In order to demarcate you need to give new convention like underscore( _).
   public large(Wide _theWide)
{
    this.theWide = _the Wide;
}
A number of such small issue comes around during coding. You should checked the specific line  and check error if there might be any null references .

Index Out of Bound Exception
Posted on: October 22, 2008 at 12:00 AM
Index Out of Bound Exception are the Unchecked Exception that occurs at run-time errors. This arises because of invalid parameter passed to a method in a code.

Index Out of Bound Exception

     
Index Out of Bound Exception  are the Unchecked Exception that occurs at run-time errors. This arises because of  invalid parameter passed to a method in a code. The java Compiler does not check the error during the compilation of a program. Index Out of Bound Exception Occurs  when a programmer try to access an element of beyond the storage capacity of the index. 
Index Out of Bound Exception are further classified into two types-
1.Array Index Out of Bound Exception-These are the exception arises when a programmer tries to access an element beyond the capacity of  index of the array. This exception are seen at run-time rather than the compile time. This causes the program to crash at run-time.Inorder to overcome this problem, you write the exceptional -handler that process the program. Now place the code in try block that cause exception in program. If exception arises in try block, you pass the control to the specific catch block preceding try block If there is no catch block, the program will terminated.
How to Handle Array Out of Bound Exception
The below example define a class 'Example', that shows  out-of-bounds exception  when you attempt to access an  element of array with an illegal subscript. . To avoid this condition, you can write an exception handler that processes the exception and keeps your program running. Place the code that cause the exception in the try block. If there is an  exception  in the try block, transfer the control to the catch block. If there is no catch block the program will terminate.

  public class Example
   {
  public static void main( String args [] )
   {
   int value;
   try
  {
  int array[] = { 6, 16, 26,36,46,56,66,76 };
  int index = 8;
  value = array[ index ];
  System.out.println("Execution does not reach here if there is a invalid index.");  

  }

   catch( ArrayIndexOutOfBoundsException e ) 
  {
   System.out.println( "Valid indexes are 0, 1,2,3, 4,5,6 or 7" );
  }
   System.out.println( "End of program" );

   }

   }
Output on the Command Prompt.
C:\saurabh>javac Example.java

C:\saurabh>java Example
Valid indexes are 0, 1,2,3,4,5,6 or 7
End of program
2.String Index Out of Bound Exception- The String Index Out of Bound Exception is a subclass of Index out of Bound Exception. This exception is thrown when  a String  object detects an index  out-of-range index. Usually, An string object occurs out-of-range , when the index is less than zero, or greater than or equal to the length of the string.

How to declare String Index Out of Bound Exception

public String Index Out of Bound Exception()
The above Constructor creates an string Index Out of Bounds Exception with no message associated with it. 
public String Index Out of Bound Exception(int index)
The above  Constructor creates an StringIndexOutOfBoundsException  class with an argument indicates the illegal index associated with it.
Inherited Method
Some of  the Inherited Method
Method 
Inherited Method
Inherited Form
fillinStackTrace(  )
Throwable   Finalize ( )
Object
get Class 
Object  get Localized Message
Throwable
get message
Throwable  Hashcode
 Object
print stack trace ( )
 Throwable print stack trace ( )
Throwable

Example to show exception in java
Posted on: October 22, 2008 at 12:00 AM
Here we are describing the use of using exception class in java .Exceptions are the way in Java to indicate to a calling method that an abnormal condition has occurred.
Example to show exception in java
     
The code describe you  the use of exception class in java .Exceptions are the set of condition in Java to indicate to a calling method that occurred when an abnormal condition occurred. This tutorial describes  how to use exceptions appropriately in your programs.. The following steps involved in the program are given below:-
division(100, 0):- This method is declared for calculating the average of any two numbers. Here 100 is the numerator and 0 is the denominator.
System.out.println("Divide" + ex.getMessage() + "Exception" + "\n"  + "Please check the denominator");:- This return you an  exception message which will be displayed if an error occurs.  
Exceptionjava.java
Bottom of Form

Java Programming: Section 6.6

}
output of the program
Divide/ by zero Exception
Please check the denominator
Note:- if you will provide the value of denominator as 100 or any number except 1 it will not give any exceptions.
Example to show exception handling in java
Posted on: October 22, 2008 at 12:00 AM
Here we are describing the use of using exception class in java .Exceptions handling is the way in Java to handle run time errors and to indicate a calling method that an abnormal condition has occurred.
Example to show exception handling in java
     
In this Tutorial we want to describe you a code that show you the use of exception class in java .Exceptions handling is the key in Java, that handle run time errors and  indicate  a calling method whenever an abnormal condition occurred. This tutorial helps you in understanding  exception handling appropriately in  programs and designs. The steps involved in the program are described below:-
BufferedReader br = new BufferedReader(new FileReader("girish")):-Buffered reader is a class that reads text from a character-input stream. Here we are creating Buffered reader which generally read request made of a Reader.
String s = br.readLine():- This method read each line of the text and buffer request is stored in the string s.
System.out.println("File not found."):-This is the Exception message which is to be displayed if the particular file is not found.
SimpleExceptionHandling.java 
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class SimpleExceptionHandling {
    public static void main(String args[]){
        try{
         BufferedReader br = new BufferedReader(new FileReader("girish"));
         String s = br.readLine();
         System.out.println(s);
        }
       catch(FileNotFoundException fne)
        {
        System.out.println("File not found.");
        }
         }
        }
Output of the program
File MyFile.txt not found.


Example to show class exception in java
Posted on: October 22, 2008 at 12:00 AM
Here we are describing the example to show the use of class exception in java .Exceptions are the way in Java to indicate to a calling method that an abnormal condition has occurred.
Example to show class exception in java
     
In this Tutorial we are describing the example to show the use of class exception in java .Exceptions are the condition  in Java to indicate a calling method when an abnormal condition has occurred. This tutorial describes  how to use exceptions in your programs.In this program an exception like division of any number by zero,an exception is caught The steps involved in the program are described below:-
result = a / b:-This is the result which is to be displayed or where the calculation is being performed.
catch (ArithmeticException e) { System.out.println(e.getMessage()+"Exception"):-This is the Exception message which is to be displayed if any of the error occured.ArithmeticException" is a subclass of "RuntimeException", which again is a subclass of class "Exception
ClassException.java
public class ClassException {
public float divide(int a, int b) {
  float result;
  try {
  result = a / b;
  }
  catch (ArithmeticException e) {
  System.out.println(e.getMessage()+"Exception");
  result = Float.NaN;
  }
  return result;
}
  public static void main(String[] args) throws Exception {
  ClassException a=new ClassException();
  System.out.println(a.divide(4,0));
  
  }
}
Output of the program
/ by zeroException
NaN


Post a Comment

0 Comments