Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 70

Hands-on Duration in

Hours

Topic

Day

1.

Overview- Environment Setup Basic


Syntax

2.

Object & Classes

3.

Basic Data types


Variable Types
Modifier Types

4.

Basic Operators
Loop Control
Decision Making

5.

Numbers Methods
Characters Methods
Strings Methods

6.

Arrays
Date & Time

7.

Methods

8.

Exceptions

9.

Inheritance

10.

Polymorphism

11.

Interfaces

12.

Packages

13.

Files and I/O

14.

GUI Programs-Java Applets

15.

Window Forms

1. OVERVIEW- ENVIRONMENT SETUP BASIC


Java Basics
Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform
(Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8.
Java is guaranteed to be Write Once, Run Anywhere.

Features of Java

Object Oriented

Platform independent

Simple

Secure

Architectural-neutral

Portable

Robust

Multithreaded

Interpreted

High Performance

Distributed

Dynamic

Java Versions
Release

Year

JDK Beta

1995

JDK 1.0

1996

JDK 1.1

1997

J2SE 1.2

1998

J2SE 1.3

2000

J2SE 1.4

2002

J2SE 5.0

2004

Java SE 6

2006

Java SE 7

2011

Java SE 8

2014

JVM vs JRE vs JDK


JVM Java Virtual machine
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JRE Java Runtime Environment

JRE is used to provide runtime environment.It is the implementation of JVM.It physically exists.
JRE = JVM + Required Library to run Application.
JDK Java Development Kit
JDK = JRE + Required Library to develop Java Application

Setting up the path for windows


Installation Folder > c:\Program Files\java\jdk directory
(Java sdk can be downloaded from the following link)
Download Link : http://www.oracle.com/technetwork/java/javase/downloads/

Right-click on 'My Computer' and select 'Properties'.

Click on the 'Environment variables' button under the 'Advanced' tab.

Set the Path variable to include c:\Program Files\java\jdk\bin'.

Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your


path to read 'C:\WINDOWS\SYSTEM32; c:\Program Files\java\jdk\bin'.

Using Command Prompt


set path=C:\Program Files\Java\jdk1.6.0_23\bin

2. Object & Classes


Java can be defined as a collection of objects that communicate via invoking each other's
methods.
Object - Objects have states and behaviors.
Example: A dog has states - colour, name, breed as well as behaviors -wagging, barking, and
eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describe the behaviors/states that
object of its type support.
Methods - A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.
Simple Java program

public class FirstJavaProgram {


/* This is my first java program.
* This will print 'Welcome to the World of Java' as the output
*/ ---------------- Multiline comments (Non executable one)
public static void main(String []args) {
System.out.println("'Welcome to the World of Java ");
// prints Hello World (Single line comment)
}
}

Executing Java Program


Step 1 : Compile FirstJavaProgram.java using javac compiler.
javac FirstJavaProgram.java
This step creates FirstJavaProgram.class file after the successful compilation. If any errors , Correct the
code and compile it once again.
Step2 : Execute the FirstJavaProgram.class file
java FirstJavaProgram

Sample program
class Student{

int rollNo;//data member (also instance variable)


String name;//data member(also instance variable)

public static void main(String args[]){


Student s1=new Student();//creating an object of Student
System.out.println(s1.rollNo);
System.out.println(s1.name);
}
}
public class Car{
String Brand;
float price;
String color;
void details (){
System.out.println (brand + + price+ + color);

}}

3. Data types and Variable Types and Decision making

Primitive Data types

Data Type

Default Value

Default size

boolean

false

1 bit

char

'\u0000'

2 byte

byte

1 byte

short

2 byte

int

4 byte

long

0L

8 byte

float

0.0f

4 byte

double

0.0d

8 byte

4. Operators

Operators

Precedence

postfix

expr++ expr--

unary

++expr --expr +expr -expr ~ !

multiplicative

*/%

additive

+-

shift

<< >> >>>

relational

< > <= >= instanceof

equality

== !=

bitwise AND

&

bitwise exclusive OR

bitwise inclusive OR

logical AND

&&

logical OR

||

ternary

?:

assignment

= += -= *= /= %= &= ^= |= <<= >>=


>>>=

Variables Types
A class can contain any of the following variable types.

Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.

Instance variables: Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.

Class variables: Class variables are variables declared with in a class, outside any
method, with the static keyword.

Keywords
abstract
default
if
private
this
boolean
do
implements
protected
throw

extends
null
break
double
import
public
throws
byte
else
instanceof

return
transient
case
int
false
short
try
catch
final
interface

static
void
char
finally
long
strictfp
volatile
true
class
float

native
super
while
const
for
new
switch
continue
goto
package
synchronized

Decision Making and Loop Statements

Statement

Description

if statement

An if statement consists of a boolean expression followed by


one or more statements.

if...else statement

An if statement can be followed by an optional else statement,


which executes when the boolean expression is false.

nested if statements

You can use one if or else if statement inside another if or else if


statement(s).

switch statement

A switch statement allows a variable to be tested for equality


against a list of values.

Loop Statements
Loop Type

Description

while loop

Repeats a statement or group of statements while a given


condition is true. It tests the condition before executing the
loop body.

for loop

Execute a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

do...while loop

Like a while statement, except that it tests the condition at the


end of the loop body

5.Numbers, Character and String Methods


Wrapper classes
Wrapper classes equivalent classes for primitive data types. All the wrapper classes (Integer,
Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

Number Methods
SN

Methods with Description

xxxValue() - Converts the value of this Number object to the xxx data type and returned it.

compareTo() - Compares this Number object to the argument.

equals() - Determines whether this number object is equal to the argument.

valueOf() - Returns an Integer object holding the value of the specified primitive.

toString() - Returns a String object representing the value of specified int or Integer.

parseInt() - This method is used to get the primitive data type of a certain String.

abs()- Returns the absolute value of the argument.

ceil() - Returns the smallest integer that is greater than or equal to the argument. Returned as
a double.

floor() - Returns the largest integer that is less than or equal to the argument. Returned as a
double.

10
rint() - Returns the integer that is closest in value to the argument. Returned as a double.

11

round() - Returns the closest long or int, as indicated by the method's return type, to the
argument.

12 min() - Returns the smaller of the two arguments.

13 max() - Returns the larger of the two arguments.

14 exp() - Returns the base of the natural logarithms, e, to the power of the argument.

15 log() - Returns the natural logarithm of the argument.

16 pow() - Returns the value of the first argument raised to the power of the second argument.

17 sqrt() - Returns the square root of the argument.

18 sin() - Returns the sine of the specified double value.

19 cos() - Returns the cosine of the specified double value.

20 tan() - Returns the tangent of the specified double value.

21 asin() - Returns the arcsine of the specified double value.

22 acos() - Returns the arccosine of the specified double value.

23 atan() - Returns the arctangent of the specified double value.

24

atan2() - Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns
theta.

25 toDegrees() - Converts the argument to degrees

26 toRadians() - Converts the argument to radians.

27 random() - Returns a random number.

Character Methods

SN

Methods with Description

isLetter() - Determines whether the specified char value is a letter.

isDigit() - Determines whether the specified char value is a digit.

isWhitespace() - Determines whether the specified char value is white space.

isUpperCase() - Determines whether the specified char value is uppercase.

isLowerCase() - Determines whether the specified char value is lowercase.

toUpperCase() - Returns the uppercase form of the specified char value.

toLowerCase() - Returns the lowercase form of the specified char value.

toString() - Returns a String object representing the specified character valuethat is, a one-character
string.

String Methods:

Here is the list of methods supported by String class:

SN

Methods with Description

char charAt(int index) Returns the character at the specified index.

int compareTo(Object o) Compares this String to another Object.

int compareTo(String anotherString) Compares two strings lexicographically.

int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case


differences.

String concat(String str) Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the
same sequence of characters as the specified StringBuffer.

static String copyValueOf(char[] data) Returns a String that represents the character
sequence in the array specified.

static String copyValueOf(char[] data, int offset, int count) Returns a String that represents
the character sequence in the array specified.

boolean endsWith(String suffix) Tests if this string ends with the specified suffix.

10 boolean equals(Object anObject) Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString) Compares this String to another String,

11 ignoring case considerations.

byte getBytes() Encodes this String into a sequence of bytes using the platform's default

12 charset, storing the result into a new byte array.

byte[] getBytes(String charsetName)Encodes this String into a sequence of bytes using the

13 named charset, storing the result into a new byte array.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this

14 string into the destination character array.

15 int hashCode() Returns a hash code for this string.

int indexOf(int ch) Returns the index within this string of the first occurrence of the specified

16 character.

int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence

17 of the specified character, starting the search at the specified index.

int indexOf(String str) Returns the index within this string of the first occurrence of the

18 specified substring.

int indexOf(String str, int fromIndex) Returns the index within this string of the first

19 occurrence of the specified substring, starting at the specified index

20 String intern() Returns a canonical representation for the string object.

int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the

21 specified character.

int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last

22 occurrence of the specified character, searching backward starting at the specified index.

int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of

23 the specified substring.

int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last

24 occurrence of the specified substring, searching backward starting at the specified index.
25 int length() Returns the length of this string.

boolean matches(String regex) Tells whether or not this string matches the given regular

26 expression.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

27 Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions

28 are equal

String replace(char oldChar, char newChar) Returns a new string resulting from replacing all

29 occurrences of oldChar in this string with newChar.

String replaceAll(String regex, String replacement Replaces each substring of this string that

30 matches the given regular expression with the given replacement.

String replaceFirst(String regex, String replacement) Replaces the first substring of this

31 string that matches the given regular expression with the given replacement.

32 String[] split(String regex) Splits this string around matches of the given regular expression.

String[] split(String regex, int limit) Splits this string around matches of the given regular

33 expression.

34 boolean startsWith(String prefix) Tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix

35 beginning a specified index.

CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence

36 that is a subsequence of this sequence.

37 String substring(int beginIndex) Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this

38 string.

39 char[] toCharArray() Converts this string to a new character array.

String toLowerCase() Converts all of the characters in this String to lower case using the

40 rules of the default locale.

String toLowerCase(Locale locale) Converts all of the characters in this String to lower case

41 using the rules of the given Locale.

42 String toString() This object (which is already a string!) is itself returned.

String toUpperCase() Converts all of the characters in this String to upper case using the

43 rules of the default locale.

String toUpperCase(Locale locale) Converts all of the characters in this String to upper case

44 using the rules of the given Locale.

45 String trim() Returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(primitive data type x) Returns the string representation of the passed

46 data type argument.

6.Arrays - Date & Time


Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.

Declaring Array Variables:

Syntax :

dataType[] arrayRefVar = new dataType[arraySize];


dataType[] arrayRefVar = {value0, value1, ..., valuek};
Example :
int[] arr = new int[5];
arr[0]=12; arr[1]=3; .
int[] arr = {1,2,3,4,5};

Passing arrays to methods -> methodname(arrayname) - > printArray(arr);

(where arr - > int[] arr={1,2,3,4,5};)


public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Returning array - > return arrayname;

Date class

Java provides the Date class available in java.util package, this class encapsulates the current
date and time.
The Date class supports two constructors as shown below.

Date()

Date(long millisec)

Date Formatting using SimpleDateFormat:

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive


manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for datetime formatting.
SimpleDateFormat format codes:

To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved
as pattern letters, which are defined as the following:
Character

Description

Example

Era designator

AD

Year in four digits

2001

Month in year

July or 07

Day in month

10

Hour in A.M./P.M. (1~12)

12

Hour in day (0~23)

22

Minute in hour

30

Second in minute

55

Millisecond

234

Day in week

Tuesday

Day in year

360

Day of week in month

2 (second Wed. in July)

Week in year

40

Week in month

A.M./P.M. marker

PM

Hour in day (1~24)

24

Hour in A.M./P.M. (0~11)

10

Time zone

Eastern Standard Time

'

Escape for text

Delimiter

"

Single quote

Sample
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.printf("%1$s %2$tB %2$td, %2$tY",
"Due date:", date);
}
}
Output
Due date: February 22, 2016
GregorianCalendar Class:

