In Java, an exception can be thought of as an error when the program is being run. There are numerous types of exceptions that may occur.
In order for an exception to be used in a program, it must throw it.
Below is a short example showing a basic exception:
public class Example{
public static void main(String args[]){
int x = -5;
if(x < 0){
throw new IllegalArgumentException("The number is too small!");
}
System.out.println(x);
}
}
The above example will simply throw a new exception. In general, it is of the form:
throw new ExceptionName("Error Message");
where throw is the keyword to generate an exception; new is creating the Exception object; ExceptionName is the name of the exception (see below); and the string "Error Message" is a useful message that the user will see when the exception is thrown.
In Java, there are many types of exceptions that are defined within the Java libraries. Below is chart of the most commonly seen exceptions that Java will generate.
1.IllegalArgumentException
-An exception to handle a problem with method or command-line arguments. One way to think of this is if the user does not give a command-line argument or the argument in a method is not in a certain range, this is the appropriate exception to be thrown.
2.NumberFormatException
-An exception to handle a problem when formatting a number(s). This is commonly seen when using any of the parseXXX methods of a certain class. Say that your string is "1234ff" and you call parseInt; when you get to the 'f', the exception will be thrown since 'f' is not a number.
3.ArrayIndexOutOfBoundsException
-The name says it all. This exception will occur when an index in an array is out of bounds in either direction (less than 0 or greater than or equal to its size).
4.NullPointerException
-Ah yes, the most commonly seen and most annoying exception of them all! This means that you are pointing at nothing (or null) perhaps in a linked list or even when dealing with a JOptionPane. The solution: a bottle of Tylenol and good debugging skills.
5.Exception
-The most general type of exceptions of them all. This will not specifically check for anything but will mean some kind of error occurred.
6.ArithmeticException
-Arithmetic error condition (for example, divide by zero).
7.ArrayStoreException
-Object type mismatch between the array and the object to be stored in the array.
8.StringIndexOutOfBoundsException
-Index is negative or greater than the size of the string.
9.IllegalThreadStateException
-Object type mismatch between the array and the object to be stored in the array.
10.ClassNotFoundException
-Unable to load the requested class.
Sample programs
An example of a built-in exception.
Sample Program 1
import java.io.*;
import java.util.*;
public class Example{
public static void main(String args[]){
StringTokenizer st;
try{
BufferedReader br = new BufferedReader(
new FileReader("input1.txt"));
String line = br.readLine();
double avg = 0.0;
int num = 0, count = 0;
while(line != null){
st = new StringTokenizer(line);
for(int i = 0; i < st.countTokens(); i++){
avg += Double.parseDouble(st.nextToken());
count++;
}
line = br.readLine();
}
br.close();
avg = avg/count;
System.out.println("Avg: " + avg);
}catch(Exception e){}
} //main
} //class
Sample Program 2
import java.io.* ;
import java.lang.Exception ;
public class DivideBy0 {
public static void main( String[] args ) {
int a = 2 ;
int b = 3 ;
int c = 5 ;
int d = 0 ;
int e = 1 ;
int f = 3 ;
try
{
System.out.println( a+"/"+b+" = "+div( a, b ) ) ;
System.out.println( c+"/"+d+" = "+div( c, d ) ) ;
System.out.println( e+"/"+f+" = "+div( e, f ) ) ;
}
catch( Exception except )
{
System.out.println( "Caught exception " +
except.getMessage() ) ;
}
}
static int div( int a, int b ) {
return (a/b) ;
}
}
The output of this application is shown here:
2/3 = 0
Caught exception / by zero
Sample Program 3
IllegalArgumentException program
public class NewExceptionName extends OldExceptionName{
public NewExceptionName(String gripe){
super(gripe); //super class: OldExceptionName
}
}
public class GradStudentException extends IllegalArgumentException{
public GradStudentException(String gripe){
super(gripe);
}
}
BufferedReader varName = new BufferedReader(
new FileReader("filename.txt"));
try{
BufferedReader br;
br = new BufferedReader(new FileReader("input.txt"));
//rest of reading code here
}catch(Exception e){
System.out.println("Error!");
}
Output
i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
Yikes! i= 7
Yikes! i= 8
Sum: 23
Sample Program 4
public class TryExample2{
public static void main(String args[]){
String str = "2346512aa";
int sum = 0;
for(int i = 0; i <= str.length(); i++){
try{
sum += Integer.parseInt(str.charAt(i) + "");
}catch(IndexOutOfBoundsException ioe){
System.out.print("Regular! ");
}catch(NumberFormatException nfe){
System.out.print("Yikes! ");
}finally{
System.out.println("i= " + i);
}
}
System.out.println("Sum: " + sum);
} //main
} //class
output:
i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
Yikes! i= 7
Yikes! i= 8
Regular! i= 9
Sum: 23
Sample Program 5
import java.io.*;
public class OutputExample{
public static void main(String args[]){
if(ars.length == 0){
System.out.println("String argument needed.");
System.exit(1);
}
String word = args[0];
try{
BufferedWriter bw = new BufferedWriter(
new FileWriter("output.txt"));
String ans = "";
for(int i = 0; i < word.length(); i++){
ans += word.substring(i);
bw.write(ans);
bw.newLine();
ans = "";
}
bw.close();
}catch(Exception e){}
} //main
} //class
output:
hello there
ello there
llo there
lo there
o there
there
there
here
ere
re
e
12:21 AM |
12:17 AM |
Encapsulation (object-oriented programming)-
in an object oriented programming encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination:
• A language mechanism for restricting access to some of the object's components.
• A language construct that facilitates the bundling of data with the methods operating on that data.
Programming language researchers and academics generally use the first meaning alone or in combination with the second as distinguishing feature of object oriented programming. The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus information hiding is defined as a separate notion by those who prefer the second definition.
Classes and objects
Java Classes
• The class is the basic data abstraction mechanism in Java
• Classes combine records, data structures, and information
hiding into one structure
• Classes are used to construct Abstract Data Types (ADTs)
Class Characteristics:
• Name: Used to declare objects of the class
• State definition: Collection of variables (fields)
• Behavior: Collection of methods
• Semantics: Constraints on state-space and behavior
• Access Levels: Private, protected, public, default
A Java class defines a set of values and a set of
operations. Together, these form a type. An instance,
or object, of that class is a variable of the class type.
Watch W = new Watch ();
W is an instance of the class Watch.
A class is a type constructor:
• Similar in use to an Ada package, a Modula-2 module, or
a C++ class
• A class is more than a type ... it is an encapsulation unit
• A class is used in place of type definitions and collections of
functions
Classes are used to create objects
• Objects have:
– identity : name
– state : a set of values for the data members
– behavior: sequence of operations
• Objects may be dynamically allocated
• References to objects can be passed as parameters to methods
Abstract Data Types
A class with a private representation and a public set of
operations is used to implement abstract data types
Fraction myFraction;
myFraction = new Fraction ();
Point Class
class Point {
private int x;
protected void setX (int y) {x = y;}
public int getX() {return x;}
Point(int xval) {x = xval;} // constructor
};
The Class Object
The standard class Object is the superclass of all other classes. A variable of type Object can hold a reference to any object, whether it is an instance of a class or an array. All class and array types inherit the methods of class Object
The Class String
Instances of class String represent sequences of Unicode characters . A String object has a constant, unchanging value. String literals are references to instances of class String.
Class Variables
In an assignment statement, the pointer of a reference typed variable is copied
A variable is a storage location. It has an associated type, sometimes called its compile-time type, that is either a primitive type or a reference type . A variable always contains a value that is assignment compatible with its type. A variable of a primitive type always holds a value of that exact primitive type. A variable of reference type can hold either a null reference or a reference to any object whose class is assignment compatible with the type of the variable.
Compatibility of the value of a variable with its type is guaranteed by the design of the Java language because default values are compatible and all assignments to a variable are checked, at compile time, for assignment compatibility.
There are seven kinds of variables:
1. A class variable is a field of a class type declared using the keyword static within a class declaration, or with or without the keyword static in an interface declaration. Class variables are created when the class or interface is loaded and are initialized on creation to default values . The class variable effectively ceases to exist when its class or interface is unloaded after any necessary finalization of the class has been completed.
2. An instance variable is a field declared within a class declaration without using the keyword static . If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value as part of each newly created object of class T or of any class that is a subclass of T. The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object has been completed.
3. Array components are unnamed variables that are created and initialized to default values whenever a new object that is an array is created . The array components effectively cease to exist when the array is no longer referenced.
4. Method parameters name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked. The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete.
5. Constructor parameters name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression or explicit constructor invocation is evaluated. The new variable is initialized with the corresponding argument value from the creation expression or constructor invocation. The constructor parameter effectively ceases to exist when the execution of the body of the constructor is complete.
6. An exception-handler parameter variable is created each time an exception is caught by a catch clause of a try statement . The new variable is initialized with the actual object associated with the exception . The exception-handler parameter effectively ceases to exist when execution of the block associated with the catch clause is complete.
7. Local variables are declared by local variable declaration statements. Whenever the flow of control enters a block or a for statement, a new variable is created for each local variable declared in a local variable declaration statement immediately contained within that block or for statement. The local variable is not initialized, however, until the local variable declaration statement that declares it is executed. The local variable effectively ceases to exist when the execution of the block or for statement is complete.
Methods
Classes and interfaces are composed of one more members; either data members (fields) or function members (methods).
• Methods are composed of statements; either declarations (local variables) or executable statements
Object-oriented methods
• Methods define the kinds of messages (and parameters) which objects of a particular class may receive.
• All object-oriented behavior is implemented through methods.
• Those members which exist in individual objects and are independent from the same named members in other instances of the same class
– A static field defines a single variable shared by all instances of the class.
– A non-static field defines a variable that is replicated whenever a new instances of the class is constructed.
– A static method may not make an unqualified reference to any static member (field or method).
– A non-static method may make unqualified references to both static and non-static members.
– May also use the reserved this variable.
Passing Parameters
There are two ways that you can pass parameters in Java.
pass-by-value (call-by-value)
pass-by-reference (call-by-reference)
Call-by-value
So far we have only passed primitive data types to methods.
Primitive data types are ALWAYS passed by value!! We do not have a choice in the matter.
Call-by-Reference
This is our other mechanism for parameter passing.
Java does not allow objects (i.e. Strings) to be passed to methods. Instead a reference to that object is passed.
