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

Read Users' Comments (0)

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.

Read Users' Comments (0)

Inheritance, Polymorphism, Interface



*Inheritance-Is the capability of a class to use the properties and methods of another class while adding its own functionality. An example of where this could be useful is with an employee records system. You could create a generic employee class with states and actions that are common to all employees. Then more specific classes could be defined for salaried, commissioned and hourly employees. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process.


>Super Class-
Any class above a specific class in the class hierarchy.
>Sub class

Any class below a specific class in the class hierarchy.
A subclass can also explicitly call a constructor of its immediate superclass. This is done by using the super constructor call. A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the superclass, based on the arguments pa
>Benefits of Inheritance

Benefits of Inheritance in OOP : Reusability– Once a behavior (method) is defined in a superclass, that behavior is automatically inherited by all subclasses. – Thus, you can encode a method only once and they can be used by all subclasses. – A subclass only needs to implement the differences between itself and the parent.
>Overriding Methods-

methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.
If for some reason a derived class needs to have a different implementation of a certain method from that of the superclass, overriding methods could prove to be very useful. A subclass can override a method defined in its superclass by providing a new implementation for that method.
>Final Methods and Classes

Final Methods–
Methods that cannot be overridden
To declare final methods, we write,
public final [returnType] [methodName]([parameters]){. . .}
>Static methods are automatically final.

Final Classes
– Classes that cannot be extended
– To declare final classes, we write,
public final ClassName{. . . }
Example:
Other examples of final classes are your wrapper classes and Strings.
public final class Person { . . . }


*Polymorphism
– The ability of a reference variable to change behavior according to what object it is holding.– This allows multiple objects of different subclasses to be treated as objects of a single superclass, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to.
Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. This is the third basic principle of object oriented programming. Overloading and overriding are two types of polymorphism . Now we will look at the third type: dynamic method binding.



>Abstract Classes
a class that cannot be instantiated. often appears at the top of an object-oriented programming class hierarchy, defining the broad types of actions possible with objects of all subclasses of the class.
*Interface
Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. Interfaces can be inherited (ie. you can have a sub-interface). As with classes the extends keyword is used for inheritence.Java does not allow multiple inheritance for classes (ie. a subclass being the extension of more than one superclass). An interface is used to tie elements of several classes together. Interfaces are also used to separate design from coding as class method headers are specified but not their bodies. This allows compilation and parameter consistency testing prior to the coding phase. Interfaces are also used to set up unit testing frameworks.

Read Users' Comments (0)

Topics discussed in Java 1

1.Topics discussed in Java 1
>BufferedReader-Buffered input Stream Character
>Filereader-Input Stream that read from a file
>Basic elements of java
1.Application
2.Applet

Syntax rules- tell you which statements are legal or accepted and which are not.

Semantic rules- determine the meaning of the instructions.

Identifiers-are names of things are defined by user.

Class-is used to create a java program.

Method-is a set of instructions designed to accomplish a specific task.

Read Users' Comments (0)

Introduction to Java Programming

Introduction to Java Programming
a.History
The Java language has undergone several changes since JDK 1.0 as well as numerous additions of classes and packages to the standard library. Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community Process (JCP), which uses Java Specification Requests (JSRs) to propose and specify additions and changes to the Java platform. The language is specified by the Java Language Specification (JLS); changes to the JLS are managed under JSR 901
.
In addition to the language changes, much more dramatic changes have been made to the Java class library over the years, which has grown from a few hundred classes in JDK 1.0 to over three thousand in J2SE 5.0. Entire new APIs, such as Swing and Java2D, have been introduced, and many of the original JDK 1.0 classes and methods have been deprecated
.

b.Java Technology

a. Programming language-is an artificial language designed to express computations that can be performed by a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine, to express algorithms precisely, or as a mode of human communication.
Many programming languages have some form of written specification of their syntax (form) and semantics (meaning). Some languages are defined by a specification document. For example, the C programming language is specified by an ISO Standard. Other languages, such as Perl, have a dominant implementation
that is used as a reference.
The earliest programming languages predate the invention of the computer, and were used to direct the behavior of machines such as Jacquard looms and player pianos. Thousands of different programming languages have been created, mainly in the computer field, with many more being created every year. Most programming languages describe computation in an imperative style, i.e., as a sequence of commands, although some languages, such as those that support functiona programming or logic programming
, use alternative forms of description.
b.Development Invironment- Development environment may refer to Integrated development environment.In hosted software (eg web site/application, database not shrinkwrap software) development, Development environment refers to a server tier designated to a specific stage in a release process.Development, staging
, and production is a common arrangement of tiers.
A more comprehensive list of tiers:

c.Application Invironment

d.Deployment Invironment

c.Java Features
-Java Virtual Machine
-Garbage Collection
-Code Security

Java 6 Features
feature or an enhancement in Java is encapsulated in the form of a JSR. JSR, which stands for Java Specification Request is nothing but a formal proposal which details the need for a specific functionality to be available in the Java Platform that can be used by Applications. These JSR’s will be reviewed and released by a committee called Java Expert Groups (JEG). This article covers the following list of features (or JSRs') that comes along with the Java 6 Platform.
>Pluggable Annotation Processing API (JSR 269)
>Common Annotations (JSR 250)
>Java API for XML Based Web Services - 2.0 (JSR 224)
>JAXB 2.0 (JSR 222)
>Web Services Metadata (JSR 181)
>Streaming API for XML (JSR 173)
>XML Digital Signature (JSR 105)
>Java Class File Specification Update (JSR 202)
>Java Compiler API (JSR 199)
>JDBC 4.0 (JSR 221)
>Scripting in the Java Platform (JSR 223)

d.The differrence between Java Application and Java Applet.

f.What makes Java an Object-Oriented-Programming Language.



Read Users' Comments (0)