GregorianCalendar is a concrete implementation of a Calendar class that implements the normal


Gregorian calendar.

Date and Time Conversion Characters:


Character

Description

Example

Complete date and time

Mon May 04 09:51:52 CDT 2009

ISO 8601 date

2004-02-09

U.S. formatted date (month/day/year)

02/09/2004

24-hour time

18:05:19

12-hour time

06:05:19 pm

24-hour time, no seconds

18:05

Four-digit year (with leading zeroes)

2004

Last two digits of the year (with leading zeroes)

04

First two digits of the year (with leading zeroes)

20

Full month name

February

Abbreviated month name

Feb

Two-digit month (with leading zeroes)

02

Two-digit day (with leading zeroes)

03

Two-digit day (without leading zeroes)

Full weekday name

Monday

Abbreviated weekday name

Mon

Three-digit day of year (with leading zeroes)

069

Two-digit hour (with leading zeroes), between 00 and 23

18

Two-digit hour (without leading zeroes), between 0 and 23 18

Two-digit hour (with leading zeroes), between 01 and 12

Two-digit hour (without leading zeroes), between 1 and 12 6

Two-digit minutes (with leading zeroes)

05

Two-digit seconds (with leading zeroes)

19

Three-digit milliseconds (with leading zeroes)

047

Nine-digit nanoseconds (with leading zeroes)

047000000

Uppercase morning or afternoon marker

PM

Lowercase morning or afternoon marker

pm

RFC 822 numeric offset from GMT

-0800

Time zone

PST

Seconds since 1970-01-01 00:00:00 GMT

1078884319

Milliseconds since 1970-01-01 00:00:00 GMT

1078884319047

06

7. Methods
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the System.out.println() method, for example, the system actually executes several statements
in order to display a message on the console.

public static int methodName(int a, int b) {


// body
}
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min; }

Method Overloading
A class may define multiple methods with the same name---this is called method
overloading
usually perform the same task on different data types
Example: The PrintStream class defines multiple println methods, i.e., println is
overloaded:
println (String s)
println (int i)
println (double d)

The following lines use the System.out.print method for different data types:
System.out.println ("The total is:");
double total = 0;
System.out.println (total);

8. EXCEPTION HANDLING
An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications, or the JVM has run
out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

Categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically a user error or


a problem that cannot be foreseen by the programmer. For example, if a file is to be opened,
but the file cannot be found, an exception occurs. These exceptions cannot simply be
ignored at the time of compilation.

Runtime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.

Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They
are also ignored at the time of compilation.

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in
case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment.

Example : JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses : IOException class and RuntimeException Class.

Exceptions Methods

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in protected code, the catch block (or blocks) that follow the try is
checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to
the catch block much as an argument is passed into a method parameter.

Uncaught Exceptions
It is useful to see what happens when you dont handle them. This small program includes an
expression that intentionally

causes a divide-by-zero error:


class Exc0 {
public static void main(String args[]) {
int d = 0;

int a = 42 / d;
}
}
Multiple catch Blocks (try, Catch):
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:
try
{
//Protected code
}catch(ExceptionType1
e1)
{
//Catch block
}catch(ExceptionType2
e2)
{
//Catch block
}catch(ExceptionType3
e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try.

If an exception occurs in the protected code, the exception is thrown to the first catch
block in the list. If the data type of the exception thrown matches ExceptionType1, it gets
caught there.

Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another
try.
Each time a try statement is entered, the context of that exception is pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statements catch handlers are inspected for a match.

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the
throws keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Try to understand the different in throws and throw
keywords.

The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally
block of code always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:
try
{

//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another
try.
Each time a try statement is entered, the context of that exception is pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception, the stack is
unwound and the next try statements catch handlers are inspected for a match.

9. Inheritance

Types:

It is a form of software reusability in which new classes are created


from existing classes by absorbing their attributes and behaviors and
adding new capabilities the new classes require.
Takes advantage of class relationships where objects of a certain class
such as a class of vehicleshave the same characteristics.
Newly created classes of objects are derived by absorbing
characteristics of existing classes and adding unique characteristics of
their own.
An object of class convertible certainly has the characteristics of the
more general class automobile, but a convertibles roof goes up and
down.
Saves time in program development.

The following kinds of inheritance are there in java.

Simple Inheritance

Multilevel Inheritance

Simple Inheritance
When a subclass is derived simply from its parent class then this mechanism is
known as simple inheritance. In case of simple inheritance there is only a sub class
and it's parent class. It is also called single inheritance or one level inheritance.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);

eg

}
}

class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}

Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived
from a derived class then this mechanism is known as the multilevel inheritance.
The derived class is called the subclass or child class for it's parent class and this
parent class works as the child class for it's just above ( parent ) class. Multilevel
inheritance can go up to any number of level.
e.g.
class A {
int x;

int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);

a.Show();
}}

Java does not support multiple Inheritances


Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is known
as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance
can be achieved by using the interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more
than one interface in a class.
Super-classes and Subclasses
Often an object of one class is an object of another class as well. A rectangle certainly is a
quadrilateral (as are squares, parallelograms and trapezoids). Thus, class Rectangle can be said
to inherit from class Quadrilateral. In this context, class Quadrilateral is a super-class, and
class Rectangle is a subclass. A rectangle is a specific type of quadrilateral, but it is incorrect to
claim that a quadrilateral is a rectangle (the quadrilateral could be a parallelogram). Figure
shows several simple inheritance examples of super-classes and potential subclasses.

super keyword

The super is java keyword. As the name suggest super is used to access the members of the super
class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by
the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B
is the subclass that also contains its own data members named a and b. then we can access the
super class (class A) variables a and b inside the subclass class B just by calling the following
command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to
handle situations where the local member of a subclass hides the members of a super class
having the same name. The following examples clarify all the confusions.
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args){

B subobj = new B(1, 5);


subobj.Show();
}
}
Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Use of super to call super class constructor: The second use of the keyword super in java is to
call super class constructor in the subclass. This functionality can be achieved just by using the
following command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super class.
super must be the first statement executed inside a super class constructor. If we want to call the
default constructor then we pass the empty parameter list.

Composition vs. Inheritance

We have also discussed has a relationships in which a class has objects of other classes as
memberssuch relationships create new classes by composition of existing classes.
For example, given the classes Employee, BirthDate and TelephoneNumber, it is
improper to say that an Employee is a BirthDate or that an Employee is a
TelephoneNumber.
But it is certainly appropriate to say that an Employee has a BirthDate and that an
Employee has a TelephoneNumber.

10. POLYMORPHISM
METHOD OVERRIDING

If a class inherits a method from its super class, then there is a chance to override the method
provided that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the sub class type.
Which means a subclass can implement a parent calss method based on its requirement.
In object oriented terms, overriding means to override the functionality of any existing method.
Calling a Method:
In creating a method, you give a definition of what the method is to do. To use a method, you
have to call or invoke it. There are two ways to call a method; the choice is based on whether
the method returns a value or not.
When a program calls a method, program control is transferred to the called method. A called
method returns control to the caller when its return statement is executed or when its methodending closing brace is reached.
If the method returns a value, a call to the method is usually treated as a value. For example:
int larger = max(30, 40);
Passing Parameters by Values:
When calling a method, you need to provide arguments, which must be given in the same order
as their respective parameters in the method specification. This is known as parameter order
association.
Rules for method overriding:

The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the
original overridden method in the super class.
The access level cannot be more restrictive than the overridden method's access level.
For example: if the super class method is declared public then the overridding method
in the sub class cannot be either private or public. However the access level can be less
restrictive than the overridden method's access level.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared
public or protected.

An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
Constructors cannot be overridden.
Using the super keyword:
When invoking a superclass version of an overridden method the super keyword is
used.

In object oriented terms, overriding means to override the functionality of any existing method.
Example:
Let us look at an example.
class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


System.out.println("Dogs can walk and run");
}
}

public class TestDog{

public static void main(String args[]){


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class


}
}
This would produce following result:
Animals can move
Dogs can walk and run
In the above example you can see that the even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is : In compile time the check is made on the
reference type. However in the runtime JVM figures out the object type and would run the
method that belongs to that particular object.

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java,
all Java objects are polymorphic since any object will pass the IS-A test for their own type and
for the class Object.

It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the
object.

A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.

11.INTERFACES

An interface is a collection of abstract methods. A class implements an interface, thereby


inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are
two different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.
An interface is similar to a class in the following ways:

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.

The bytecode of an interface appears in a .class file.

Interfaces appear in packages, and their corresponding bytecode file must be in a


directory structure that matches the package name.
However, an interface is different from a class in several ways, including:

You cannot instantiate an interface.

An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

Defining an Interface

Using the keyword interface, you can fully abstract a class interface from its
implementation.

An interface declaration consists of modifiers, the keyword interface, the interface name,
a comma-separated list of parent interfaces (if any), and the interface body.

Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.


Interfaces add most of the functionality that is required for many applications that would
normally resort to using multiple inheritance in a language such as C++.
For example:
An interface is defined much like a class. This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

The public access specifier indicates that the interface can be used by any class in any
package.

An interface can extend other interfaces, just as a class can extend or subclass another
class. However, whereas a class can extend only one other class,

An interface can extend any number of interfaces. The interface declaration includes a
comma-separated list of all the interfaces that it extends.
Example of an interface definition
It declares a simple interface that contains one method called callback( ) that takes a single
integer parameter.
interface Callback {
void callback(int param);
}

The Interface Body

The interface body contains method declarations for all the methods included in the
interface.


A method declaration within an interface is followed by a semicolon, but no braces,
because an interface does not provide implementations for the methods declared within it.

All methods declared in an interface are implicitly public, so the public modifier can be
omitted.

An interface can contain constant declarations in addition to method declarations. All


constant values defined in an interface are implicitly public, static, and final. Once again, these
modifiers can be omitted.
Implementing Interfaces

Once an interface has been defined, one or more classes can implement that interface.

To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface.

The general form of a class that includes the implements clause looks like this:

class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

If a class implements more than one interface, the interfaces are separated with a comma.

If a class implements two interfaces that declare the same method, then the same method
will be used by clients of either interface.

The methods that implement an interface must be declared public.

Also, the type signature of the implementing method must match exactly the type
signature specified in the interface definition.

Here is a small example class that implements the Callback interface shown earlier.

class Client implements Callback


{
// Implement Callback's interface
public void callback(int p) {

System.out.println("callback called with " + p);


}
}

Notice that callback( ) is declared using the public access specifier.

Partial Implementations

If a class includes an interface but does not fully implement the methods defined by that
interface, then that class must be declared as abstract.

For example:
abstract class Incomplete implements Callback
{
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}

Here, the class Incomplete does not implement callback( ) and must be declared as
abstract.

Any class that inherits Incomplete must implement callback( ) or be declared abstract
itself.

Interfaces Can Be Extended


One interface can inherit another by use of the keyword extends. The syntax is the same as
for inheriting classes.
When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.

Following is an example:
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}

Extending Multiple Interfaces:

A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a commaseparated list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as:

public interface Hockey extends Sports, Event

Tagging Interfaces:

The most common use of extending interfaces occurs when the parent interface does not
contain any methods. For example, the MouseListener interface in the java.awt.event package
extended java.util.EventListener, which is defined as:

package java.util;
public interface EventListener
{}
An interface with no methods in it is referred to as a tagging interface.
Abstract Class

A class which contains the abstract keyword in its declaration is known as abstract class.

Abstract classes may or may not contain abstract methods ie., methods with out body
( public void get(); )

But, if a class have at least one abstract method, then the class must be declared abstract.

If a class is declared abstract it cannot be instantiated.

To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.

If you inherit an abstract class you have to provide implementations to all the abstract
methods in it.

abstract class Bike{


abstract void run();
}

class Honda4 extends Bike{


void run(){System.out.println("running safely..");}

public static void main(String args[]){


Bike obj = new Honda4();
obj.run();
}
}

12.PACKAGES

A package is a grouping of related types providing access protection and name space
management.

Note that types refer to classes, interfaces, enumerations, and annotation types.

Enumerations and annotation types are special kinds of classes and interfaces,
respectively, so types are often referred to in this lesson simply as classes and interfaces

This is the general form of the package statement:

package pkg;

Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage.

package MyPackage;

Java uses file system directories to store packages. For example, the .class files for any

classes you declare to be part of MyPackage must be stored in a directory called MyPackage.

Remember that case is significant, and the directory name must match the package name
exactly.

More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong. It does not exclude other
classes in other files from being part of that same package. Most real-world packages are
spread across many files.

Finding Packages and CLASSPATH

packages are mirrored by directories

the

CLASSPATH environmental variable. the -classpath option with java and javac to specify

path to your classes.

For example, consider the following package specification:

package MyPack

In order for a program to find MyPack, one of three things must be true. Either the program
can be executed from a directory immediately above MyPack,

The CLASSPATH must be set to include the path to MyPack, or the -classpath option must
specify the path to MyPack when the program is run via java.

When the second two options are used, the class path must not include MyPack, itself.

It must simply specify the path to MyPack. For example, in a Windows environment, if the
path to MyPack is

C:\MyPrograms\Java\MyPack

Then the class path to MyPack is

C:\MyPrograms\Java

The easiest way to try the examples shown in this book is to simply create the package
directories below your current development directory, put the .class files into the appropriate
directories, and then execute the programs from the development directory.

ACCESS PROTECTION

Classes and packages are both means of encapsulating and containing the name space and
scope of variables and methods. Packages act as containers for classes and other subordinate
packages.

Classes act as containers for data and code. The class is Javas smallest unit of
abstraction.


Because of the interplay between classes and packages, Java addresses four categories of
visibility for class members:

Subclasses in the same package

Non-subclasses in the same package

Subclasses in different packages

Classes that are neither in the same package nor subclasses

The three access specifiers: private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories.

IMPORTING PACKAGES

The import statement is a convenience to the programmer and is not technically needed to
write a complete Java program.

In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the import
statement:

import pkg1[.pkg2].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.)

There is no practical limit on the depth of a package hierarchy, except that imposed by
the file system. Finally, you specifyeither an explicit classname or a star (*), which indicates
that the Java compiler should import the entire package. This code fragment shows both forms
in use:
import java.util.Date; import java.io.*;

13. IO classes and Interfaces


Java Uses the concept of Streams to represent the ordered sequence of data, a common
characteristic shared by all I/O devices.
Streams presents a uniform, easy to use, object oriented interface between the program
and I/O devices.
A stream in Java is a path along which data flows (like a river or pipe along which water
flows).

The File class does not specify how information is retrieved from or stored in files; it
describes the properties of a file itself.
A File object - used to obtain or manipulate the information associated with a disk
file, such as the permissions, time, date, and directory path, and to navigate
subdirectory hierarchies.

Files are a primary source and destination for data within many programs.

The following constructors can be used to create File objects:

File(String directoryPath)

File(String directoryPath, String filename)

File(File dirObj, String filename)

File(URI uriObj)

Sample

File f1 = new File("/");


File f2 = new File("/","autoexec.bat");
File f3 = new File(f1,"autoexec.bat");

Example program

import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");

p(f1.canWrite() ? "is writeable" : "is not writeable");


p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}

Output:

File Name: COPYRIGHT


Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes

Directories

A directory is a File that contains a list of other files and directories. When you
create a File object and it is a directory, the isDirectory( ) method will return true.

import java.io.File;
class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}

Using FilenameFilter
String[ ] list(FilenameFilter FFObj)
FilenameFilter defines only a single method, accept( ), which is called once for each file in a
list.

General form

boolean accept(File directory, String filename)

The listFiles( )
The signatures for listFiles( ) are shown here:

File[ ] listFiles( )
File[ ] listFiles(FilenameFilter FFObj)
File[ ] listFiles(FileFilter FObj)

Closeable
void close( ) throws IOException
Flushable
void flush( ) throws IOException
Javas stream-based I/O is built upon four abstract classes: InputStream,
OutputStream,Reader, and Writer.

InputStream is an abstract class that defines Javas model of streaming byte input.
It implements the AutoCloseable and Closeable interfaces

OutputStream
OutputStream is an abstract class that defines streaming byte output. It implements the
AutoCloseable, Closeable, and Flushable interfaces.
Input/Output related classes are defined in java.io package.
Input/Output in Java is defined in terms of streams.
A stream is a sequence of data, of no particular length.
Java classes can be categorised into two groups based on the data type one which they
operate:
Byte streams
Character Streams

Byte Stream Classes

Character Stream Classes

PushbackInputStream Example
import java.io.*;
import java.text.SimpleDateFormat;
class PushbackInputStreamDemo
{
public static void main(String args[]) throws IOException
{ final long start = System.nanoTime();
String s = "if (a == 4) a=0;\\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);

int c;
while ((c = f.read()) != -1)
{
switch(c)
{
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else
{
System.out.print("<-");
f.unread(c);
}

break;
default:
System.out.print((char) c);
break;
}//end of Switch

}//end of While

File ff=new File("PushbackInputStreamDemo.java");


System.out.println("\nlast modified : "+ff.lastModified());
SimpleDateFormat ss=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("\ndate modified : "+ss.format(ff.lastModified()));
final long endtime = System.nanoTime();
System.out.println(" Execution time in nano"+ ((endtime-start)/1000000));
}//end of main

}//end of class
PushBackReader Example
import java.io.*;
public class PRDemo {
public static void main(String args[]) throws IOException
{ char carray[] = { 'q', 'u', 'a', 'l', 'i', 't', 'y' };
CharArrayReader careader = new CharArrayReader(carray);
PushbackReader preader = new PushbackReader(careader);
int temp; // read first character and print
temp = preader.read();
System.out.println("The first character: " + (char) temp); // read the second character and print
temp = preader.read();
System.out.println("The second character: " + (char) temp); // read the third character and print
temp = preader.read(); System.out.println("The third character: " + (char) temp);

preader.unread(temp); // unread the third character


temp = preader.read(); // read it again and print
System.out.println("Reading again third character: " + (char) temp);
}}

14. GUI Programs-Java Applets


Applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed, and run as part of a web document.
After an applet arrives on the client, it has limited access to resources so that it can produce a
graphical user interface and run complex computations without introducing the risk of viruses or
breaching data integrity.
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows: It works at client side so less response
time.
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac
Os etc.
Lifecycle of an Applet:
Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1
life cycle methods for an applet. java.applet.Applet class:
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet. public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class:
The Component class provides 1 life cycle method of applet. public void paint(Graphics g): is
used to paint the Applet. It provides Graphics class object that can be used for drawing oval,
rectangle, arc etc.
How to run an Applet?
There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).
Lets begin with the simple applet shown here:
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>

*/
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
}
}
To execute the applet by appletviewer tool, write in
command prompt:
c:\>javac SimpleApplet.java
c:\>appletviewer SimpleApplet.java

16.

14. GUI Programs-Windows Forms


Javas Abstract Window Toolkit(AWT) provides classes and other tools for building
programs that have a graphical user interface.
The term Abstract refers to the AWTs ability to run on multiple platforms.
Building a GUI involves creating abstract components such as buttons and windows,
which are then mapped to concrete components for a specific platform.
Swing vs AWT
Swing is bigger, slower, and more complicated
But not as slow as it used to be
Swing is more flexible and better looking
Swing and AWT are incompatible--you can use either, but you cant mix them
Actually, you can, but its tricky and not worth doing
Learning the AWT is a good start on learning Swing
Many of the most common controls are just renamed
AWT: Button b = new Button ("OK");
Swing: JButton b = new JButton("OK");

FrameTest.java

// Displays a frame on the screen.


// WARNING: Frame cannot be closed.

import java.awt.*;

public class FrameTest {


public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(150, 100);
f.setVisible(true);
}
}

Frame created by the FrameTest program:

As with the other AWT components, the appearance of a frame depends on the platform.
ButtonTest.java

// Displays a frame containing a single button.


// WARNING: Frame cannot be closed.

import java.awt.*;

// Driver class
public class ButtonTest {
public static void main(String[] args) {
Frame f = new ButtonTestFrame("Button Test");
f.setSize(150, 100);
f.setVisible(true);

}
}

// Frame class
class ButtonTestFrame extends Frame {
public ButtonTestFrame(String title) {
super(title);
setLayout(new FlowLayout());
Button b = new Button("Testing");
add(b);
}
}

Event

Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard,selecting an item from list, scrolling the page are the activities that causes
an event to happen.
Types of Event

The events can be broadly classified into two categories:

Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page etc.

Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.

Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs. This mechanism has the code which is known as event handler that is
executed when an event occurs. Java Uses the Delegation Event Model to handle the events.
This model defines the standard mechanism to generate and handle the events.Let's have a
brief introduction to this model.

The Delegation Event Model has the following key participants namely:

Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes for
source object.

Listener - It is also known as event handler.Listener is responsible for generating response


to an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received , the listener process the event an
then returns.
Event handling steps

The User clicks the button and the event is generated.

Now the object of concerned event class is created automatically and information
about the source and the event get populated with in same object.

Event object is forwarded to the method of registered listener class.

The method is now get executed and returns.

AWT Event Classes


Sr.
No.

Control & Description


AWTEvent

It is the root event class for all AWT events. This class and its subclasses supercede the
original java.awt.Event class.
ActionEvent

The ActionEvent is generated when button is clicked or the item of a list is double
clicked.

InputEvent

The InputEvent class is root event class for all component-level input events.
KeyEvent
4

On entering the character the Key event is generated.


MouseEvent

This event indicates a mouse action occurred in a component.


TextEvent

The object of this class represents the text events.


WindowEvent

The object of this class represents the change in state of a window.


AdjustmentEvent

The object of this class represents the adjustment event emitted by Adjustable objects.
ComponentEvent

The object of this class represents the change in state of a window.


ContainerEvent

10

The object of this class represents the change in state of a window.


MouseMotionEvent

11

The object of this class represents the change in state of a window.


PaintEvent

12

The object of this class represents the change in state of a window.

AWT Event Listener Interfaces:


Following is the list of commonly used event listeners.

Sr. No.

Control & Description

ActionListener

This interface is used for receiving the action events.


2

10

11

ComponentListener
This interface is used for receiving the component events.
ItemListener
This interface is used for receiving the item events.
KeyListener
This interface is used for receiving the key events.
MouseListener
This interface is used for receiving the mouse events.
TextListener
This interface is used for receiving the text events.
WindowListener
This interface is used for receiving the window events.
AdjustmentListener
This interface is used for receiving the adjusmtent events.
ContainerListener
This interface is used for receiving the container events.
MouseMotionListener
This interface is used for receiving the mouse motion events.
FocusListener
This interface is used for receiving the focus events.

References
1. Herbert Schildt, Java -Complete Reference, 8th edition Tata McGraw Hill, 2013.
2. Kathy sierra and Bert Bates Head First Java second edition, Oreilly, 2013

3. Harvey M. Deitel and Paul J. Deitel, Java How to Program, Prentice Hall of India,
2012
4. Gary Cornell and Cay S.Horstmann, Core Java Vol.1 and Vol.2, Sun Microsystems
Press, 2010
5. Herbert Schildt, Java(R) 7, A Beginners Guide, Tata McGraw Hill, 2012
http://www.tutorialspoint.com/java/
www.javatpoint.com/java-tutorial
javabeginnerstutorial.com/core-java/

You might also like