JAVA PROGRAMMING RCCS10CA3 Unit I: Overview of JAVA

82
JAVA PROGRAMMING RCCS10CA3 Unit I: Overview of JAVA: JAVA is a general purpose object oriented programming language developed by sun micro systems of USA in 1991. It took 18 months to develop the first working version. This language was initially called ―Oak‖ but was renamed ―JAVA‖ in 1985. Sample JAVA program: import java.io.*; class sample { public static void main(String args[]) { System.out.println(“Welcome to JAVA Programming”); } } In this example, class is a keyword, sample is a identifier. We can develop two types of JAVA Programming. o Stand Alone Applications: - First, compiling the source code and convert into byte code using ‗javac‘ compiler. Example: javac sample.java - Second, executing the byte code program using ‗java‘ interpreter. Example: java sample o Applets: - Java programs that are downloaded over the World Wide Web (WWW) and executed by web browser on the reader‘s machine. Java development Kit [JDK] o JDK contains collection of tools that are used for developing and running JAVA programs. It includes: - appletviewer It is a command line program to run Java applets. It used to test an applet before we run it in a browser. - javac Source files to be compiled - java Bytecode class file to be interpreted - javap Java class file disassembler - javah C header and source file generator - javadoc It is a documentation generator - jdb The Java debugger The Advantages of JAVA: Simple. Java was designed to be easy to use and is therefore easy to write, compile, debug, and learn than other programming languages. Securable Java providing a ―firewall‖ between a networked application and your computer, it protected the personal information (account balances, passwords and etc) theft. We can safely download java applets without fear of viral infection or malicious intent. Java execution environment and not allowing it access to other parts of the computer.

Transcript of JAVA PROGRAMMING RCCS10CA3 Unit I: Overview of JAVA

JAVA PROGRAMMING RCCS10CA3

Unit I:

Overview of JAVA:

JAVA is a general purpose object oriented programming language developed by sun micro

systems of USA in 1991. It took 18 months to develop the first working version.

This language was initially called ―Oak‖ but was renamed ―JAVA‖ in 1985.

Sample JAVA program:

import java.io.*;

class sample {

public static void main(String args[]) {

System.out.println(“Welcome to JAVA Programming”);

}

}

In this example, class is a keyword, sample is a identifier.

We can develop two types of JAVA Programming.

o Stand Alone Applications:

- First, compiling the source code and convert into byte code using ‗javac‘ compiler.

Example: javac sample.java

- Second, executing the byte code program using ‗java‘ interpreter.

Example: java sample

o Applets:

- Java programs that are downloaded over the World Wide Web (WWW) and executed

by web browser on the reader‘s machine.

Java development Kit [JDK]

o JDK contains collection of tools that are used for developing and running JAVA

programs.

It includes:

- appletviewer It is a command line program to run Java applets. It used to test an

applet before we run it in a browser.

- javac Source files to be compiled

- java Bytecode class file to be interpreted

- javap Java class file disassembler

- javah C header and source file generator

- javadoc It is a documentation generator

- jdb The Java debugger

The Advantages of JAVA:

Simple.

Java was designed to be easy to use and is therefore easy to write, compile, debug, and learn

than other programming languages.

Securable

Java providing a ―firewall‖ between a networked application and your computer, it protected

the personal information (account balances, passwords and etc) theft.

We can safely download java applets without fear of viral infection or malicious intent. Java

execution environment and not allowing it access to other parts of the computer.

Interpreted

Java compiler translated source code into byte code instructions. Java byte code can be

interpreted on any system that provides a Java Virtual Machine. (Byte code instructions can

be directly executed by any machine).

Platform-Independent or Robust

Java is its ability to move easily from one computer system to another. The ability to run the

same program on many different systems is crucial to World Wide Web software, and Java

succeeds at this by being platform-independent at both the source and binary levels.

Portable

Java ensures portability in two ways:

1. Java compiler generates byte code instructions that can be implemented on any machine.

2. The size of the primitive data types are machine independent.

Object-Oriented.

This allows you to create modular programs and reusable code. The object model in java is

simple and easy to extend.

Multithreaded

Java allows you to write programs that do many things simultaneously. The java run-time

system comes with an elegant yet sophisticated solution for multiprocess synchronization that

enables you to construct smoothly running interactive systems.

Example: we can lesson audios and working any other applications.

Distributed

Java is designed for the distributed environment of the internet, because it handles TCP/IP

protocols. A package Remote Method Invocation (RMI) provides two different computers to

execute procedures remotely. (It‘s called client/server programming).

Dynamic

Java programs carry with them substantial amounts of run-time type information that is used

to verify and resolve accesses to objects at run time. Small fragments of byte code may be

dynamically updated on a running system.

Basic concepts of Object Oriented Programming:

Classes

Class defines the characteristics of objects which include its attributes, field‘s properties and

behavior. Let us say we have a class called car, then the color, model number, speed can be

its properties. Accelerating, breaking, turning will be its behavior.

Hear will create an object TataNano belonging to the class car.

Objects

Objects are the basic run time entities in an object oriented system, they may be represented a

person, a place, a bank account and etc. An object is also an instant of a class.

Data abstraction

Abstraction refers to the act of representing essential futures without including the

background details or explanations

Encapsulation

The wrapping (grouping) up of data and methods into single unit (called class) is known as

encapsulation.

Data encapsulation is the future of a class, the data is not accessible to the outside and only

those methods which are wrapped in the class can access it.

Inheritance

Inheritance means, one class to inherit the characteristics of another class. A class that is

inherited is called a superclass. The class that does the inheriting is called a subclass.

It supports the concept of hierarchical classification.

Class A

Class B

Finally Class B

Polymorphism

Polymorphism means taking more than one forms.

Polymorphism classified into

1. Function overloading and function overriding

2. Operator overloading.

Dynamic binding

Binding refers to the linking of a procedure call to the code to be executed in response to the

call. Dynamic binding means that code associated with a given procedure call at run time. It

is associated with polymorphism and inheritance.

Message passing

Consist of a set of objects that communicate with each other. It involves the following basic

steps:

1. Creating classes that define objects and their behaviors.

2. Creating object from class definition.

3. Establishing, communication among objects.

Objects have a life cycle they can be created and destroyed. Communication with an object is

feasible as long as it is alive.

1

2

3

4

1 3

2 4

2 Marks:

1. Define data types in java?

Java is a strongly typed language. Every variable and expression has a type. Every type is strictly

defined.

Java defines eight simple types of date: byte, short, int, long, char, float, double, and Boolean.

This type represents single value – not complex values. They can be put in four groups

Simple data types

Integer Floating point Character Boolean

byte float char boolean

short double

int

long

2. What is literal? Write its type?

In Java, a constant value used in a program is called a literal. There are

1. Integer literals

2. Floating point literals

3. Boolean literals

4. Character literals

5. String literals

Example: 2.0, 5 and ‗a‘.

3. Define variables.

The variable is the basic unit of storage in a java program. A variable is defined by the

combination of an identifier, a type, and an optional initializer.

All variables must be declared before they can be used. The basic form is

type identifier[= value][, identifier[= value]…];

Example: int a;

4. How will you declare a variable?

In Java, all variables must be declared before they can be used. The basic form of a variable

declaration is

type identifier[= value][, identifier[= value]…];

The type denotes the data types or the name of a class of interface. The identifier is the name of

the variable. To declare more then one variable of the specified type, use a comma separated list.

Example: int a, b=5;

5. What is scope and lifetime of a variable?

6. Define type conversion and its type?

It is common to assign a value of one type to a variable of another type is called type conversion.

It is classified into two types there are

i. Automatic type conversion (implicit conversion)

ii. Type casting (explicit conversion)

7. What are the conditions in java’s automatic type conversion?

An automatic type conversion will take place if the following two conditions are

- The two types are compatible.

- The destination type is larger then the source type.

8. What is Automatic conversion?

When assigning one type of data to another type of variable, an automatic type conversion will

take place if the following two conditions are

- The two types are compatible.

- The destination type is larger then the source type.

The numeric types are not compatible with char or boolean.

9. Define casting or explicit casting of narrowing conversion?

In cases where java‘s automatic type conversions do not apply, we will need to use an explicit

cost. For example we will need to use a cast when assigning an int value to a byte variable. The

general form is:

(target-type) value

Here, target-type specifies the desired type to convert the specified value

10. Define arrays and its types?

An array is a group of logically related elements that are referred to by a common mane. Arrays

of any type can be created and may have one or more dimensions. They are classified into two

types,

- One-Dimensional Array

- Multi-Dimensional Array

11. How will you initialize an array when declare it?

Arrays can be initialized when they are declared. An array initializer is a list of comma separated

expressions surrounded by curly braces. The commas separate the value of the array elements.

The array will automatically be created large enough to hold the number of elements we specify

in the array initializer. There is no need to use new. For example:

int intx[] = { 1, 2, 3, 4, 5 };

12. Define string?

Java‘s string type called String. It is not a simple type. Nor is it simply an array of characters.

Rather String defines an object of a class.

13. Define class?

A class is a template for an object and an object is an instance of a class. A class is declared

using the class keyword. The general form of a class definition is shown here:

class classname {

type instance-variable1;

type instance-variable2;

//…

type instance-variableN;

type methodname1(parameter-list) {

// body of method

}

type methodname2(parameter-list) {

// body of method

}

//…

type methodnameN(parameter-list) {

// body of method

}

}

14. How to defining a class?

A class is declared using the class keyword. The general form of a class definition is shown here: class classname {

type instance-variable1;

type instance-variable2;

//…

type instance-variableN;

type methodname1(parameter-list) {

// body of method

}

type methodname2(parameter-list) {

// body of method

}

//…

type methodnameN(parameter-list) {

// body of method

}

}

The data or variables, defined within a class are called instance variables. The code is contained

within methods. The methods and variables defined within a class are called members of the

class.

15. Define method.

Method means a procedure, especially a regular and systematic way of accomplishing something.

Two of the components of a method declaration comprise the method signature—the method's

name and the parameter types.

16. How will you create an object for a class?

When we create a class, we are creating a new data type. We can use this type to declare objects

of that type. Obtaining of a class is a two-step process.

1. We must declare a variable of the class type.

2. We must acquire an actual, physical copy of the object and assign it to that variable. This is

accomplished using the new operator.

Here, we create an object ob to the class sample. sample ob;

ob= new sample(); (or) sample ob = new sample();

17. What is constructor?

A constructor initializes an object immediately upon creation. It has the same name as the class.

Constructors have no return type, not even void. This is because the implicit return type of a

class‘s constructor in the class type itself.

Constructors classified depend on the parameter.

- Parameterized Constructor

- Default Constructor

18. How Constructors differ from methods?

Constructor Methods

Constructors cannot be abstract, final, native,

static and synchronized

Method declared as abstract, final, native, static

and synchronized

Constructors support access modifiers Methods also support access modifiers

It have no return type It have return type

Class name and method name are same Class name and method name are different

19. Define garbage collection?

C++ dynamically allocated objects must be manually released by using a delete operator. But

Java, deallocation (memory occupied by the object can be reclaimed) performs automatically.

This technique that accomplishes this is called garbage collection.

20. Define Finalize() method?

Sometimes we will need to ensure that an object has performed some action before it is

destroyed. We might want to make sure this resource has been freed before the object is

destroyed. To handle these types of situations, java provides a mechanism called finalization.

Inside the finalize() method we specify those actions that must be performed before an object is

destroyed. The finalize() method general form is:

protected void finalize() {

// finalization code here

}

21. What is method overloading?

Tow or more methods within the same class that share the same name, as long as their parameter

declarations are different. The methods are said to be overload and the process is referred to as

method overloading.

Overloading methods must differ in the type and/or member of their parameters. While

overloaded methods may have different return types.

22. Differentiate overloading and overriding?

Overloading Overriding

Signature of method is change Signature of method is same

We can overload methods in same class We can overrides methods in sub classes

We can overload static, final or private

method in Java

We can not override static, final and private

method in Java

Overloaded method in Java is bonded by

static binding

Overridden methods are subject to dynamic

binding.

23. What is argument passing?

A computer language can pass an argument to a subroutine is called argument passing. It is

classified into two types

- Call-by-value

- Call-by-reference

24. Differentiate call-by-value and call-by-reference?

Call by Value:

A copies the value of an argument into the formal parameter of the subroutine. Therefore,

changes made to the parameter of the subroutine have no effect on the argument used to call it.

swap(x,y);

/...

swap(int x1, int y1) {

// method code

}

Call by Reference:

A reference to an argument is passed to the parameter. Inside the subroutine, changes made to the

parameter will affect on the argument used to call the subroutine.

swap(&x,&y);

/...

swap(int *x1, int *y1) {

// method code

}

24. What is Recursion?

Java supports recursion. Recursion is the attribute that allows a method to call itself. The

example of recursion is Factorial, Fibonacci series and etc.

When a method calls itself, new local variables and parameters are store on the stack.

25. Write about static.

When a class member is declared static, it may be accessed before any objects of its class are

created and without reference to any object. A static member is for most intents and purposes

global.

We may declare both methods and variables to be static. Method declared as static have several

restrictions

- They can only call other static methods and static data.

- They cannot refer to this or super in any way.

We may also use static to create a block in which we may initialize static variables. A static

block is executed exactly once, when the class is first loaded.

26. Write notes on Access control?

How a class member can be accessed is determined by the access specifier that modifies its

declaration. Java‘s access specifiers are public, private, and protected. A default access level is

also defined.

27. Define main() method?

The main() method is declared as public static so that it can be called by code outside of the class

in which it is declared and before any objects of its class are created.

We will want to pass information into a program when we run it. This is accomplished by

passing commend line arguments to main().

28. What is command line argument?

A commend line argument is the information that directly follows the program‘s name of the

command line when it is executed. They are stored as strings in the String array passed to main().

Example: class CommandLine {

public static void main(String args[]) {

for( int i=0; i<args.length; i++)

System.out.println(“args[“ + i + ”]: ” + args[i]);

}

}

5 Mark Questions:

1. Explain the Data Types in java?

Java is a strongly typed language. Every variable and expression has a type. Every type is strictly

defined.

Simple data types

Integer Floating point Character Boolean

byte float char boolean

short double

int

long

Simple types:

Java defines eight simple types of date: byte, short, int, long, char, float, double, and Boolean.

This type represents single value – not complex values. They can be put in four groups

i. Integers:

- Java defines four integer types: byte, short, int, and long, all of these are whole valued

signed numbers. Java does not support unsigned.

Name Size Range

byte 8 bits -128 to 127

short 16 bits -32,768 to 32767

int 32 bits -2,147,483,648 to 2,147,483,647

long 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ii. Floating point numbers:

- Floating point numbers are used for numbers with fractional components (Decimal part).

There are two floating point types: float and double.

Name Size Range

float 32 bits 3.4e-038 to 3.4e+038

double 64 bits 1.7e-308 to 1.7e+308

iii. Characters:

- The character data type is char. Java uses Unicode to represent characters. Unicode

defines a full international character set that can represent all of the characters found in all

human languages.

- Java char is a 16-bits type. The range of a char is 0 to 65,536. There are no negative

chars.

iv. Boolean:

- Java has a simple type for logical values called boolean. It can have only one of two

possible values, true or false, which are keywords.

2. Define Literals? List out the type of literals and explain it?

In Java, a constant value used in a program is called a literal. There are

i. Integer literals

ii. Floating point literals

iii. Boolean literals

iv. Character literals

v. String literals

i. Integer literals

- Any whole number value is an integer literal. Examples are 1, 15, and 75. These are all

decimal values.

- Integer literals can also be represented in octal (033 is the octal equivalent to the decimal

value 27) and in hexadecimal (0x1b is the octal equivalent to the decimal value 27).

ii. Floating point literals

- Floating point numbers represent decimal values with fractional components (Decimal part).

They can be expressed in either standard notation (Example: 2.0, 3.14159, and 0667) or

scientific notation (Example: 6.02E23, 314159E-05, and 2e+100).

iii. Boolean literals

- There are only two possible values that a boolean value can have true and false. The values

of true and false do not convert into any numerical representation.

iv. Character literals

- A character literal is represented inside a pair of single quotes. All of the visible ASCII

Characters can be directly entered inside the quotes, such as ‗a‘, ‗Z‘, and ‗@‘.

- Some characters that are impossible to enter directly, so escape sequences used to enter this

kind of characters, such as ‗\n‘ denotes the newline character and ‗ \‖ ‘ denotes double quote.

v. String literals

- String literals enclosing a sequence of characters between a pair of double quotes. The

escape sequences that apply to character literals also work within string literals.

- Example: “I like Java”

“One\nTwo\nThree”

3. Define Variable? How to declare a variable and explain it?

The variable is the basic unit of storage in a java program. A variable is defined by the

combination of an identifier, a type, and an optional initializer.

Declaring a Variable:

- In Java, all variables must be declared before they can be used. The basic form of a variable

declaration is

type identifier[= value][, identifier[= value]…];

- The type denotes the data types or the name of a class of interface. The identifier is the name

of the variable.

- To declare more then one variable of the specified type, use a comma separated list.

- Rules for Identifier:

o Identifiers must not begin with a digit.

o White spaces are not allowed.

o Identifiers should not be a keyword.

o Uppercase and lowercase letters are used.

- Example: int a;

char c1, c2, c3;

int count=10;

4. Explain Type Conversion in Java?

It is common to assign a value of one type to a variable of another type is called type conversion. It

is classified into two types there are

i. Automatic type conversion (implicit conversion)

ii. Type casting (explicit conversion)

Automatic Type conversions:

When assigning one type of data to another type of variable, an automatic type conversion will take

place if the following two conditions are

- The two types are compatible.

- The destination type is larger then the source type.

The numeric types are not compatible with char or boolean. Also, char and boolean are not

compatible with each other.

Java also performs an automatic type conversion when storing a literal integer constant into

variables of type‘s byte, short, or long.

Example:

int i;

byte b;

//….

i = b; // valid automatic type conversion

b = i; // invalid (it requires explicit conversion)

Type casting:

In cases where java‘s automatic type conversions do not apply, we will need to use an explicit cost.

For example we will need to use a cast when assigning an int value to a byte variable.

A cast is simply an explicit type conversion. It has this general form:

(target-type) value

Here, target-type specifies the desired type to convert the specified value to. For example:

int i;

byte b;

//….

b = (byte) i;

When a floating point value is assigned to an integer type, the fractional component is lost.

Example, if the value 1.23 is assigned to integer, the resulting value is 1.

5. Define Constructor and explain it?

A constructor initializes an object immediately upon creation. It has the same name as the class.

Constructors have no return type, not even void. This is because the implicit return type of a class‘s

constructor in the class type itself.

Constructors can have parameters. Constructors classified depend on the parameter.

- Parameterized Constructor

- Default Constructor

In Parameterized Constructor, parameters receive the arguments passed to the constructor when an

object created. For example: class sample {

int a, b;

sample(int x, int y) {

a = x ;

b = y ;

}

int area() {

return a * b ;

}

}

class example {

public static void main(String args[]) {

sample ob = new sample(10, 12);

System.out.println(ob.area());

}

}

In this example an object ob creates a class sample and passing it the value 10 and 12. this

program displays the value 120.

The default constructor automatically initializes all instance variables to zero. Once we create own

constructor, the default constructor is no longer used.

6. What is Method overloading? Explain with example?

Tow or more methods within the same class that share the same name, as long as their parameter

declarations are different. The methods are said to be overload and the process is referred to as

method overloading.

Overloading methods must differ in the type and/or member of their parameters. While

overloaded methods may have different return types.

class overload {

void test() {

System.out.println(“No parameters”);

}

void test(int a) {

System.out.println(“int a: ” + a);

}

double test(double a) {

System.out.println(“double a: ” + a);

return a*a;

}

}

class demo {

public static void main(String args[]) {

overload ob = new overload();

double res;

ob.test();

ob.test(10);

res = ob.test(12.24);

}

}

In this example, test() is overloaded three times. The first method takes no parameters, the

second takes one integer parameter, and the third takes one double parameter and also returns a

double value.

7. What is Recursion? Write a example program?

Java supports recursion. Recursion is the attribute that allows a method to call itself. The

example of recursion is Factorial, Fibonacci series and etc.

When a method calls itself, new local variables and parameters are store on the stack.

A recursive call does not make a new copy of the method. Only the arguments are new.

As each recursive call returns, the old local variables and parameters are removed from the stack.

class Factorial {

int fact(int n) {

int result;

if (n==1) return 1;

result = fact(n-1) * n;

return result;

}

}

class Recursion {

public static void main(String args[]) {

Factorial f = new Factorial();

System.out.println(“Factorial of 4 is “ + f.fact(4));

}

}

The output is

Factorial of 4 is 24

In this example, an argument is 1, fact() returns 1, otherwise it returns the product of fact(n-1)*n.

To evaluate this expression, fact() is called with n-1. This procedure repeats until n equals 1.

8. Write notes on STATIC in Java?

When a class member is declared static, it may be accessed before any objects of its class are

created and without reference to any object. A static member is for most intents and purposes

global.

We may declare both methods and variables to be static. The most common use of static is to

declare the main() method. Method declared as static have several restrictions

- They can only call other static methods.

- They must access only static data.

- They cannot refer to this or super in any way.

We may also use static to create a block in which we may initialize static variables. A static

block is executed exactly once, when the class is first loaded.

static {

// static block code here

}

Outside of the class static variables and methods may be used independently of any object. We

need only specify the name of their class followed by the dot operator. The general form is:

classname.method()

Here, classname is the name of the class in which the static method is declared.

class StaticDemo {

int a= 3;

static int b;

static void test(int x) {

System.out.println(“x = “ + x);

System.out.println(“ a= “ + a);

System.out.println(“b = “ + b);

}

Static {

System.out.println(“Static block initialized”);

b = a * 4;

}

public static void main(String args[]) {

test(20);

}

}

The output is: Static block initialized

x = 20

a = 3

b = 12

9. What is Commend Line Arguments? Give example?

We will want to pass information into a program when we run it. This is accomplished by passing

commend line arguments to main(). A commend line argument is the information that directly

follows the program‘s name of the command line when it is executed.

They are stored as strings in the String array passed to main().

Example: class CommandLine {

public static void main(String args[]) {

for( int i=0; i<args.length; i++)

System.out.println(“args[“ + i + ”]: ” + args[i]);

}

}

The execution of this program is java CommandLine this is a test 100

The output is args[0]: this

args[1]: is

args[2]: a

args[3]: test

args[4]: 100

10 Mark Questions:

1. Define Array and explain with an example?

An array is a group of logically related elements that are referred to by a common mane. Arrays of

any type can be created and may have one or more dimensions. A specific element in an array is

accessed by its index.

Obtaining an array is a two step process.

1. We must declare a variable of the desired array type.

2. we must allocate the memory that will hold the array, using new, and assign it to the array

variable,

Arrays are classified into two types, there are

- One-Dimensional Array

- Multi-Dimensional Array

One-Dimensional Arrays

To create an array, first we must create an array variable of the desired type. The general form of a

one-dimensional array declaration is

type var-name[]; (or) type[] var-name;

Here, type declares the base type of the array. The base type for the array determines what type of

data the array will hold.

Once we have created the array variable, we need to allocate storage for the array using new.

Example int iarray[];

iarray = new int[12];

This example, array named as iarray and allocates for 12 elements. We can combine these two steps

as int iarray[] = new int[12]; (or) int[] iarray = new int[12];

Arrays can be initialized when they are declared. An array initializer is a list of comma separated

expressions surrounded by curly braces. The commas separate the value of the array elements.

The array will automatically be created large enough to hold the number of elements we specify in

the array initializer. There is no need to use new. For example:

int intx[] = { 1, 2, 3, 4, 5 };

Multi-Dimensional Arrays

To declare a multidimensional array variable, specify each additional index using another set of

square brackets. For example:

int twoDi[][] = new int [2][3];

This declaration allocates 2 x 3 array and assigns it to twoDi.

The following fragment allocates memory for the first dimension of twoDi when it is declared. It

allocates the second dimension manually.

int twoDi[][] = new int [2][];

twoDi[0] = new int[3];

twoDi[1] = new int[3];

Since multidimensional arrays are actually arrays of arrays, the length of each array is under our

control. For example:

int twoDi[][] = new int [2][];

twoDi[0] = new int[2];

twoDi[1] = new int[5];

This example the sizes of the second dimension are unequal.

2. Explain briefly about class in Java?

Class fundamentals:

Any concept we wish to implement in a Java program must be encapsulated with in a class.

A class is a template for an object and an object is an instance of a class. Very simple classes may

contain only code or only data, most real-world classes contain both code and data.

A class is declared using the class keyword. The general form of a class definition is shown here:

class classname {

type instance-variable1;

type instance-variable2;

//…

type instance-variableN;

type methodname1(parameter-list) {

// body of method

}

type methodname2(parameter-list) {

// body of method

}

//…

type methodnameN(parameter-list) {

// body of method

}

}

The data or variables, defined within a class are called instance variables. The code is contained

within methods. Collectively the methods and variables defined within a class are called members of

the class.

All methods are declared within classes, and all have this general form:

type methodname(parameter-list) {

// body of method

}

Here, type specifies the type of data returned by the method. This can be any void type, including

class types that we create. If the method does not return a value, its return type must be void.

The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are

essentially variables that receive the values of the arguments passed to the method when it is called.

If the method has no parameters, then the parameter list will be empty.

Example:

class sample {

int a, b;

int sum() {

return a+b;

}

}

This class named as sample. It contains two instance variables called a and b and one method named

as sum().

Declaring class objects:

When we create a class, we are creating a new data type. We can use this type to declare objects of

that type.

Obtaining of a class is a two-step process.

1. We must declare a variable of the class type.

2. We must acquire an actual, physical copy of the object and assign it to that variable. This is

accomplished using the new operator. The new operator dynamically allocates memory for

an object and returns a reference to it.

Here, we create an object ob to the class sample.

sample ob; // declare reference to object

ob= new sample(); // allocates an object

We can combine these two steps as

sample ob = new sample();

Once we have obtained a class object, we access its members using the dot (.) operator. The general

form: object-name.member-name

Example:

ob.a=10;

Unit II:

2 Marks:

1. What is operator and list out its types?

An operator is a symbol that tells the computer to perform certain mathematical or logical

manipulations.

Java provides a rich operator environment. It can be divided into the following groups

1. Arithmetic operators

2. Bitwise operators

3. Relational operators

4. Logical operators

5. Special operators

2. What are the two forms in increment and decrement?

The increment and decrement operators can appear both in postfix form (a++) and prefix form

(++a). In prefix form, the operand is incremented or decremented and the value is used in the

expression. For example: a = 5 and b = ++a, resulted b value is 6.

In postfix form, the previous value is obtained for the use in the expression and then the operand

is modified. For example: a = 5 and b = a++, resulted b value is 5.

3. What is assignment operator in Java?

The assignment operator is used to assign expression value or value to a variable, the general

form is var = expression;

Example: x = a + b;

4. What is the shorthand assignment operator?

Java allows convenient ―shorthand‖ for assignments of this general form: var = var op expression;

Its equal to: var op = expression;

Example: x += b;

5. Define Dot operator

The dot operator (.) is used to refer a member of a class. For example:

ob.sum();

ob.a=5;

6. Define The?: operator?

The general from is expression1 ? expression2 : expression3;

Here: expression1 is true, then expression2 is evaluated. Otherwise expression3 is evaluated.

Example: c = a!=0 ? b/a : 0;

7. Write the notes on this keyword?

The keyword this can be used inside any method to refer to the current object. In other words,

this is a reference to the object on which the method was invoked.

Example: this.a=10;

8. What is inheritance?

Inheritance means, one class to inherit the characteristics of another class. A class that is

inherited is called a superclass. The class that does the inheriting is called a subclass.

A subclass is a specialized version of a superclass.

To inherit a class to another class using the keyword extends. The general form is

class subclass-name extends superclass-name {

// body of class

}

9. Define about super keyword?

A subclass needs to refer to its immediate superclass, it can using the keyword super.

super has two general forms

i) To call superclass constructors

ii) To access the superclass members

The general form is super.member

Here, member can be either a method or an instance variable.

super is most applicable to situations in which member names of a subclass hide by the same

name in the superclass.

10. Define method overriding?

A method in a subclass has the same name, parameters and type signature as a method in its

superclass, then the method in the subclass is said to override the method in the superclass.

When an overridden method is called from within a subclass, it will always refer to the subclass

method, the superclass method will be hidden.

11. What is dynamic method dispatch?

Dynamic method dispatch is the mechanism by which the calls to overridden functions are

resolved at run time, rather then compile time.

12. What is an abstract class?

To define a superclass that declares its form and structure without providing a complete

implementation of its methods. Such a class is referred to as abstract class.

An abstract class is a class in which at least one abstract method.

13. What is an abstract method?

An abstract method is declared using the abstract specifier and has no defined implementation.

When a superclass contains an abstract method, any subclass must override the abstract method.

The general form of abstract method is abstract type methodname(parameter-list);

14. Difference between final and static?

final: final method can not be overridden in Java.

inal class can not be inheritable in Java.

final variables can‘t be modified.

static: A static method can access only static data. It can not access non-static data.

A static method can call only other static methods.

A static method and variable can be accessed directly by the class name and doesn‘t need any object.

Syntax : <class-name>.<method-name> or <class-name>.<variable-name>

A static method cannot refer to ―this‖ or ―super‖ keywords in anyway.

The static block, is a block of statement that will be executed when a class is first loaded.

15. How will you prevent overriding in a program? or Define final method?

Sometimes we will want to prevent method overridden, specify final as a modifier at the start of

its declaration.

Example: class A {

final void test() {

System.out.println(“This is a final method”);

}

}

class B {

void test() { \\ // ERROR Can’t override

System.out.println(“Illegal”);

}

}

In this example test() declared as final, it cannot be overridden in class B

16. How will you prevent Inheritance in a program? or Define final class?

Sometimes we will want to prevent a class from being inheritance. So, we add a final keyword at

the beginning of a class declaration.

Declaring a class as final implicitly declares all of its methods as final.

We can not declare a class as both abstract and final.

final class A {

// . . .

}

class B extends A { // ERROR Can’t inherit

// . . .

}

17. Define package?

Packages are containers for classes. They are used to keep the class name space

compartmentalized. For this reason, Java standard library is stored in a collection of packages.

The package is both a naming and a visibility control mechanism. We can define classes inside a

package that are not accessible by code outside that package.

18. What is Classpath?

The java compiler will consider as the root of any package hierarchy is controlled by

CLASSPATH. The default current working directory (―.‖) is usually in the CLASSPATH

environmental variable defined for the Java run-time system.

19. How the packages imported in java?

The import statement brings certain classes, or entire packages, into the current name space.

Once imported, a class can be referred to directly, using only its name.

In Java source file, import statements occur immediately following the package statement and

before any class definitions. The general form of the import statement is

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

A star indicates that java compiler should search this entire package when it encounters a class

name.

20. What is Interface?

An interface allows us to fully abstract a class from its implementation. Interfaces are

syntactically similar to classes, but their methods are declared without any body. They end with a

semicolon after the parameter list.

One class can implement any number of interfaces.

21. Write the uses of extends keyword?

The extends keyword use in two places, there are

i. Inherit Classes

ii. Inherit Interfaces

i) Inherit Classes:

The extends keyword used to she superclass of a class. Its general form is

class class-name extends inherited-class-mane {

// body of class

}

ii) Inherit Interfaces:

One interface to inherit another using 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.

22. Write the uses of implements keyword?

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

implement an interface, include the implements keyword. The general form of a class that

includes the implements statements:

Access class classname implements interface {

//class-body

}

Here, Access is either public or not used. If a class implements more then one interface, the

interfaces are separated with a comma.

23. Write the uses instanceof keyword?

The instanceof operator tests whether an object is an instance of a particular class or whether an

object implements a particular interface. The operator returns true or false.

Example: Component c = new Button(“Start”);

//…

if(c instanceof Button) {

//…

}

24. Write the uses of native keyword?

The keyword native specifies that a method is implemented in native code rather then Java

bytecode. Native code is the instruction that a CPU actually executes.

Example: Class Alarm {

public native void activate();

}

Most native code methods are implemented in C also.

25. Write the uses of new keyword?

The new operator creates an instance of an object. The general form is

class-var = new class-name();

Here, class-var is the name of a reference variable, and class-name is the name of the class. For

example

Button b = new Button(―Strat‖);

26. Write the uses of synchronized keyword?

The synchronized keyword provides two ways to coordinate the access of multiple threads to a

shared resource. First a method can be designed as synchronized. The general form is Synchronized ret-type method1(parameter-list) {

// statements to be synchronized

}

The second way that synchronized can be used is to designate a synchronized block. The general

form is Synchronized(object) {

// statements to be synchronized

}

27. Write the uses of throw and throws keyword?

The throws keyword is part of java‘s exception-handling mechanism. An exception is an object

that describes an exceptional condition that has occurred in a piece of code.

A throws clause is used in the method‘s declaration. A throws clause lists the types of

exceptions that a method might throw. The general form is

ret-type method-name(parameter-list) throws exception-list {

//…

}

5 Mark Questions:

1. Write notes on super keyword in Java?

- A subclass needs to refer to its immediate superclass, it can using the keyword super.

- super has two general forms

iii) To call superclass constructors

iv) To access the superclass members

i) To call superclass constructors

- A subclass can also a constructor method defined by its superclass using the following

form of super super(parameter-list);

Here, parameter-list specifies any parameters needed by the constructor in the

superclass.

ii) To call superclass constructors

- The general form is super.member

Here, member can be either a method or an instance variable.

- super is most applicable to situations in which member names of a subclass hide by the

same name in the superclass.

2. Write a short note on Access Control?

- How a class member can be accessed is determined by the access specifier that modifies its

declaration.

- Java‘s access specifiers are public, private, and protected. A default access level is also

defined.Both classes and packages provide access control, and interact with each other.

- Java provides these four categories of visibility for class members relative to packages.

o Subclass in the same package

o Non-subclasses in the same package

o Subclasses in different packages

o Classes that are neither in the same package nor subclasses

- In general, public grants access to anyone. private denies access to everyone except code

within that same class.

- protected provides access to all code in the same package and to subclasses in different

packages. The default access restricts access to within the same package.

private

member

default

member

protected

member

public

member

Visible within same class Yes Yes Yes Yes

Visible within same package by subclass No Yes Yes Yes

Visible within same package by non-subclass No Yes Yes Yes

Visible within different package by subclass No No Yes Yes

Visible within same package by non-subclass No No No Yes

3. Define Abstract Class? Write a program to illustrate Abstract Class?

To define a superclass that declares its form and structure without providing a complete

implementation of its methods. Such a class is referred to as abstract class.

An abstract class is a class in which at least one method has no implementation. A method is also

called abstract method. An abstract method is declared using the abstract specifier and has no

defined implementation.

When a superclass contains an abstract method, any subclass must override the abstract method.

The general form of abstract method is

abstract type methodname(parameter-list);

Any class that contains one or more abstract methods must also be declared as abstract class. There

can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with

the new operator.

Example: abstract class A {

abstract int square(int i);

void test() {

System.out.println(“This is a concrete method”);

}

}

class B extends A {

int square(int i) { return i * i; }

}

class AbstractDemo {

public static void main(String args[]) {

{

B b = new B();

System.out.println(“5 squared is “ + b.square(5));

b.test();

}

}

4. Describe the usage of the final keyword in Java?

Java supports the keyword final. Which has used in three places

- final Classes

- final Methods

- final variables

1) final Classes:

Sometimes we will want to prevent a class from being inheritance. So, we add a final keyword

at the beginning of a class declaration.

- Declaring a class as final implicitly declares all of its methods as final.

- We can not declare a class as both abstract and final.

final class A {

// . . .

}

class B extends A { // ERROR Can’t inherit

// . . .

}

2) final Methods:

Sometimes we will want to prevent method overridden, specify final as a modifier at the start

of its declaration.

Example: class A {

final void test() {

System.out.println(“This is a final method”);

}

}

class B {

void test() { \\ // ERROR Can’t override

System.out.println(“Illegal”);

}

}

In this example test() declared as final, it cannot be overridden in class B

3) final variables:

final variable is equivalent of a named constant. If we precede a variable declaration with final,

this variable cannot be modified.

We must initialize a final variable when it is declared.

Example: final int COUNT = 50;

5. Write notes on extends keyword?

The extends keyword use in two places, there are

i. Inherit Classes

ii. Inherit Interfaces

i. Inherit Classes:

The extends keyword used to she superclass of a class. Its general form is

class class-name extends inherited-class-mane {

// body of class

}

Example: class A {

int a;

}

class B {

int b;

}

Here, class B inherits class A.

ii. Inherit Interfaces:

One interface to inherit another using 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.

Example:

interface A {

void a1();

}

interface B {

void b1();

}

class Myclass implements B {

{

Public void a1() {

System.out.println(“Implementation a1().”);

}

Public void b1() {

System.out.println(“Implementation b1().”);

}

}

6. Explain try and catch keywords?

The try keyword is part of java‘s exception-handling mechanism. An exception is an object that

describes an exceptional condition that has occurred in a piece of code.

We want to monitor for exceptions are contained within a try block. If an exception occurs within

the try block, it is thrown. Our code can catch this exception using catch and handle it in some

rational manner.

System-generated exceptions are automatically thrown by the Java run-time system.

The general form of try, catch, throw, and finally is try {

// block of code to monitor for errors

throw ExceptionType;

}

catch (ExceptionType1 exOb) {

\\ exception handler

}

catch (ExceptionType2 exOb) {

\\ exception handler

}

//...

finally {

// block of code to be executed before try block ends

}

10 Mark Questions:

1. Explain briefly about the various types of Operators in Java?

An operator is a symbol that tells the computer to perform certain mathematical or logical

manipulations.

Java provides a rich operator environment. It can be divided into the following groups

i. Arithmetic operators

ii. Bitwise operators

iii. Relational operators

iv. Logical operators

v. Special operators

i. Arithmetic operators

- Arithmetic operators are used in mathematical expressions.

- The operands of the arithmetic operators must be of a mumeric type. We cannot use them on

boolean types, but we use char type (char type in Java is a subset of int).

Operator Result

+ Addition

- Subtraction (also unary minus)

* Multiplication

/ Division

% Modules

++ Increment

-- Decrement

- Addition, Subtraction, Multiplication, and Division are also called basic arithmetic operators.

- The unary minus (-) operator which negates its single operand. Example: x = -6 / 3

- The modulus operator (%) returns the remainder of a division. It can be applied to floating

point types as will as integer types. Example: x = 10 % 3

- The increment operator (++) increases its operand by 1.

- The decrement operator (--) decreases its operand by 1.

- The increment and decrement operators can appear both in postfix form (a++) and prefix

form (++a).

- In prefix form, the operand is incremented or decremented and the value is used in the

expression. For example: a = 5 and b = ++a, resulted b value is 6.

- In postfix form, the previous value is obtained for the use in the expression and then the

operand is modified. For example: a = 5 and b = a++, resulted b value is 5.

ii. Bitwise operators

- Those operators act upon the individual bits of their operands. It can be applied to the integer

types: long, int, short, char, and byte.

- Bitwise operators classified into two categories

i) Bitwise logical operator

ii) Bitwise shift operator

i) Bitwise logical operator:

Operator Result

~ Bitwise unary NOT

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

- The following table show the outcome of each operations

A B A&B A|B A^B ~A

0 0 0 0 0 1

0 1 0 1 1 1

1 0 0 1 1 0

1 1 1 1 0 0

ii) Bitwise shift operator:

Operator Result

>> Shift right

>>> Shift right, zero fill

<< Shift left

- The shift left operator (<<) shifts all of the bits in a value to the left a specified number of

times. The high-order bits are left and a zero is filled on the right side. The general form: value << num

- The shift right operator (>>) shifts all of the bits in a value to the right a specified number

of times. The low-order bits are left and a zero is filled on the left side. But sign bit is

preserved. The general form:

value >> num

- The shift right, zero fill operator (>>>) left the number of the bits left side(low order bits)

and fill the zero on the right sign (high order bit) include sign bit.

- Example: x = a << b

iii. Relational operators

- The relational operators ascertain the relationship between two operands.

- The outcome of these operations is a boolean value. These operators are mostly used in the

condition and looping statements.

Operator Result

== Equal to

!= Not equal to

> Greater then

< Less then

>= Greater then or equal to

<= Less then or equal to

iv. Boolean logical operators

- It‘s operating only on boolean operands, all of the binary logical operators combine two

boolean values to form a resultant boolean value.

Operator Result

& Logical AND

| Logical OR

^ Logical XOR

! Logical unary NOT

|| Short-circuit OR

&& Short-circuit AND

== Equal to

!= Not equal to

?: Ternary if-then-else

- The logical AND, OR, XOR, and unary NOT operators operate on boolean values.

- The logical AND (&) and OR ( | ) operators always evaluate the expression on both left and

right sides of the operators. But, the short-circuit OR (||) and short-circuit AND(&&)

operators do not always evaluate the expression on the right side of the operator.

- Example: if((income>=40000) && (age >= 65)) {

//...

}

v. Assignment operators

- The assignment operator is used to assign expression value or value to a variable, the general

form is var = expression;

- Java allows convenient ―shorthand‖ for assignments of this general form: var = var op expression;

- Its equal to: var op = expression;

- for example:

a=a+b; its equal to a+=b;

Operator Result

+= Addition assignment

-= Subtraction assignment

*= Multiplication assignment

/= Division assignment

%= Modulus assignment

&= AND assignment

|= OR assignment

^= XOR assignment

>>= Shift right assignment

>>>= Shift right, zero fill assignment

<<= Shift left assignment

vi. The ?: operator:

- The general from is expression1 ? expression2 : expression3;

- expression1 is true, then expression2 is evaluated. Otherwise expression3 is evaluated.

- Example: c = a!=0 ? b/a : 0;

vii. The new operator:

- The new operator creates an instance of an object. The general form is

class-var = new class-name();

Here, class-var is the name of a reference variable, and class-name is the name of the class

being instantiated. For example

Button b = new Button(―Strat‖);

viii. The dot operator:

- The dot operator (.) is used to refer a member of a class. For example:

ob.sum();

ob.a=5;

2. Explain Inheritance with appropriate example?

- Inheritance means, one class to inherit the characteristics of another class. A class that is

inherited is called a superclass. The class that does the inheriting is called a subclass.

- A subclass is a specialized version of a superclass.

- To inherit a class to another class using the keyword extends. The general form is

class subclass-name extends superclass-name {

// body of class

}

super:

- A subclass needs to refer to its immediate superclass, it can using the keyword super.

- super has two general forms

i) To call superclass constructors

ii) To access the superclass members

i) To call superclass constructors

- A subclass can also a constructor method defined by its superclass using the following

form of super super(parameter-list);

super class

sub class

super class

sub class 1

sub class 2

Here, parameter-list specifies any parameters needed by the constructor in the

superclass.

ii) To call superclass constructors

- The general form is super.member

Here, member can be either a method or an instance variable.

- super is most applicable to situations in which member names of a subclass hide by the

same name in the superclass.

Inheritance types:

Inheritance classified into following types, there are

i) Simple inheritance

- It contains only one superclass and one subclass.

ii) Multilevel inheritance

- A subclass becomes a superclass of another subclass.

iii) Hierarchical inheritance

- One superclass into multiple subclasses.

iv) Multiple inheritance

- Multiple super classes into one subclass. But

java does not support this type of inheritance directly.

v) Hybrid inheritance

- It denotes combination of any two or more type of inheritance.

Example:

class A {

int i;

void show() {

System.out.println(“super class: ” +i);

}

}

class B {

int i,j;

super class

sub class 1 sub class 2

super class 1 super class 2

sub class

void show() {

super.show();

System.out.println(“sub class: ” +j);

}

}

class Inheritance {

public static void main(String args[]) {

A sob = new A();

B ob = new B();

Sob.i=10;

Ob.j=20;

Sob.show();

Ob.show();

}

}

3. Define Packages and Explain it?

- Packages are containers for classes. They are used to keep the class name space

compartmentalized. For this reason, Java standard library is stored in a collection of packages.

- The package is both a naming and a visibility control mechanism. We can define classes inside a

package that are not accessible by code outside that package.

- We can also define class members that are exposed only to other members of the same package.

Defining a Package:

- To create a package, simply include a package keyword as the first statement in java source file.

The package statement defines a name space in which classes are stored.

- The general form of the package statement is package pkg;

Here, pkg is the name of the package.

- Java uses file system directories to store packages. For example, a package MyPack must be

stored in a directory MyPack. The directory name must match the package name exactly.

- We can create a hierarchy of packages. To do so, simply separate each package name from the

one above it using a period.

- The general form of a multilevel package statement is package pkg1[.pkg2[.pkg3]];

CLASSPATH

- The java compiler will consider as the root of any package hierarchy is controlled by

CLASSPATH.

- The default current working directory (―.‖) is usually in the CLASSPATH environmental

variable defined for the Java run-time system.

Importing Packages:

- The import statement brings certain classes, or entire packages, into the current name space.

Once imported, a class can be referred to directly, using only its name.

- In Java source file, import statements occur immediately following the package statement and

before any class definitions.

- The general form of the import statement is

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

Here, pkg1 is the name of a top-level package, pkg2 is the name of a subordinate package

inside the outer package separated by a dot (.).

Finally, an explicit classname or a star(*) is specified; a star indicates that java compiler

should search this entire package when it encounters a class name.

Example: package MyPack;

public class Balance{

String name;

float bal;

public Balance(String s, float f) {

name=n;

bal=f;

}

public void show() {

System.out.println(name +”: Rs: “ +bal);

}

}

import MyPack.*;

class Test {

public static void main(String args[]) {

Balance ob = new Balance(“BCA”, 99.88);

Ob.show();

}

}

Here, Test import a package MyPack and to make use of the Balance class.

4. What is interface? Briefly explain it.

- An interface allows us to fully abstract a class from its implementation.

- Interfaces are syntactically similar to classes, but their methods are declared without any body.

They end with a semicolon after the parameter list.

- One class can implement any number of interfaces.

Defining an interface:

- An interface is defined much like a class. The general form of an interface is 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;

}

- Here, access is either public or not used. When no access specifier is included, then default

access results and the interface is available only to other members of the package in which it is

declared.

- When it is declared as public, the interface can be used by any other code.

- name is the name of the interface and can be any valid identifier.

- Each class that implements an interface must implement all of the methods.

- Variables can be declared inside of interface declarations. They are implicitly final and static,

meaning they cannot be changed by the implementing class. They must also be initialized with a

constant value.

- All methods and variables are implicitly public if the interface itself is declared as public.

- Example: interface Series {

int nextNumber();

void setSort(int i);

}

Here, Series is the name of the interface. It defines two methods, called nextNumber()and setSort().

Importing Interfaces:

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

implement an interface, include the implements keyword.

- The general form of a class that includes the implements statements:

Access class classname implements interface {

//class-body

}

- Here, Access is either public or not used. If a class implements more then one interface, the

interfaces are separated with a comma.

- The methods that implement an interface must be declared public.

- For example: class MySeries implements Series {

int num;

public int nextNumber(){

num+=2;

return num;

}

public void setStart(int i) {

num=i;

}

class TestSeries {

public static void main(String args[]) { MySeries ob = new MySeries();

ob.setStart(10);

System.out.println(ob.nextNumber() +” “ + ob.nextNumber());

}

}

UNIT – III

LANGUAGE PACKAGES:

java.lang is automatically imported into all programs. It contains classes and interfaces that are

fundamental to virtually all of Java programming. It is Java‘s most widely used package.

java.lang includes the following classes:

Boolean Integer Short

Byte Long String

Character Math StringBuffer

Class Number System

ClassLoader Object Thread

Compiler Process ThreadGroup

Double Runtime Throwable

Float SecurityManager Void

java.lang defines the following interfaces:

Cloneable Runnable

Number

The abstract class Number defines a superclass that is implemented by the classes that wrap the

numeric type‘s byte, short, int, long, float, and double. Number has abstract methods that return the

value of the object in each of the different number formats. These methods are shown here:

byte byteValue( ) - returns the value as a byte

double doubleValue( ) - returns the value as a double

float floatValue( ) - returns the value as a float

int intValue( ) - returns the value as a int

long longValue( ) - returns the value as a long

short shortValue( ) - returns the value as a short

The values returned by these methods can be rounded.

Number has six concrete subclasses that hold explicit values of each numeric type: Double, Float,

Byte, Short, Integer, and Long.

Byte, Short, Integer, and Long

The Byte, Short, Integer, and Long classes are wrappers for byte, short, int, and long integer types,

respectively. Their constructors are shown here:

Byte(byte num)

Byte(String str) throws NumberFormatException

Short(short num)

Short(String str) throws NumberFormatException

Integer(int num)

Integer(String str) throws NumberFormatException

Long(long num)

Long(String str) throws NumberFormatException

These objects can be constructed from numeric values or from strings that contain valid whole

number values.

The following constants are defined:

MIN_VALUE - Minimum value

MAX_VALUE - Maximum value

TYPE - The Class object for byte, short, int, or long

Method Description

byte byteValue( ) Returns the value of the invoking object as a byte.

static Byte decode(String str) throws

NumberFormatException

Returns a Byte object that contains the value specified

by the string in str.

double doubleValue( ) Returns the value of the invoking object as a double.

boolean equals(Object Obj) Returns true if the invoking object is equivalent to

Obj. Otherwise, it returns false.

float floatValue( ) Returns the value of the invoking object as a float.

int hashCode( ) Returns the hash code for the invoking object.

int intValue( ) Returns the value of the invoking object as an int.

long longValue( ) Returns the value of the invoking object as a long.

static byte parseByte(String str) throws

NumberFormatException

Returns the byte equivalent of the number contained

in the string specified by str using radix 10.

static int parseInt(String str) throws

NumberFormatException

Returns the int equivalent of the number contained in

the string specified by str using radix 10.

static int parseLong(String str) throws

NumberFormatException

Returns the Long equivalent of the number contained

in the string specified by str using radix 10.

static int parseShort(String str) throws

NumberFormatException

Returns the Short equivalent of the number contained

in the string specified by str using radix 10.

short shortValue( ) Returns the value of the invoking object as a short.

String toString( ) Returns the string equivalent of the invoking object.

static byte valueOf(String str) throws

NumberFormatException

Returns the Byte object that contains the value

specified by the string in str.

Example:

\\...

str = br.readLine();

i = Integer.parseInt(str);

\\...

Double and Float

Double and Float are wrappers for floating-point values of type double and float, respectively. The

constructors for Double are shown here:

Double(double num)

Double(String str) throws NumberFormatException

Double objects can be constructed with a double value or a string containing a floating-point value.

The constructors for Float are shown here:

Float(double num)

Float(float num)

Float(String str) throws NumberFormatException

The float objects can be constructed with values of type float or double. They can also be constructed

from the string representation of a floating-point number.

Both Float and Double define the following constants:

MAX_VALUE - Maximum positive value

MIN_VALUE - Minimum positive value

NaN - Not a number

POSITIVE_INFINITY - Positive infinity

NEGATIVE_INFINITY - Negative infinity

TYPE - The Class object for float or double

Method Description

byte byteValue( ) Returns the value of the invoking object as a byte.

double doubleValue( ) Returns the value of the invoking object as a

double.

Static long doubleToLongBits(double num) Returns the IEEE-compatible, double-precision bit

pattern that corresponds to num.

static double longBitsToDouble(long num) Returns double equivalent of the IEEE-compatible,

double-precision bit pattern specified by num.

boolean equals(Object Obj) Returns true if the invoking object is equivalent to

Obj. Otherwise, it returns false.

static int floatToIntBits(float num) Returns the IEEE-compatible, single-precision bit

pattern that corresponds to num.

float floatValue( ) Returns the value of the invoking object as a float.

int hashCode( ) Returns the hash code for the invoking object.

static float intBitsToFloat(int num) Returns float equivalent of the IEEE-compatible,

single-precision bit pattern specified by num.

int intValue( ) Returns the value of the invoking object as an int.

boolean isInfinite( ) Returns true if the invoking object contains an

infinite value. Otherwise, it returns false.

static boolean isInfinite(float num) Returns true if num specifies an infinite value.

Otherwise, it returns false.

boolean isNaN( ) Returns true if the invoking object contains a value

that is not a number. Otherwise, it returns false.

static boolean isNaN(float num) Returns true if num specifies a value that is not a

number. Otherwise, it returns false.

long longValue( ) Returns the value of the invoking object as a long.

static double parseDouble(String str) throws

NumberFormatException

Returns the double equivalent of the number

contained in the string specified by str using radix

10.

static float parseFloat(String str) throws

NumberFormatException

Returns the float equivalent of the number

contained in the string specified by str using radix

10.

short shortValue( ) Returns the value of the invoking object as a short.

String toString( ) Returns the string equivalent of the invoking object.

static Float valueOf(String str) throws

NumberFormatException

Returns the Float object that contains the value

specified by the string in str.

Example: Float d3 = new Float (1/0.);

Double d1 = new Double(3.14159);

Double d2 = new Double("314159E-5");

System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN());

System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2));

//...

Boolean

Boolean is a very thin wrapper around boolean values. It contains the constants TRUE and FALSE,

which define true and false Boolean objects. Boolean also defines the TYPE field, which is the Class

object for boolean. Boolean defines these constructors:

Boolean(boolean boolValue)

Boolean(String Str)

In the first version, boolValue must be either true or false. In the second version, if Str contains the

string ―true‖ (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will

be false.

Method Description

boolean booleanValue( ) Returns boolean equivalent.

boolean equals(Object Obj) Returns true if the invoking object is equivalent to Obj.

Otherwise, it returns false.

static boolean getBoolean(String

propertyName)

Returns true if the system property specified by

propertyNameis true. Otherwise, it returns false.

int hashCode( ) Returns the hash code for the invoking object.

String toString( ) Returns the string equivalent of the invoking object.

static Boolean valueOf(String Str) Returns true if Str contains the string ―true‖ (in uppercase or

lowercase). Otherwise, it returns false.

Character Character is a simple wrapper around a char. The constructor for Character is Character(char ch)

Here, ch specifies the character that will be wrapped by the Character object being created.

The Character class defines several constants, including the following:

MAX_RADIX - The largest radix

MIN_RADIX - The smallest radix

MAX_VALUE - The largest character value

MIN_VALUE - The smallest character value

TYPE - The Class object for char

Method Description

char charValue( ) It returns the character value contained in a Character object

static int digit(char digit, int radix) Returns the integer value associated with the specified

character according to the specified radix.

boolean equals(Object Obj) Returns true if the invoking object is equivalent to Obj.

Otherwise, it returns false.

int hashCode( ) Returns the hash code for the invoking object.

static boolean isDigit(char ch) Returns true if ch is a digit. Otherwise, it returns false.

static boolean isLetter(char ch) Returns true if ch is a letter. Otherwise, it returns false.

static boolean isLowerCase(char

ch)

Returns true if ch is a lowercase letter. Otherwise, it returns

false.

static boolean isUpperCase(char ch) Returns true if ch is an uppercase letter. Otherwise, it returns

false.

static boolean isWhitespace(char

ch)

Returns true if ch is white space. Otherwise, it returns false.

static char toLowerCase(char ch) Returns lowercase equivalent of ch.

static char toUpperCase(char ch) Returns uppercase equivalent of ch.

String toString( ) Returns the string equivalent of the invoking object.

Example:

class IsDemo {

public static void main(String args[]) {

char a[] = {'a', 'b', '5', '?', 'A', ' '};

for(int i=0; i<a.length; i++) {

if(Character.isDigit(a[i]))

System.out.println(a[i] + " is a digit.");

if(Character.isLetter(a[i]))

System.out.println(a[i] + " is a letter.");

if(Character.isWhitespace(a[i]))

System.out.println(a[i] + " is whitespace.");

if(Character.isUpperCase(a[i]))

System.out.println(a[i] + " is uppercase.");

if(Character.isLowerCase(a[i]))

System.out.println(a[i] + " is lowercase.");

}

}

}

Process

The abstract Process class encapsulates a process—that is, an executing program. It is used primarily

as a superclass for the type of objects created by exec( ) in the Runtime class. Process contains the

abstract methods are

Method Description

void destroy( ) Terminates the process.

int exitValue( ) Returns an exit code obtained from a subprocess.

InputStream getErrorStream( ) Returns an input stream that reads input from the process err

output stream.

InputStream getInputStream( ) Returns an input stream that reads input from the process out

output stream.

OutputStream

getOutputStream( )

Returns an output stream that writes output to the process in input

stream.

int waitFor( ) throws

InterruptedException

Returns the exit code returned by the process. This method does

not return until the process on which it is called terminates.

Runtime

The Runtime class encapsulates the run-time environment. We cannot instantiate a Runtime object.

However, we can get a reference to the current Runtime object by calling the static method

Runtime.getRuntime( ).

Once we obtain a reference to the current Runtime object, we can call several methods that control

the state and behavior of the Java Virtual Machine.

Applets and other untrusted code typically cannot call any of the Runtime methods without raising a

SecurityException. Commonly used methods defined by Runtime are shown

Method Description

Process exec(String progName)

throws IOException

Executes the program specified by progName as a separate

process. An object of type Process is returned that describes the

new process.

Process exec(String progName,

String environment[ ]) throws

IOException

Executes the program specified by progName as a separate

process with the environment specified by environment. An object

of type Process is returned that describes the new process.

Process exec(String

comLineArray[ ]) throws

IOException

Executes the command line specified by the strings in

comLineArrayas a separate process. An object of type Process is

returned that describes the new process.

Process exec(String

comLineArray[ ], String

environment[ ]) throws

IOException

Executes the command line specified by the strings in

comLineArray as a separate process with the environment

specified by environment. An object of type Process is returned

that describes the new process.

void exit(int exitCode) Halts execution and returns the value of exitCode to the parent

process. By convention, 0 indicates normal termination. All other

values indicate some form of error.

long freeMemory( ) Returns the approximate number of bytes of free memory

available to the Java run-time system.

void gc( ) Initiates garbage collection.

static Runtime getRuntime( ) Returns the current Runtime object.

void halt(int code) Immediately terminates the Java Virtual Machine. No termination

threads or finalizers are run. The value of code is returned to the

invoking process.

void load(String

libraryFileName)

Loads the dynamic library whose file is specified by

libraryFileName, which must specify its complete path.

void loadLibrary(String

libraryName)

Loads the dynamic library whose name is associated with

libraryName.

void runFinalization( ) Initiates calls to the finalize( ) methods of unused but not yet

recycled objects.

long totalMemory( ) Returns the total number of bytes of memory available to the

program.

void traceInstructions(boolean

traceOn)

Turns on or off instruction tracing, depending upon the value of

traceOn. If traceOn is true, the trace is displayed. If it is false,

tracing is turned off.

void traceMethodCalls(boolean

traceOn)

Turns on or off method call tracing, depending upon the value of

traceOn. If traceOn is true, the trace is displayed. If it is false,

tracing is turned off.

Example:

class MemoryDemo {

public static void main(String args[]) {

Runtime r = Runtime.getRuntime();

long mem1;

Integer someints[] = new Integer[1000];

System.out.println("Total memory is: " + r.totalMemory());

mem1 = r.freeMemory();

System.out.println("Initial free memory: " + mem1);

r.gc();

mem1 = r.freeMemory();

System.out.println("Free memory after garbage collection: " + mem1);

for(int i=0; i<1000; i++)

someints[i] = new Integer(i); // allocate integers

}

}

Sample output from this program is shown here:

Total memory is: 1048568

Initial free memory: 751392

Free memory after garbage collection: 841424

System

The System class holds a collection of static methods and variables. The standard input, output, and

error output of the Java run time are stored in the in, out, and err variables.

Method Description

static long currentTimeMillis( ) Returns the current time in terms of milliseconds since

midnight, January 1, 1970.

static void exit(int exitCode) Halts execution and returns the value of exitCode to the

parent process (usually the operating system). By

convention, 0 indicates normal termination. All other

values indicate error.

static void gc( ) Initiates garbage collection.

static String getenv(String which) Returns the value associated with the environmental

variable passed in which.

static Properties getProperties( ) Returns the properties associated with the Java run-time

system.

static String getProperty(String which) Returns the property associated with which. A null object

is returned if the desired property is not found.

static String getProperty(String which,

String default)

Returns the property associated with which. If the desired

property is not found, default is returned.

static SecurityManager

getSecurityManager( )

Returns the current security manager or a null object if no

security manager is installed.

static void load(String

libraryFileName)

Loads the dynamic library whose file is specified by

libraryFileName, which must specify its complete path.

static void loadLibrary(String

libraryName)

Loads the dynamic library whose name is associated with

libraryName.

static void runFinalization( ) Initiates calls to the finalize( ) methods of unused but not

yet recycled objects.

static void setErr(PrintStream eStream) Sets the standard err stream to eStream.

static void setIn(InputStream iStream) Sets the standard in stream to iStream.

static void setOut(PrintStream oStream Sets the standard out stream to oStream.

static void setProperties(Properties

sysProperties)

Sets the current system properties as specified by

sysProperties.

static void setSecurityManager(

SecurityManager secMan)

Sets the security manager to that specified by secMan.

Example:

//...

start = System.currentTimeMillis();

System.out.println(start);

//...

Object

Object is a superclass of all other classes. Object defines the methods shown in Table.

Method Description

Object clone( ) throws

CloneNotSupportedException

Creates a new object that is the same as the invoking object.

boolean equals(Object object) Returns true if the invoking object is equivalent to object.

void finalize( ) throws Throwable Default finalize( ) method. This is usually overridden by

subclasses.

final native Class getClass( ) Obtains a Class object that describes the invoking object.

int hashCode( ) Returns the hash code associated with the invoking object.

final void notify( ) Resumes execution of a thread waiting on the invoking object.

final void notifyAll( ) Resumes execution of all threads waiting on the invoking

object.

String toString( ) Returns a string that describes the object.

final void wait( ) throws

InterruptedException

Waits on another thread of execution.

final void wait(long milliseconds)

throws InterruptedException

Waits up to the specified number of milliseconds on another

thread of execution.

final void wait(long milliseconds,

int nanoseconds) throws

InterruptedException

Waits up to the specified number of milliseconds plus

nanoseconds on another thread of execution.

Example:

try {

// call clone in Object.

return super.clone();

} catch(CloneNotSupportedException e) {

System.out.println("Cloning not allowed.");

return this;

}

The Cloneable Interface

The clone( ) method generates a duplicate copy of the object on which it is called. Only classes that

implement the Cloneable interface can be cloned.

The Cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy

of an object (that is, a clone) to be made. If we try to call clone( ) on a class that does not implement

Cloneable, a CloneNotSupportedException is thrown.

When a clone is made, the constructor for the object being cloned is not called. A clone is simply an

exact copy of the original.

Class

Class encapsulates the run-time state of an object or interface. Objects of type Class are created

automatically, when classes are loaded. We cannot explicitly declare a Class object.

Generally, we obtain a Class object by calling the getClass( ) method defined by Object. Class is a

generic type that is declared as shown here:

class Class<T>

Here, T is the type of the class or interface represented.

Method Description

static native Class

forName(String name) throws

ClassNotFoundException

Returns a Class object given its complete name.

native Class[ ] getInterfaces( ) When invoked on an object, this method returns an array of the

interfaces implemented by the class type of the object. When

invoked on an interface, this method returns an array of

interfaces extended by the interface.

String getName( ) Returns the complete name of the class or interface of the

invoking object.

native Class getSuperclass( ) Returns the superclass of the invoking object. The return value

is null if the invoking object is of type Object.

boolean isInterface( ) Returns true if the invoking object is an interface. Otherwise, it

returns false.

native Object newInstance( )

IllegalAccessException,

InstantiationException

Creates a new instance (i.e., a new object) that is of the same

type as the invoking object. This is equivalent to using new with

the class‘ default constructor. The new object is returned.

Example: class X {

int a;

float b;

}

class Y extends X {

double c;

}

class RTTI {

public static void main(String args[]) {

X x = new X();

Y y = new Y();

native Class clObj;

clObj = y.getClass();

System.out.println("y is object of type: " +clObj.getName());

clObj = clObj.getSuperclass();

System.out.println("y's superclass is " +clObj.getName());

}

}

Math

The Math class contains all the floating-point functions that are used for geometry and trigonometry,

as well as several general-purpose methods. Math defines two double constants: E (approximately

2.72) and PI (approximately 3.14).

Method Description

static double sin(double arg) Returns the sine of the angle specified by arg in radians.

static double cos(double arg) Returns the cosine of the angle specified by arg in radians.

static double tan(double arg) Returns the tangent of the angle specified by arg in

radians.

static double asin(double arg) Returns the angle whose sine is specified by arg.

static double acos(double arg) Returns the angle whose cosine is specified by arg.

static double atan(double arg) Returns the angle whose tangent is specified by arg.

static double exp(double arg) Returns e to the arg.

static double log(double arg) Returns the natural logarithm of arg.

static double pow(double y, double x) Returns y raised to the x; for example, pow(2.0, 3.0)

returns 8.0.

static double sqrt(double arg) Returns the square root of arg.

static int abs(int arg) Returns the absolute value of arg.

static long abs(long arg) Returns the absolute value of arg.

static float abs(float arg) Returns the absolute value of arg.

static double abs(double arg) Returns the absolute value of arg.

static double ceil(double arg) Returns the smallest whole number greater than or equal to

arg.

static double floor(double arg) Returns the largest whole number less than or equal to arg.

static int max(int x, int y) Returns the maximum of x and y.

static long max(long x, long y) Returns the maximum of x and y.

static float max(float x, float y) Returns the maximum of x and y.

static double max(double x, double y) Returns the maximum of x and y.

static int min(int x, int y) Returns the minimum of x and y.

static long min(long x, long y) Returns the minimum of x and y.

static float min(float x, float y) Returns the minimum of x and y.

static double min(double x, double y) Returns the minimum of x and y.

static int round(float arg) Returns arg rounded up to the nearest int.

static long round(double arg) Returns arg rounded up to the nearest long.

static double IEEEremainder(double

dividend, double divisor)

Returns the remainder of dividend/ divisor.

static double random( ) Returns a pseudorandom number between 0 and 1.

Thread, ThreadGroup, and Runnable

The Runnable interface and the Thread and ThreadGroup classes support multithreaded

programming. Each is examined next.

The Runnable Interface

The Runnable interface must be implemented by any class that will initiate a separate thread of

execution. Runnable only defines one abstract method, called run( ), which is the entry point to the

thread. It is defined like this: void run( )

Threads that we create must implement this method.

Thread

Threadcreatesanewthreadofexecution.Itdefinesthefollowingcommonlyusedconstructors:

Thread( )

Thread(RunnablethreadOb)

Thread(RunnablethreadOb, String threadName)

Thread(String threadName)

Thread(ThreadGroup groupOb, Runnable threadOb)

Thread(ThreadGroup groupOb, Runnable threadOb, String threadName)

Thread(ThreadGroup groupOb, String threadName)

threadOb is an instance of a class that implements the Runnable interface and defines where

execution of the thread will begin. The name of the thread is specified by threadName. When a name

is not specified, one is created by the Java Virtual Machine. GroupOb specifies the thread group to

which the new thread will be long. When no thread group is specified, the new thread belongs to the

same group as the parent thread. The following constants are defined by Thread:

MAX_PRIORITY, MIN_PRIORITY, and NORM_PRIORITY

As expected, these constants specify the maximum, minimum, and default thread priorities.

Method Description

static int activeCount( ) Returns the number of threads in the group to which the

thread belongs.

final void checkAccess( ) Causes the security manager to verify that the current thread

can access and/or change the thread on which checkAccess(

) is called.

static Thread currentThread( ) Returns a Thread object that encapsulates the thread that

calls this method.

final void destroy() Destroys the thread on which it is called.

static void dumpStack( ) Displays the call stack for the thread.

static int enumerate(Thread threads[

])

Puts copies of all Thread objects in the current thread‘s

group into threads. The number of threads is returned.

final String getName( ) Returns the thread‘s name.

final int getPriority( ) Returns the thread‘s priority setting.

void interrupt( ) Interrupts the thread.

static boolean interrupted( ) Returns true if the currently executing thread has been

scheduled for interruption. Otherwise, it returns false.

final boolean isDaemon( ) Returns true if the thread is a daemon thread. Otherwise, it

returns false.

boolean isInterrupted( ) Returns true if the thread is interrupted. Otherwise, it returns

false.

final void join( ) throws

InterruptedException

Waits until the thread terminates.

final void join(long milliseconds)

throws InterruptedException

Waits up to the specified number of milliseconds for the

thread on which it is called to terminate.

void run( ) Begins execution of a thread.

final void setDaemon(boolean state) Flags the thread as a daemon thread.

final void setName(String

threadName)

Sets the name of the thread to that specified by threadName.

final void setPriority(int priority) Sets the priority of the thread to that specified by priority.

void start( ) Starts execution of the thread.

final void stop() throws

SecurityException

Terminates the invoking object.

String toString( ) Returns the string equivalent of a thread.

static void yield( ) The calling thread yields the CPU to another thread.

ThreadGroup

ThreadGroup creates a group of threads. It defines these two constructors:

ThreadGroup(String groupName)

ThreadGroup(ThreadGroup parentOb, String groupName)

For both forms, groupName specifies the name of the thread group. The first version creates a new

group that has the current thread as its parent.

Thread groups offer a convenient way to manage groups of threads as a unit. This is particularly

valuable in situations in which we want to suspend and resume a number of related threads.

Method Description

static int activeCount( ) Returns the number of threads in the group to which the thread

belongs.

static int activeGroupCount( ) Returns the number of groups for which the invoking thread is a

parent.

final void checkAccess( ) Causes the security manager to verify that the current thread can

access and/or change the thread on which checkAccess( ) is called.

final void destroy() Destroys the thread on which it is called.

static int enumerate(Thread

group[ ])

The threads that comprise the invoking thread group are put into the

grouparray.

int enumerate(Thread group[

], boolean all)

The threads that comprise the invoking thread group are put into the

grouparray. If all is true, then threads in all subgroups of the thread

are also put into group.

int enumerate(ThreadGroup

group[ ])

The subgroups of the invoking thread group are put into the

grouparray

int enumerate(ThreadGroup

group[ ], boolean all)

The subgroups of the invoking thread group are put into the

grouparray. If all is true, then all subgroups of the subgroups (and

so on) are also put into group.

final String getName( ) Returns the thread‘s name.

final int getMaxPriority( ) Returns the maximum priority setting for the group.

final boolean isDaemon( ) Returns true if the thread is a daemon thread. Otherwise, it returns

false.

boolean isDestroyed( ) Returns true if the group has been destroyed. Otherwise, it returns

false.

void list( ) Displays information about the group.

final void setDaemon(boolean

state)

Flags the thread as a daemon thread.

final void setMaxPriority(int

priority)

Sets the maximum priority of the invoking group to priority

final void stop() throws

SecurityException

Terminates the invoking object.

String toString( ) Returns the string equivalent of a thread.

Example:

//...

public void run() {

try {

for(int i = 5; i > 0; i--) {

System.out.println(getName() + ": " + i);

Thread.sleep(1000);

}

} catch (Exception e) {

System.out.println("Exception in " + getName());

}

System.out.println(getName() + " exiting.");

}

//...

The Utility Classes and Interfaces

The java.util has classes that generate pseudorandom numbers, manage date and time, observe

events, manipulate sets of bits, tokenize strings, and handle formatted data. The java.util package

also contains one of Java‘s most powerful subsystems:

The Collections Framework. The Collections Framework is a sophisticated hierarchy of interfaces

and classes that provide state-of-the-art technology or managing groups of objects. It merits close

attention by all programmers.

BitSet

Calendar

Date

Dictionary

EventObject

GregorianCalendar

Hashtable

ListResourceBundle

Locale

Observable

Properties

PropertyResourceBundle

Random

ResourceBundle

SimpleTimeZone

Stack

StringTokenizer

TimeZone

Vector

The interfaces defined by java.util are shown next:

Enumeration EventListener Observer

The Enumeration Interface

The Enumeration interface defines the methods by which we can enumerate (obtain one at a time)

the elements in a collection of objects. This legacy interface has been superseded by Iterator.

Enumeration specifies the following two methods:

boolean hasMoreElements( )

object nextElement( )

When implemented, hasMoreElements() must return true while there are still more elements to

extract, and false when all the elements have been enumerated. nextElement() returns the next object

in the enumeration. That is, each call to nextElement( ) obtains the next object in the enumeration. It

throws NoSuchElementException when the enumeration is complete.

Vector

Vector implements a dynamic array. It is similar to Array List, but with two differences: Vector is

synchronized, and it contains many legacy methods that are not part of the Collections Framework.

All vectors start with an initial capacity. After this initial capacity is reached, the next time that we

attempt to store an object in the vector, the vector automatically allocates space for that object plus

extra room for additional objects. By allocating more than just the required memory, the vector

reduces the number of allocations that must take place.

This reduction is important, because allocations are costly in terms of time. The amount of extra

space allocated during each reallocation is determined by the increment that we specify when we

create the vector. If we don‘t specify an increment, the vector‘s size is doubled by each allocation

cycle.

Vector defines these protected data members:

int capacityIncrement; int elementCount; Object[ ] elementData;

Here are theVectorconstructors:

Vector( )

Vector(int size)

Vector(int size, int incr)

The first form creates a default vector, which has an initial size of 10. The second form creates a

vector whose initial capacity is specified by size. The third form creates a vector whose initial

capacity is specified by size and whose increment is specified by incr.

Method Description

void addElement(Object

element)

The object specified by element is added to the vector.

int capacity( ) Returns the capacity of the vector.

Object clone( ) Returns a duplicate of the invoking vector.

boolean contains(Object

element)

Returns true if element is contained by the vector, and returns false

if it is not.

void copyInto(Object array[ ]) The elements contained in the invoking vector are copied into the

array specified b array.

Object elementAt(int index) Returns the element at the location specified by index.

Enumeration elements( ) Returns an enumeration of the elements in the vector.

void ensureCapacity(int size) Sets the minimum capacity of the vector to size.

Object firstElement( ) Returns the first element in the vector.

int indexOf(Object element) Returns the index of the first occurrence of element. If the object is

not in the vector, –1 is returned.

void insertElementAt(Object

element, int index)

Adds element to the vector at the location specified by index

boolean isEmpty( ) Returns true if the vector is empty, and returns false if it contains

one or more elements.

Object lastElement( ) Returns the last element in the vector.

int lastIndexOf(Object

element)

Returns the index of the last occurrence of element. If the object is

not in the vector, –1 is returned.

void removeAllElements( ) Empties the vector. After this method executes, the size of the

vector is zero.

boolean

removeElement(Object

element)

Removes element from the vector. If more than one instance of the

specified object exists in the vector, then it is the first one that is

removed. Returns true if successful and false if the object is not

found.

void removeElementAt(int

index)

Removes the element at the location specified by index.

void setSize(int size) Sets the number of elements in the vector to size. If the new size is

less than the old size, elements are lost. If the new size is larger

than the old size, null elements are added.

int size( ) Returns the number of elements currently in the vector.

String toString( ) Returns the string equivalent of the vector.

void trimToSize( ) Sets the vector‘s capacity equal to the number of elements that it

currently holds.

Stack

Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the

default constructor, which creates an empty stack.

Method Description

boolean empty( ) Returns true if the stack is empty, and returns false if the stack contains

elements.

Object peek( ) Returns the element on the top of the stack, but does not remove it.

Object pop( ) Returns the element on the top of the stack, removing it in the process.

Object push(Object

element)

Pushes element on to the stack. Element is also returned.

int search(Object

element)

Searches for element in the stack. If found, its offset from the top of the

stack is returned. Otherwise, –1 is returned.

Dictionary

Dictionary is an abstract class that represents a key/value storage repository and operates much like

Map. Given a key and value, we can store the value in a Dictionary object. Once the value is stored,

we can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of

key/value pairs.

Method Description

Enumeration elements(

)

Returns an enumeration of the values contained in the dictionary.

Object get(Object key) Returns the object that contains the value associated with key. If key is not

in the dictionary, a null object is returned.

boolean isEmpty( ) Returns true if the dictionary is empty, and returns false if it contains at

least one key.

Enumeration keys( ) Returns an enumeration of the keys contained in the dictionary.

Object put(Object key,

Object value)

Inserts a key and its value into the dictionary. Returns null if key is not

already in the dictionary; returns the previous value associated with key if

key is already in the dictionary.

Object remove(Object

key)

Removes key and its value. Returns the value associated with key. If key is

not in the dictionary, a null is returned.

int size( ) Returns the number of entries in the dictionary.

Hashtable

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.

A hash table can only store objects that override the hashCode( ) and equals( ) methods that are

defined by Object.

The Hashtable constructors are shown here:

Hashtable( )

Hashtable(int size)

Hashtable(int size, float fillRatio)

The first version is the default constructor. The second version creates a hash table that has an initial

size specified by size. (Thedefaultsizeis11.)The third version creates a hash table that has an initial

size specified by size and a fill ratio specified by fill Ratio. This ratio must be between 0.0 and 1.0,

and it determines how full the hash table can be before it is resized upward.

Method Description

void clear( ) Resets and empties the hash table.

Object clone( ) Returns a duplicate of the invoking object.

boolean contains(Object

value)

Returns true if some value equal to value exists within the hash table.

Returns false if the value isn‘t found.

boolean

containsKey(Object key)

Returns true if some key equal to key exists within the hash table.

Returns false if the key isn‘t found.

Enumeration elements( ) Returns an enumeration of the values contained in the hash table.

Object get(Object key) Returns the object that contains the value associated with key. If key is

not in the hash table, a null object is returned.

boolean isEmpty( ) Returns true if the hash table is empty; returns false if it contains at least

one key.

Enumeration keys( ) Returns an enumeration of the keys contained in the hash table.

Object put(Object key,

Object value)

Inserts a key and its value into the dictionary. Returns null if key is not

already in the dictionary; returns the previous value associated with key

if key is already in the dictionary.

void rehash( ) Increases the size of the hash table and rehashes all of its keys.

Object remove(Object

key)

Removes key and its value. Returns the value associated with key. If key

is not in the dictionary, a null is returned.

int size( ) Returns the number of entries in the dictionary.

String toString( ) Returns the string equivalent of a hash table.

Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String

and the value is also a String.

Properties defines these constructors:

Properties( )

Properties(Properties propDefault)

The first version creates a Properties object that has no default values. The second creates an object

that uses propDefault for its default values. In both cases, the property list is empty.

Method Description

String getProperty(String key) Returns the value associated with key. A null object is returned

if key is neither in the list nor in the default property list.

String getProperty(String

defaultProperty)

Returns the value associated with key. Default Property is

returned if key is String neither in the list nor in the default

property list.

void list(PrintStream streamOut) Sends the property list to the output stream linked tostreamOut.

void list(PrintWriter streamOut) Sends the property list to the output stream linked tostreamOut.

void load(InputStream streamIn)

throws IOException

Inputs a property list from the input stream linked to streamIn.

Enumeration propertyNames( ) Returns an enumeration of the keys. This includes those keys

found in the default property list, too.

Object setProperty(String key,

String value)

Associates value with key. Returns the previous value associated

with key, or returns null if no such association exists

StringTokenizer

The processing of text often consists of parsing a formatted input string. Parsing is the division of

text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic

meaning.

To use StringTokenizer, we specify an input string and a string that contains delimiters. Delimiters

are characters that separate tokens. Each character in the delimiters string is considered a valid

delimiter - for example, ―,;:‖ sets the delimiters to a comma, semicolon, and colon. The default set

of delimiters consists of the white space characters: space, tab, newline, and carriage return.

The StringTokenizer constructors are shown here: StringTokenizer(String str)

StringTokenizer(String str, String delimiters)

StringTokenizer(String str, String delimiters, boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default delimiters are

used. In the second and third versions, delimiters is a string that specifies the delimiters. In the

third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string

is parsed. Otherwise, the delimiters are not returned.

Here is an example that creates a StringTokenizer to parse ―key=value‖ pairs. Consecutive sets of

―key=value‖ pairs are separated by a semicolon.

Method Description

int countTokens( ) Using the current set of delimiters, the method determines the number

of tokens left to be parsed and returns the result.

boolean hasMoreElements(

)

Returns true if one or more tokens remain in the string and returns

false if there are none.

boolean hasMoreTokens( ) Returns true if one or more tokens remain in the string and returns

false if there are none.

Object nextElement( ) Returns the next token as an Object.

String nextToken( ) Returns the next token as a String.

String nextToken(String

delimiters)

Returns the next token as a String and sets the delimiters string to that

specified by delimiters

Example: import java.util.StringTokenizer;

class STDemo {

static String in = "title=Java: The Complete Reference;" +

"author=Schildt;" + "copyright=2007";

public static void main(String args[]) {

StringTokenizer st = new StringTokenizer(in, "=;");

while(st.hasMoreTokens()) {

String key = st.nextToken();

String val = st.nextToken();

System.out.println(key + "\t" + val);

}

}

} The output from this program is shown here:

title Java: The Complete Reference

author Schildt

copyright 2007

BitSet

A BitSet class creates a special type of array that holds bit values. This array can increase in size as

needed. This makes it similar to a vector of bits. The BitSet constructors are shown here:

BitSet( )

BitSet(int size)

The first version creates a default object. The second version allows you to specify its initial size

(that is, the number of bits that it can hold). All bits are initialized to zero.

Method Description

void and(BitSet

bitSet)

ANDs the contents of the invoking BitSet object with those specified by

bitSet. The result is placed into the invoking object.

void clear(int index) Zeros the bit specified by index.

Object clone( ) Duplicates the invoking BitSet object.

boolean equals(Object

bitSet)

Returns true if the invoking bit set is equivalent to the one passed in bitSet.

Otherwise, the method returns false.

boolean get(int index) Returns the current state of the bit at the specified index.

int hashCode( ) Returns the hash code for the invoking object.

void or(BitSet bitSet) ORs the contents of the invoking BitSet object with that specified by bitSet.

The result is placed into the invoking object.

void set(int index) Sets the bit specified by index.

int size( ) Returns the number of bits in the invoking BitSet object.

String toString( ) Returns the string equivalent of the invoking BitSet object.

void xor(BitSet bitSet) XORs the contents of the invoking BitSet object with that specified by

bitSet. The result is placed into the invoking object.

Date

TheDate class encapsulates the current date and time.

Date supports the following constructors: Date( )

Date(long millisec)

The first constructor initializes the object with the current date and time. The second constructor

accepts one argument that equals the number of milliseconds that have elapsed since midnight,

January1, 1970.

Method Description

boolean after(Date

date)

Returns true if the invoking Date object contains a date that is later than the

one specified by date. Otherwise, it returns false.

boolean before(Date

date)

Returns true if the invoking Date object contains a date that is earlier than

the one specified by date. Otherwise, it returns false.

boolean

equals(Object date)

Returns true if the invoking Date object contains the same time and date as

the one specified by date. Otherwise, it returns false.

long getTime( ) Returns the number of milliseconds that have elapsed since January 1, 1970.

int hashCode( ) Returns a hash code for the invoking object.

void setTime(long

time)

Sets the time and date as specified by time, which represents an elapsed time

in milliseconds from midnight, January 1, 1970.

String toString( ) Converts the invoking Date object into a string and returns the result.

Example:

import java.util.Date;

class DateDemo {

public static void main(String args[]) {

Date date = new Date();

System.out.println(date);

long msec = date.getTime();

System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);

}

}

Sample output is shown here:

Mon Jan 01 16:28:16 CST 2007

Milliseconds since Jan. 1, 1970 GMT = 1167690496023

Calendar

The abstract Calendar class provides a set of methods that allows you to convert a time in

milliseconds to a number of useful components.

Some examples of the type of information that can be provided are year, month, day, hour, minute,

and second.

Calendar defines the following int constants, which are used when you get or set components of the

calendar:

AM

AM_PM

PM

HOUR

MINUTE

SECOND

MILLISECOND

HOUR_OF_DAY

DAY_OF_WEEK

DAY_OF_MONTH

DAY_OF_YEAR

DAY_OF_WEEK_IN_MO

NTH

WEEK_OF_MONTH

WEEK_OF_YEAR

DATE

MONTH

YEAR

MONDAY

TUESDAY

WEDNESDAY

THURSDAY

FRIDAY

SATURDAY

SUNDAY

JANUARY

FEBRUARY

MARCH

APRIL

MAY

JUNE

JULY

AUGUST

SEPTEMBER

OCTOBER

NOVEMBER

DECEMBER

UNDECIMBER

DST_OFFSET

ERA

ZONE_OFFSET

FIELD_COUNT

Calendar provides no public constructors.

Calendar defines several protected instance variables. Are FieldsSet is a boolean that indicates if the

time components have been set. fields is an array of ints that holds the components of the time. isSet

is a boolean array that indicates if a specific time component has been set.

Method Description

boolean after(Object

calendarObj)

Returns true if the invoking Calendar object contains a date that is later

than the one specified by calendarObj. Otherwise, it returns false.

boolean before(Object

calendarObj)

Returns true if the invoking Calendar object contains a date that is earlier

than the one specified by calendarObj. Otherwise, it returns false.

boolean equals(Object

calendarObj)

Returns true if the invoking Calendar object contains a date that is equal

to the one specified by calendarObj. Otherwise, it returns false.

int get(int calendarField) Returns the value of one component of the invoking object. The

component is indicated by Examples of the components that can be

requested are Calendar.MONTH, Calendar.MINUTE, and so forth.

final Date getTime( ) Returns a Date object equivalent to the time of the invoking object.

final void set(int year,

int month, int date, int

hours, int min, int sec)

Sets various date and time components of the invoking object.

final void setTime(Date

d)

Sets various date and time components of the invoking object. This

information is obtained from the Date objectd.

Example: //...

Calendar calendar = Calendar.getInstance();

System.out.print("Time: ");

System.out.print(calendar.get(Calendar.HOUR) + ":");

System.out.print(calendar.get(Calendar.MINUTE) + ":");

System.out.println(calendar.get(Calendar.SECOND));

calendar.set(Calendar.HOUR, 10);

System.out.print("Updated time: ");

System.out.print(calendar.get(Calendar.HOUR) + ":");

System.out.print(calendar.get(Calendar.MINUTE) + ":");

System.out.println(calendar.get(Calendar.SECOND));

//...

Sample output is shown here:

Time: 11:24:25

Updated time: 10: 24: 25

GregorianCalendar

GregorianCalendar is a concrete implementation of a Calendar. GregorianCalendar defines two

fields: AD and BC. These represent the two eras defined by the Gregoriancalendar.

There are also several constructors for GregorianCalendar objects. The default, GregorianCalendar(

), initializes the object with the current date and time in the default locale and time zone. Three more

constructors are:

GregorianCalendar(int year, int month, int date, int hours, int minutes, int

seconds)

GregorianCalendar(TimeZone timeZone, Locale locale)

Here, year specifies the year. The month is specified by month, with zero indicating January. The

day of the month is specified by dayOfMonth. The second version also constructs a

GregorianCalendar object by specifying the locale and/or time zone.

Method Description

boolean after(Object

calendarObj)

Returns true if the invoking Calendar object contains a date that is later

than the one specified by calendarObj. Otherwise, it returns false.

boolean before(Object

calendarObj)

Returns true if the invoking Calendar object contains a date that is earlier

than the one specified by calendarObj. Otherwise, it returns false.

boolean equals(Object

calendarObj)

Returns true if the invoking Calendar object contains a date that is equal

to the one specified by calendarObj. Otherwise, it returns false.

boolean isLeapYear() This method returns true if year is a leap year and false otherwise.

TimeZone

Another time-related class is TimeZone. The TimeZone class allows you to work with time zone

offsets from Greenwich meantime (GMT), also referred to as Coordinated Universal Time (UTC).It

also computes day light saving time.

Method Description

static String[ ] getAvailableIDs( ) Returns an array of String objects representing the names of all

time zones.

static TimeZone getDefault( ) Returns a TimeZone object that represents the default time zone

used on the host computer.

abstract int getOffset(int era, int

year, int month, int dayOfMonth,

int dayOfWeek, int millisec)

Returns the offset that should be added to GMT to compute

local time. This value is adjusted for daylight saving time. The

parameters to the method represent date and time components.

abstract int getRawOffset( ) Returns the raw offset that should be added to GMT to compute

local time. This value is not adjusted for daylight saving time.

static TimeZone

getTimeZone(String tzName)

Returns the TimeZone object for the time zone named tzName.

abstract boolean

inDaylightTime(Date d)

Returns true if the date represented by dis in daylight saving

time in the invoking object. Otherwise, it returns false.

static void setDefault(TimeZone

tz)

Sets the default time zone to be used on this host. tz is a

reference to the TimeZone object to be used.

abstract boolean

useDaylightTime( )

Returns true if the invoking object uses daylight saving time.

Otherwise, it returns false.

SimpleTimeZone

The SimpleTimeZone class is a convenient sub class of TimeZone. Its allow to work with time zones

for a Gregorian calendar. It also computes daylight saving time.

SimpleTimeZone(int timeDelta, String tzName)

This constructor creates a SimpleTimeZone object. The offset relative to Greenwich meantime

(GMT) is timeDelta. The time zone is named tzName.

Method Description

abstract int getOffset(int era, int

year, int month, int dayOfMonth,

int dayOfWeek, int millisec)

Returns the offset that should be added to GMT to compute

local time. This value is adjusted for daylight saving time. The

parameters to the method represent date and time components.

abstract int getRawOffset( ) Returns the raw offset that should be added to GMT to compute

local time. This value is not adjusted for daylight saving time.

abstract boolean

inDaylightTime(Date d)

Returns true if the date represented by dis in daylight saving

time in the invoking object. Otherwise, it returns false.

abstract boolean

useDaylightTime( )

Returns true if the invoking object uses daylight saving time.

Otherwise, it returns false.

Locale

The Locale class is instantiated to produce objects that describe a geographical or cultural region. It

provides us with the ability to write programs that can execute in different international

environments.

CANADA

CANADA_FRENCH

CHINA

CHINESE

SIMPLIFIED_CHINESE

TRADITIONAL_CHINESE

FRANCE

FRENCH

GERMANY

GERMAN

ITALY

ITALIAN

JAPAN

JAPANESE

KOREA

KOREAN

TAIWAN

UK

US

ENGLISH

PRC

Locale(String language, String country, String data)

This constructor builds a Locale object to represent a specific language and country. These values

must contain ISO-standard language and country codes. Auxiliary browser and vendor-specific

information can be provided in data.

static void setDefault(Locale localeObj)

This sets the default locale to that specified by localeObj.

Random

The Random class is a generator of pseudorandom numbers. These are called pseudorandom

numbers because they are simply uniformly distributed sequences. Random defines the following

constructors: Random( )

Random(long seed)

The first version creates a number generator that uses the current time as the starting, or seed, value.

The second form allows specifying a seed value manually.

Method Description

boolean nextBoolean( ) Returns the next boolean random number.

void nextBytes(byte vals[ ]) Fills vals with randomly generated values.

double nextDouble( ) Returns the next double random number.

float nextFloat( ) Returns the next float random number.

double nextGaussian( ) Returns the next Gaussian random number.

int nextInt( ) Returns the next int random number.

long nextLong( ) Returns the next long random number.

void setSeed(long newSeed) Sets the seed value (that is, the starting point for the random

number generator) to that specified by newSeed.

Observable

The Observable class is used to create subclasses that other parts of your program can observe. When

an object of such a subclass undergoes a change, observing classes are notified.

Observing classes must implement the Observer interface, which defines the update( ) method.

Theupdate( ) method is called when an observer is notified of a change in an observed object.

Method Description

void addObserver( Observer obj) Adds obj to the list of objects observing the invoking object.

protected void clearChanged( ) Calling this method returns the status of the invoking object to

―unchanged.‖

int countObservers( ) Returns the number of objects observing the invoking object.

void deleteObserver( Observer

obj)

Removes obj from the list of objects observing the invoking

object.

void deleteObservers( ) Removes all observers for the invoking object.

boolean hasChanged( ) Returns true if the invoking object has been modified and false

if it has not

void notifyObservers( ) Notifies all observers of the invoking object that it has changed

by calling update( ). A null is passed as the second argument to

update( ).

void notifyObservers( Object obj) Notifies all observers of the invoking object that it has changed

by calling update( ). obj is passed as an argument to update( ).

protected void setChanged( ). Called when the invoking object has changed

The Observer Interface

To observe an observable object, you must implement the Observer interface. This interface defines

only the one method shown here:

void update(Observable observOb, Object arg)

Here, observOb is the object being observed, and arg is the value passed by notify Observers(). The

update() method is called when a change in the observed object takes place.

Streaming

A stream is an abstraction that either produces or consumes information. A stream is linked to a

physical device by the Java I/O system. All streams behave in the same manner, even if the actual

physical devices to which they are linked differ.

Input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network

socket, and an output stream may refer to the console, a disk file, or a network connection.

The Java I/O Classes and Interfaces

This chapter explores java.io, which provides support for I/O operations.

BufferedInputStream

BufferedOutputStream

BufferedReader

BufferedWriter

ByteArrayInputStream

ByteArrayOutputStream

CharArrayReader

CharArrayWriter

DataInputStream

DataOutputStream

File

FileDescriptor

FileInputStream

FileOutputStream

FileReader

FileWriter

FilterInputStream

FilterOutputStream

FilterReader

FilterWriter

InputStream

InputStreamReader

LineNumberReader

ObjectInputStream

ObjectOutputStream

ObjectStreamClass

OutputStream

OutputStreamWriter

PrintStream

PrintWriter

RandomAccessFile

Reader

StreamTokenizer

StringReader

StringWriter

Writer

The following interfaces are defined by java.io:

DataInput

DataOutput

Externalizable

FilenameFilter

ObjectInput

ObjectInputValidation

ObjectOutput

Serializable

File

A File object is used to obtain or manipulate the information associated with a disk file or directory.

Since File does not operate on streams.

The following constructors can be used to create File objects:

File(String directoryPath)

File(String directoryPath, String filename)

File(File dirObj, String filename)

Here, directoryPath is the path name of the file, filename is the name of the file or subdirectory,

dirObj is a File object that specifies a directory.

Method Description

boolean canRead( ) throws

SecurityException

This method checks whether the file referred to by the invoking object

can be read by this program

boolean canWrite( )

throws SecurityException

This method checks whether the file referred to by the invoking object

can be written by this program

boolean delete( ) This method deletes the file referred to by the invoking object. This

method returns true if it deletes the file and false if the file cannot be

removed.

boolean equals(Object

Obj)

Returns true if the invoking object is equivalent to Obj. Otherwise, it

returns false.

boolean exits() throws

SecurityException

This method determines whether the file referred to by the invoking

object exits.

String getAbsolutePath() Returns a String object equivalent to the absolute path name of the file

referred to by the invoking object.

String getName() Returns a String object that contains the name of the file referred to by

the invoking object.

String getParent() Returns a String object that contains the parent directory.

String getPath() Returns the relative path name of the file.

int hashCode( ) Returns the hash code for the invoking object.

boolean isAbsolute( ) Returns true if the file has an absolute path and false if its path is

relative.

boolean isDirectory( )

throws SecurityException

This method checks whether the file referred to by the invoking object

is a directory.

boolean isFile( ) throws

SecurityException

This method checks whether the file referred to by the invoking object

is a normal file.

long lastModified() Returns the last modified time stamp for the file referred to by the

invoking object.

String[] list() throws

SecurityException

Returns an array of String objects equivalent to the name of files in the

directory represented by the invoking object.

boolean mkdir() throws

SecurityException

Creates a directory whose name is the path name of the invoking object.

Its return true only if the operation is success, otherwise it return false.

boolean renameTo(File

newName)

The filename specified by newName becomes the new name of the

invoking File object. It will return true upon success and false if the file

cannot be renamed

String toString( ) Returns the string equivalent of the invoking object.

InputStream, FileInputStream, ByteArrayInputStream, BufferedInputStream, Reader,

CharArrayReader, and BufferedReader

InputStream:

InputStream is an abstract class that defines Java‘s model of streaming byte input. Most of the

methods in this class will throw an IOException on error conditions.

FileInputStream:

The File Input Stream class creates an InputStream that you can use to read bytes from a file. Its two

most common constructors are shown here:

FileInputStream(String filepath)

FileInputStream(File fileObj)

Either can throw a FileNotFoundException. Here, filepath is the full path name of a file, and fileObj

is a File object that describes the file.

Example: //...

int size,n;

InputStream f = new FileInputStream("FileInputStreamDemo.java");

System.out.println("Total Available Bytes: " + (size = f.available()));

n = size / 2;

for (int i=0; i < n; i++) {

System.out.print((char) f.read());

}

System.out.println("\nStill Available: " + f.available());

//...

ByteArrayInputStream:

ByteArrayInputStream is an implementation of an input stream that uses a byte array as the source.

This class has two constructors, there are:

ByteArrayInputStream(byte array[ ])

ByteArrayInputStream(byte array[ ], int start, int numBytes)

Here, array is the input source. The second constructor creates an InputStream from a subset of your

byte array that begins with the character at the index specified by start and is numBytes long.

BufferedInputStream:

Buffering I/O is a very common performance optimization. Java‘s BufferedInputStream class allows

us to ―wrap‖ any InputStream in to a bufferedstream and achieve this performance improvement.

There are five instance variables. buf is a protected byte array that holds the data. count is a

protected int that indicates the next passion to write in buf. marklimit is a protected int that

indicates the maximum number of bits allowed. markpos is a protected int that indicates the current

mark position. pos is a protected int that indicates the passion of the next byte to read from buf.

BufferedInputStream has two constructors:

BufferedInputStream(InputStream inputStream)

BufferedInputStream(InputStream inputStream, int bufSize)

The first form creates a buffered stream using a default buffer size. In the second, the size of the

buffer is passed in bufSize.

Reader

Reader is an abstract class that defines Java‘s model of streaming character input. It has one instance

variable lock is a protected reference to an Object. All of the methods in this class (except for

markSupported()) will throw an IOException on error conditions.

Reader has two constructors:

Reader( )

Reader(Object lock)

This constructors creates an object that can read a stream of characters. Second method lock is an

Object that is used to synchronize the activities of multiple threads that are concurrently doing read

operations.

CharArrayReader:

CharArrayReader is an implementation of an input stream that uses a character array as the source.

There are four instance variables. buf is a protected character array that holds the data. count is a

protected int that indicates the number of valid characters in buf. markedPos is a protected int that

indicates the current mark position. pos is a protected int that indicates the passion of the next byte to

read from buf.

This class has two constructors, each of which requires a character array to provide the data source:

CharArrayReader(char array[ ])

CharArrayReader(char array[ ], int start, int numChars)

Here, array is the input source. The second constructor creates a Reader from a subset of your

character array that begins with the character at the index specified by start and is numChars long.

BufferedReader:

BufferedReader improves performance by buffering input. It has two constructors:

BufferedReader(Reader inputStream)

BufferedReader(Reader inputStream, int bufSize)

The first form creates a buffered character stream using a default buffer size. In the second, the size

of the buffer is passed inbufSize.

Method Description

void close( ) Closes the input source. Further read attempts will generate an

IOException.

void mark(int numBytes) Places a mark at the current point in the input stream that will remain

valid until numBytes bytes are read.

boolean markSupported( ) Returns true if mark( )/reset( ) are supported by the invoking stream.

void reset( ) Resets the input pointer to the previously set mark.

int read( ) Returns an integer representation of the next available byte of input. –1

is returned when the end of the file is encountered.

int read(byte buffer[ ]) Attempts to read up to buffer.length bytes into buffer and returns the

actual number of bytes that were successfully read. –1 is returned when

the end of the file is encountered.

int read(byte buffer[ ], int

offset, int numBytes)

Attempts to read up to numBytes bytes into buffer starting at

buffer[offset], returning the number of bytes successfully read. –1 is

returned when the end of the file is encountered.

long skip(long numBytes) Ignores (that is, skips) numBytes bytes of input, returning the number

of bytes actually ignored.

OutputStream, FileOutputStream, BufferedOutputStream, PrintStream, PrintWriter,

Writer, CharArrayWriter, and BufferedWriter

OutputStream:

OutputStream is an abstract class that defines Java‘s model of streaming byte output. Most of the

methods in this class return void and throw an IOException in the case of errors.

FileOutputStream:

FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most

commonly used constructors are shown here:

FileOutputStream(String filePath)

FileOutputStream(File fileObj)

FileOutputStream(String filePath, boolean append)

They can throw a FileNotFoundException. Here, filePath is the full path name of a file, and file Obj

is a File object that describes the file. If append is true, the file is opened in append mode.

Example:

//...

String source = "Now is the time for all good men\n" + " to come to the aid

of their country\n" + " and pay their due taxes.";

byte buf[] = source.getBytes();

OutputStream f0 = new FileOutputStream("file1.txt");

for (int i=0; i < buf.length; i += 2) {

f0.write(buf[i]);

}

f0.close();

//...

BufferedOutputStream:

ABufferedOutputStream is similar to any OutputStream. Buffers for output in Java are there to

increase performance. There are two instance variables. buf is a protected byte array that holds the

data. count is a protected int that indicates the next passion to write in buf.

Here are the two available constructors:

BufferedOutputStream(OutputStream outputStream)

BufferedOutputStream(OutputStream outputStream, int bufSize)

The first form creates a buffered stream using the default buffer size. In the second form, the size of

the buffer is passed in bufSize.

PrintStream:

The PrintStream class provides all of the output capabilities we have been using from the System file

handle. The PrintStream class contains methods that make it easy to generate formatted output.

The constructors are:

PrintStream(OutputStream outputStream)

PrintStream(OutputStream outputStream, boolean flushOnNewline)

Here, outputStream specifies an open OutputStream that will receive output. The flushOnNewline

parameter controls whether the output buffer is automatically flushed every time a new line (\n)

character or a byte array is written, or when println( ) is called. If flushOnNewline is true, flushing

automatically takes place. If it is false, flushing is not automatic.

PrintStream supports the print( ) and println( ) methods for all types, including Object. If an

argument is not a primitive type, the PrintStream methods will call the object‘s toString() method

and then display the result. For example:

void println(double d) – This method display the string equivalent of double d.

PrintWriter:

PrintWriter is essentially a character-oriented version of PrintStream. The constructors are:

PrintWriter(OutputStream outputStream)

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

PrintWriter(Writer outputStream)

PrintWriter(Writer outputStream, boolean flushOnNewline)

Here, outputStream specifies an open OutputStream that will receive output. The flushOnNewline

parameter controls whether the output buffer is automatically flushed. If flushOnNewline is true,

flushing automatically takes place. If false, flushing is not automatic. Constructors that do not

specify the flushOnNewline parameter do not automatically flush.

The following methods exist in both PrintStream and PrintWriter: checkError(), close(), flush(),

print(), println(), write(), and setError().

Writer:

Writer is an abstract class that defines Java‘s model of write to a character stream. It has one instance

variable lock is a protected reference to an Object.

Reader has two constructors:

Writer( )

Writer(Object lock)

This constructors creates an object that can write a stream of characters. Second method lock is an

Object that is used to synchronize the activities of multiple threads that are concurrently doing read

operations.

CharArrayWriter:

CharArrayWriter is an implementation of an outputstream that uses an array as the destination. There

are two instance variables. buf is a protected character array that holds the data. count is a protected

int that indicates the number of valid characters in buf.

CharArrayWriter has two constructors, shown here:

CharArrayWriter( )

CharArrayWriter(int numChars)

In the first form, a buffer with a default size is created. In the second, a buffer is created with a Size

equal to that specified by numChars. The buffer is held in the buf field of CharArrayWriter. The

buffer size will be increased automatically, if needed.

BufferedWriter:

ABufferedWriter is a Writer that buffers ouput. Using a BufferedWriter can increase performance by

reducing the number of times data is actually physically written to the output stream. A

BufferedWriter has these two constructors:

BufferedWriter(Writer outputStream)

BufferedWriter(Writer outputStream, int bufSize)

The first form creates a buffered stream using a buffer with a default size. In the second, the size of

the buffer is passed in bufSize.

Method Description

void close( ) Closes the Output Stream. Further read attempts will generate an

IOException.

void flush( ) Finalizes the output state so that any buffers are cleared. That is, it

flushes the output buffers.

void write(int b) Writes a single byte to an output stream. Note that the parameter is an

int, which allows you to call write( ) with expressions without having to

cast them back to byte.

void write(byte buffer[ ]) Writes a complete array of bytes to an output stream.

void write(byte buffer[ ],

int offset, int numBytes)

Writes a subrange of numBytes bytes from the array buffer, beginning

at buffer[offset].

ByteArrayOutputStream:

ByteArrayOutputStream is an implementation of an output stream that uses a byte array as the

destination. ByteArrayOutputStream has two constructors, shown here:

ByteArrayOutputStream( )

ByteArrayOutputStream(int numBytes)

In the first form, a buffer of 32 bytes is created. In the second, a buffer is created with a size equal to

that specified by numBytes.

Method Description

void reset( ) Sets the stream counter to their initial state.

int size() Returns the number of data bytes in the invoking stream.

byte[ ] toByteArray( ) Returns a new byte array whose contents are equivalent to the bytes

in the invoking stream.

String to String( ) Returns a String equivalent to the invoking object.

String to String(String

encoding)

Returns a String equivalent to the invoking object. encoding is the

name of character technique.

void write(int b) Writes a single byte to an output stream. Note that the parameter is

an int, which allows you to call write( ) with expressions without

having to cast them back to byte.

void write(byte buffer[ ], int

offset, int numBytes)

Writes a subrange of numBytes bytes from the array buffer,

beginning at buffer[offset].

void writeTo(OutputStream

outStream)

Writes the ByteArrayOutputStream data to the stream specified by

outStream.

DataInput Interface, DataInputStream class

DataInput Interface:

The DataInput interface provides a set of methods that allow us to read the elemental data types

from a stream.

DataInputStream class:

The constructor is, DataInputStream(InputStream istream)

Here, istream specifies the input stream from which data will be read.

Method Description

abstract boolean

readBoolean( )

Reads and returns a boolean from the invoking stream. It can throw

EOFException or IOException.

abstract byte readByte( ) Reads and returns a byte from the invoking stream. It can throw

EOFException or IOException.

abstract char readChar( ) Reads and returns a char from the invoking stream. It can throw

EOFException or IOException.

abstract double

readDouble( )

Reads and returns a double from the invoking stream. It can throw

EOFException or IOException.

abstract float readFloat(

)

Reads and returns a float from the invoking stream. It can throw

EOFException or IOException.

abstract int readInt( ) Reads and returns a int from the invoking stream. It can throw

EOFException or IOException.

abstract long readLong(

)

Reads and returns a long from the invoking stream. It can throw

EOFException or IOException.

abstract short readShort(

)

Reads and returns a short from the invoking stream. It can throw

EOFException or IOException.

abstract void readFully(

)

Reads bytes from a stream into the buffer. The method does not return

until buffer is fulled. It can throw EOFException or IOException.

abstract int

readUnsignedByte( )

Reads and returns a unsigned byte from the invoking stream. It can throw

EOFException or IOException.

abstract int

readUnsignedShort( )

Reads and returns a unsigned short from the invoking stream. It can

throw EOFException or IOException.

Abstract int

skipBytes(int number)

This method causes the invoking stream to ignore number bytes. It

returns number. It can throw EOFException or IOException.

DataOutput Interface, DataOutputStream class:

DataOutput Interface:

The DataOutput interface provides a set of methods that allow us to read the elemental data

types from a stream.

DataOutputStream class: The constructor is,

DataOutputStream(OutputStream ostream)

Here, ostream specifies the output stream from which data will be read.

Method Description

void write(int b) Writes a single byte to an output stream. Note that the parameter

is an int, which allows you to call write( ) with expressions

without having to cast them back to byte.

void write(byte buffer[ ]) Writes a complete array of bytes to an output stream.

void write(byte buffer[ ], int

offset, int numBytes)

Writes a subrange of numBytes bytes from the array buffer,

beginning at buffer[offset].

abstract void

writeBoolean(boolean value)

Writes a boolean to the invoking stream. It can throw

IOException.

abstract void writeByte(String

value)

Writes a byte to the invoking stream. It can throw IOException.

abstract void writeChar(int value) Writes a char to the invoking stream. It can throw IOException.

abstract void writeDouble(double

value)

Writes a double to the invoking stream. It can throw

IOException.

abstract void writeFloat(float

value)

Writes a float to the invoking stream. It can throw IOException.

abstract void writeInt(int value) Writes a int to the invoking stream. It can throw IOException.

abstract void writeLong(int value) Writes a long to the invoking stream. It can throw IOException.

abstract void writeShort(int value) Writes a short to the invoking stream. It can throw IOException.

FileReader

The FileReader class creates a Reader that you can use to read the contents of a file. Its two most

commonly used constructors are shown here:

FileReader(String filePath)

FileReader(FileDescriptor fd)

FileReader(File f)

Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, fd is a File

descriptor that describes the file, and f is a File object that describes the file.

FileWriter

FileWriter creates a Writer that you can use to write to a file. Its most commonly used constructors

are shown here:

FileWriter(String filePath)

FileWriter(String filePath, boolean append)

FileWriter(File fileObj)

FileWriter(File fileObj, boolean append)

They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a File

object that describes the file. If append is true, then output is appended to the end of the file.

StreamTokenizer:

StreamTokenizer breaks up the input stream into tokens that are delimited by sets of characters.

StreamTokenizer defines four int constants: TT_EOF, TT_EOL, TT_NUMBER, and TT_WORD.

There are three instance variables. nval is a public double used to hold the values of numbers as they

are recognized. Sval is a public String used to hold the value of any words as they are recognized.

ttype is a public int indicating the type of token that has just been read by the nextToken( )method. If

the token is a word, ttype equals TT_WORD. If the token is a number, ttype equals TT_NUMBER.

If the end of the stream has been encountered, ttype equals TT_EOF.

It has this constructor: StreamTokenizer(Reader inStream)

Here, inStream must be some form of Reader.

Method Description

void eolIsSignificant(boolean

eolFlag)

To ensure that new line characters will be delivered as tokens, so we

can count the number of lines as well as words. If eolFlag is true, the

end-of-line characters are returned as tokens. IfeolFlag is false, the

end-of-line characters are ignored

void wordChars(int start, int

end)

This method causes the StreamTokenizer to treat all characters

between start and end as white space.

void wordspaceChars(int

start, int end)

This method causes the StreamTokenizer to treat all characters

between start and end as word characters.

int lineno( ) This method returns the current line number

void

lowerCaseMode(boolean

caseFlog)

If caseFlog is true, this method automatically converts tokens to

lowercase before they are assigned to the variable sval.

void

slashSlashComments(boolean

commentFlag)

If commentFlag is true, this method causes the StreamTokenizer to

interpret two consecutive forword slash characters as the start of a

comment. All characters from that point to the end of the same line

are ignored.

void

slashStarComments(boolean

commentFlag)

If commentFlag is true, this method causes the StreamTokenizer to

interpret a slash-star character sequence as the start of a comment.

All characters from that point to the end of the same line are ignored.

The Networking Classes and Interfaces

The Java is the premier language for network programmings are the classes defined in the java.net

package. The networking classes that make web-based programming easy, the classes contained in

the java.net package are shown here:

ContentHandler

DatagramPacket

DatagramSocket

DatagramSocketImpl

HttpURLConnection

InetAddress

ServerSocket

Socket

URL

URLConnection

URLEncoder

URLStreamHandler

The java.net package‘s interfaces are listed here:

ContentHandlerFactory

FileNameMap

SocketImplFactory

URLStreamHandlerFactory

DatagramSocket

The DatagramSocket is the mechanism used to send or receive the DatagramPackets.

DatagramSocket defines few public constructors. They are shown here:

DatagramSocket( ) throws SocketException

DatagramSocket(int port) throws SocketException

DatagramSocket(int port, InetAddress ipAddress) throws SocketException

The first creates a DatagramSocket bound to any unused port on the local computer. The second

creates a DatagramSocket bound to the port specified by port. The third constructs a DatagramSocket

bound to the specified port and InetAddress.

DatagramSocket defines many methods.

Method Description

void close() This method closes the invoking object.

InetAddress getInetAddress( ) Returns the InetAddress associated with the object. It returns

null if the socket is not connected.

int getLocalPort( ) Returns the local port to which the invoking object is bound. It

returns –1 if the socket is not bound.

synchronized int getSoTimeout()

throws SocketException

Returns the timeout(in milliseconds) of the invoking socket. A

value is zero means there is no timeout.

synchronized void setSoTimeout(

int ms) throws SocketException

Set the timeout(in milliseconds) for the invoking socket.

void send(DatagramPacket

packet) throws IOException

The send( ) method sends packet to the port specified by packet.

void receive(DatagramPacket

packet) throws IOException

The receive( ) method waits for a packet to be received from the

port specified bypacketand returns the result.

DatagramPacket

The DatagramPacket object is the data container. It represent datagram packets, which are sent from

one machine to another.

DatagramPacket defines several constructors. Four are shown here:

DatagramPacket(byte data[ ], int size)

DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)

The first constructor specifies a buffer that will receive data and the size of a packet. It is used for

receiving data over a DatagramSocket. The second form specifies a target address and port, which

are used by aDatagramSocket to determine where the data in the packet will be sent.

Method Description

InetAddress getAddress( ) Returns the address of the source (for datagrams being received) or

destination (for datagrams being sent).

byte[ ] getData( ) Returns the byte array of data contained in the datagram. Mostly

used to retrieve data from the datagram after it has been received.

int getLength( ) Returns the length of the valid data contained in the byte array that

would be returned from the getData( ) method. This may not equal

the length of the whole byte array.

void setAddress(InetAddress

ipAddress)

Sets the address to which a packet will be sent.The address is

specified by ipAddress.

int getPort( ) Returns the port number.

void setData(byte[ ] data) Sets the data to data, the offset to zero, and the length to number of

bytes in data.

void setLength(int size) Sets the length of the packet to size.

void setPort(int port) Sets the port to port.

InetAddress

The InetAddress class is used to encapsulate both the numerical IPaddress and the domain name for

that address. You interact with this class by using the name of an IPhost, which is more convenient

and understandable than its IPaddress. The InetAddress class hides the number inside. InetAddress

can handle both IPv4 and IPv6 addresses.

Method Description

boolean equals(Object other) Returns true if this object has the same Internet address as other.

byte[ ] getAddress( ) Returns a byte array that represents the object‘s IP address in

network byte order.

static InetAddress[ ]

getAllByName(String

hostName) throws

UnknownHostException

Returns an array of InetAddresses that represent all of the addresses

that a particular name resolves to. It will also throw an

UnknownHostException if it can‘t resolve the name to atleast one

address.

static InetAddress

getByName(String hostName)

throws

UnknownHostException

Returns an InetAddress for a host name passed to it. If these

methods are unable to resolve the host name, they throw an

UnknownHostException.

String getHostAddress( ) Returns a string that represents the host address associated with the

InetAddress object.

String getHostName( ) Returns a string that represents the host name associated with the

InetAddress object.

boolean isMulticastAddress( ) Returns true if this address is a multicast address. Otherwise, it

returns false.

String toString( ) Returns a string equivalent of the invoking object.

Socket

The Socket class is for clients. It is designed to connect to server sockets and initiate protocol

exchanges. The creation of a Socket object implicitly establishes a connection between the client and

server.

Here are two constructors used to create client sockets:

Method Description

Socket(String hostName, int port) throws

UnknownHostException, IOException

Creates a socket connected to the named host and port.

Socket(InetAddress ipAddress, int port)

throws IOException

Creates a socket using a preexisting InetAddress object

and a port.

Socket defines several instance methods.

Method Description

synchronized void close() This method closes the invoking object. it can throw an

IOException.

InetAddress getInetAddress( ) Returns the InetAddress associated with the Socket object. It

returns null if the socket is not connected.

InputStream getInputStream( )

throws IOException

Returns the InputStream associated with the invoking socket.

int getPort( ) Returns the remote port to which the invoking Socket object is

connected. It returns 0 if the socket is not connected.

int getLocalPort( ) Returns the local port to which the invoking Socket object is

bound. It returns –1 if the socket is not bound.

synchronized int getSoTimeout()

throws SocketException

Returns the timeout(in milliseconds) of the invoking socket. A

value is zero means there is no timeout.

synchronized void setSoTimeout(

int ms) throws SocketException

Set the timeout(in milliseconds) for the invoking socket.

OutputStream getOutputStream( )

throws IOException

Returns the OutputStream associated with the invoking socket.

String toString( ) Returns a string equivalent of the invoking object.

ServerSocket

The ServerSocket class is designed to be a ―listener,‖ which waits for clients to connect before doing

anything. The ServerSocket class is used to create servers that listen for either local or remote client

programs to connect to them on published ports.

Here are three of its constructors:

Method Description

ServerSocket(int port) throws

IOException

Creates server socket on the specified port with a queue length

of 50.

ServerSocket(int port, int

maxQueue) throws IOException

Creates a server socket on the specified port with a maximum

queue length of maxQueue.

ServerSocket(int port, int

maxQueue, InetAddress

localAddress) throws IOException

Creates a server socket on the specified port with a maximum

queue length of maxQueue. On a multihomed host,

localAddressspecifies the IP address to which this socket

binds.

ServerSocket defines several instance methods.

Method Description

void close() This method closes the invoking object. it can throw an

IOException.

Socket accept() throws

IOException

This method waits until an incoming connection request is

received from a client. It returns a Socket object that can used

for communicating with that client.

InetAddress getInetAddress( ) Returns the InetAddress associated with the object. It returns

null if the socket is not connected.

int getLocalPort( ) Returns the local port to which the invoking Socket object is

bound. It returns –1 if the socket is not bound.

synchronized int getSoTimeout()

throws SocketException

Returns the timeout(in milliseconds) of the invoking socket. A

value is zero means there is no timeout.

synchronized void setSoTimeout(

int ms) throws SocketException

Set the timeout(in milliseconds) for the invoking socket.

String toString( ) Returns a string equivalent of the invoking object.

URL

The Uniform Resource Locator (URL) provides a reasonably intelligible form to uniquely identify or

address information on the Internet. The URL class provides a simple, concise API to access

information across the Internet using URLs.

One commonly used form specifies the URL with a string that is identical to what you see displayed

in a browser:

URL(String url) throws MalformedURLException

The next two forms of the constructor allow you to break up the URL into its component parts:

URL(String protocolName, String hostName, int port, String path)

throws MalformedURLException

URL(String protocolName, String hostName, String path) throws

MalformedURLException

Method Description

boolean equals(Object

other)

Returns true if this object has the same Internet address as other.

final getContent() Return the contents of the invoking URL. It can throw an IOException.

String getfile() Return the file name component of the invoking URL.

String gethost() Return the host name component of the invoking URL.

int getport() Return the port number component of the invoking URL.

String getprotocol() Return the protocol component of the invoking URL.

int hashCode() Return the hash code of the invoking object.

URLConnection

openConnection()

This method creates a connection to the URL specified by the invoking

object. it can throw an IOException.

final InputStream

openStream()

Returns a stream connected to the URL specified by the invoking object.

if there is no open connection to the URL, one is created. Once the input

stream has been obtained, it can be used to read data from the URL.

Boolean sameFile(URL

anotherURL)

This method tests whether the invoking object and anotherURL refer to

the same resource.

String toString( ) Returns a string equivalent of the invoking object.

URLConnection

URLConnection is an abstract class that encapsulates the mechanism used to communicate with a

remote URL.

URLConnection is a general-purpose class for accessing the attributes of a remote resource. Once

you make a connection to a remote server, you can use URLConnection to inspect the properties of

the remote object before actually transporting it locally.

Method Description

int getContentLength( ) Returns the size in bytes of the content associated with the resource. If the

length is unavailable, –1 is returned.

String getContentType(

)

Returns the type of content found in the resource. This is the value of the

content-type header field. Returns null if the content type is not available.

long getDate( ) Returns the time and date of the response represented in terms of

milliseconds since January 1, 1970 GMT.

String

getHeaderField(int idx)

Returns the value of the header field at index idx. (Header field indexes

begin at 0.) Returns null if the idx exceeds the number of fields. value of

String

getHeaderField(String

fieldname)

Returns the value of header field whose name is specified by fieldName.

Returns null if the specified name is not found.

long getLastModified( ) Returns the time and date, represented in terms of milliseconds since

January 1, 1970 GMT, of the last modification of the resource. Zero is

returned if the last-modified date is unavailable.

String toString( ) Returns a string equivalent of the invoking object.

URLEncoder

The URLEncoder class contains one static method that takes a String object and converts it to the

corresponding URL-encoded format.

static String encode(String str)

This method returns the URL-encoded format of str. Encoding follows these rules:

- Alphanumeric characters are not changed.

- Spaces are translated into the ‗+‘ character.

- All other characters are converted to a two-digit hexadecimal representation. This value is

preceded by a ‗%‘ character.

The Java Applet Class and Interfaces:

The Applet class is contained in the java.applet package. The java.applet also defines three

interfaces: AppletContext, AudioClip, and AppletStub.

The Applet Class

Applet contains several methods that give you detailed control over the execution of your applet.

Applet provides all necessary support for applet execution, such as starting and stopping. It also

provides methods that load and display images, and methods that load and play audio clips. Thus,

Applet provides all of the necessary support for window-based activities.

Method Description

void destroy( ) Called by the browser just before an applet is terminated. Your applet

will override this method if it needs to perform any cleanup prior to its

destruction.

AppletContext

getAppletContext( )

Returns the context associated with the applet.

String getAppletInfo( ) Returns a string that describes the applet.

AudioClip

getAudioClip(URL url )

Returns an AudioClip object that encapsulates the audio clip found at

the location specified by url.

AudioClip

getAudioClip(URL url,

String clipName )

Returns an AudioClip object that encapsulates the audio clip found at

the location specified by urland having the name specified by

clipName.

URL getCodeBase( ) Returns the URL associated with the invoking applet.

URL getDocumentBase( ) Returns the URL of the HTML document that invokes the applet.

Image getImage(URL url ) Returns an Image object that encapsulates the image found at the

location specified by url.

Image getImage(URL url,

String imageName)

Returns an Image object that encapsulates the image found at the

location specified by urland having the name specified by imageName.

String getParameter(String

paramName)

Returns the parameter associated withparamName. null is returned if

the specified parameter is not found.

String[ ] [ ]

getParameterInfo( )

Returns a String table that describes the parameters recognized by the

applet. It contains the name of the parameter, a description of its type

and/or range, and an explanation of its purpose.

void init( ) Called when an applet begins execution. It is the first method called for

any applet.

boolean isActive( ) Returns true if the applet has been started. It returns false if the applet

has been stopped.

void play(URL url) If an audio clip is found at the location specified by url, the clip is

played.

void play(URL url, String

clipName)

If an audio clip is found at the location specified by url with the name

specified byclipName, the clip is played.

void resize(Dimension

dim)

Resizes the applet according to the dimensions specified by dim. It

contains two integer fields: width and height.

void resize(int width, int

height)

Resizes the applet according to the dimensions specified by width and

height.

void showStatus(String str

)

Displays strin the status window of the browser or applet viewer. If the

browser does not support a status window, then no action takes place.

void start( ) Called by the browser when an applet should start (or resume)

execution. It is automatically called after init( ) when an applet first

begins.

void stop( ) Called by the browser to suspend execution of the applet. Once stopped,

an applet is restarted when the browser calls start( ).

Example:

import java.awt.*;

import java.applet.*;

/*

<applet code="AppletSkel" width=300 height=100></applet>

*/

public class AppletSkel extends Applet {

public void init() {

// initialization

}

public void start() {

// start or resume execution

}

public void stop() {

// suspends execution

}

public void destroy() {

// perform shutdown activities

}

public void paint(Graphics g) {

// redisplay contents of window

}

}

The AudioClip Interface

The AudioClip interface defines these methods:

- play( ) - play a clip from the beginning.

- stop( ) - stop playing the clip.

- loop( ) - play the loop continuously.

After you have loaded an audio clip using getAudioClip( ), you can use these methods to play it.

The AppletStub Interface

The AppletStub interface provides the means by which an applet and the browser (or applet viewer)

communicate. Your code will not typically implement this interface.

The AppletContext Interface

AppletContext is an interface that lets we get information form the applet‘s execution environment.

The methods defined by AppletContext are:

Method Description

Applet getApplet(String

appletName)

Returns the applet specified by appletNameif it is within the current

applet context. Otherwise, null is returned.

Enumeration getApplets( ) Returns an enumeration that contains all of the applets within the

current applet context.

AudioClip

getAudioClip(URL url)

Returns an AudioClip object that encapsulates the audio clip found at

the location specified by url.

Image getImage(URL url) Returns an Image object that encapsulates the image found at the

location specified by url.

void showDocument(URL

url)

Brings the document at the URL specified by urlinto view. This

method may not be supported by applet viewers.

void showDocument(URL

url, String where)

Brings the document at the URL specified by url into view. This

method may not be supported by applet viewers. The placement of the

document is specified by where as described in the text.

void showStatus(String str) Displays strin the status window.

The Abstract Window Toolkit classes and Interfaces

The abstract window toolkit (AWT) contains numerous classes and methods that allow us to create

and manage windows. The AWT classes are contained in the java.awt package. It is one of Java‘s

largest packages.

They lists some of the many AWT classes are:

Class Description

AWTEvent Encapsulates AWT events.

BorderLayout The border layout manager. Border layouts use five components: North,

South, East, West, and Center.

Button Creates a push button control.

Canvas A blank, semantics-free window.

Checkbox Creates a check box control.

CheckboxGroup Creates a group of check box controls.

CheckboxMenuItem Creates an on/off menu item.

Choice Creates a pop-up list.

Color Manages colors in a portable, platform-independent fashion.

Component An abstract superclass for various AWT components.

Container A subclass of Component that can hold other components.

Cursor Encapsulates a bitmapped cursor.

Dialog Creates a dialog window.

Dimension Specifies the dimensions of an object. The width is stored in width, and the

height is stored in height.

Event Encapsulates events.

FileDialog Creates a window from which a file can be selected.

FlowLayout The flow layout manager. Flow layout positions components left to right, top

to bottom.

Font Encapsulates a type font.

FontMetrics Encapsulates various information related to a font. This information helps

you display text in a window.

Frame Creates a standard window that has a title bar, resize corners, and a menu bar.

Graphics Encapsulates the graphics context. This context is used by the various output

methods to display output in a window.

Label Creates a label that displays a string.

List Creates a list from which the user can choose. Similar to the standard

Windows list box.

Menu Creates a pull-down menu.

MenuBar Creates a menu bar.

MenuComponent An abstract class implemented by various menu classes.

MenuItem Creates a menu item.

Panel The simplest concrete subclass of Container.

Point Encapsulates a Cartesian coordinate pair, stored in x and y.

Polygon Encapsulates a polygon.

Rectangle Encapsulates a rectangle.

Scrollbar Creates a scroll bar control.

TextArea Creates a multiline edit control.

TextComponent A superclass for TextArea and TextField.

TextField Creates a single-line edit control.

Toolkit Abstract class implemented by the AWT.

Window Creates a window with no frame, no menu bar, and no title.

java.awt also defines these interfaces:

Adjustable

ItemSelectable

LayoutManager

LayoutManager2

MenuContainer

PrintGraphics

Shape

The BorderLayout Class:

The BorderLayout class implements a common layout style for top-level windows. The Border

layout class defines the five components: North, South, East, West, and Center.

Method Description

public BorderLayout( ) This is default constructor. It creates a default border layout.

public BorderLayout( int

horz, int vert )

It allows us to specify the horizontal and vertical space left between

components in horz and vert, respectively.

The Button Class:

A push button is a component that contains a label and that generates an event when it is pressed.

Method Description

Button(String str) throws

HeadlessException

It creates a button that contains str as a label.

synchronized void

addActionListener(

ActionListener al)

This method adds the ActionListener al to the set of objects that

will receive action events generated by the invoking object.

synchronized void

removeActionListener(

ActionListener al)

This method removes the ActionListener al from the set of

objects that will receive action events generated by the invoking

object.

String setActionCommand( String

c )

Sets to c the name of command associated with the action event

that will be generated by the invoking object.

String getLabel( ) Return the label of the invoking object.

void setLabel(String str) Set the new label of the invoking object to str.

void setActionCommand( String c

)

This method changes the action command string, but does not

affect the string used to label the button.

The Label Class:

A Label is an object of type Label, and it contains a string, which it displays. Labels are passive

controls that do not support any interaction with the user.Label defines the following constructors:

Label( ) throws HeadlessException

Label(String str) throws HeadlessException

Label(String str, int how) throws HeadlessException

The first version creates a blank label. The second version creates a label that contains the string

specified by str.This string is left-justified. The third version creates a label that contains the string

specified by str using the alignment specified by how. The value of how must be one of these three

constants:Label.LEFT,Label.RIGHT, or Label.CENTER.

You can set or change the text in a label by using the setText( ) method. You can obtain the current

label by calling getText( ). These methods are shown here:

void setText(String str)

String getText( )

For setText( ),str specifies the new label. For getText( ), the current label is returned.

The Checkbox Class:

A check box is a control that is used to turn an option on or off. It consists of a small box that can

either contain a check mark or not. There is a label associated with each check box that describes

what option the box represents. We change the state of a check box by clicking on it.

Check boxes can be used individually or as part of a group. Check boxes are objects of the Checkbox

class. Checkbox supports these constructors:

Checkbox( ) throws HeadlessException

Checkbox(String str) throws HeadlessException

Checkbox(String str, boolean on) throws HeadlessException

Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException

Checkbox(String str, CheckboxGroup cbGroup, boolean on) throws HeadlessException

The first form creates a check box whose label is initially blank. The state of the check box is

unchecked. The second form creates a check box whose label is specified by str.The state of the

check box is unchecked. The third form allows you to set the initial state of the check box. If on is

true, the check box is initially checked; otherwise, it is cleared. The fourth and fifth forms create a

check box whose label is specified by str and whose group is specified by cbGroup.If this check box

is not part of a group, then cbGroup must be null.

Method Description

void addItemListener(

ItemListener il)

This method adds the ItemListener il to the set of objects that will

receive action events generated by the invoking object.

void removeItemListener(

ItemListener il)

This method removes the ItemListener il from the set of objects that

will receive action events generated by the invoking object.

boolean getState( ) Return the state of the invoking object. it return true if the check box

is checked, otherwise it return false.

String getLabel( ) Return the label of the invoking object.

void setLabel(String str) Set the new label of the invoking object to str.

void setState(boolean on) It determines whether the invoking object is checked or not. If state is

true, the check box is displayed as checked. Otherwise it is cleared.

The CheckboxGroup Class:

To create a set of mutually exclusive check boxes, we must first define the group to which they will

belong and then specify that group when we construct the check boxes. Check box groups are objects

of type CheckboxGroup.

Only the default constructor is defined, which creates an empty group.

public CheckboxGroup()

You can determine which check box in a group is currently selected by calling

getSelectedCheckbox( ). You can set a check box by calling setSelectedCheckbox( ). These methods

are as follows:

Checkbox getSelectedCheckbox( )

void setSelectedCheckbox(Checkbox which)

Here, which is the check box that we want to be selected. The previously selected check box will be

turned off.

The Choice Class:

The Choice class is used to create apop-up list of items from which the user may choose. When

inactive, a Choicecomponent takes up only enough space to show the currently selected item. When

the user clicks on it, the whole list of choices pops up, and a new selection can be made.

Method Description

Choice() It creates an empty list.

void add(String str) Add the String object str to the choice list. It can throw a

NullPointerException.

String getSelectedItem( ) Returns a string containing the name of the currently selected item.

int getSelectedIndex( ) Returns the index of the currently selected item.

int getItemCount( ) Returns the number of items in the invoking object.

String getItem(int index) Returns the item that is stored at index in the invoking object. Indexing

begins at zero.

void select(int index) Selects the item at index in the invoking object. Indexing begins at zero.

void select(String str) Selects the item matching str in the invoking object.

The List Class:

The List class provides a compact, multiple-choice, scrolling selection list. A List object can be

constructed to show any number of choices in the visible window. It can also be created to allow

multiple selections. List provides these constructors:

List( ) throws HeadlessException

List(int numRows) throws HeadlessException

List(int numRows, boolean multipleSelect) throws HeadlessException

The first version creates aList control that allows only one item to be selected at any one time. In the

second form, the value of numRows specifies the number of entries in the list that will always be

visible (others can be scrolled into view as needed). In the third form, if multipleSelect is true, then

the user may select two or more items at a time. If it is false, then only one item may be selected.

Method Description

void addItem(String str) Add the String object str to the List.

String getSelectedItem( ) Returns a string containing the name of the currently selected item.

String[ ] getSelectedItems( ) Returns the string containing the name of the currently selected items.

int getSelectedIndex( ) Returns the index of the currently selected item.

int[ ] getSelectedIndexes( ) Returns the indexs of the currently selected items.

int getItemCount( ) Returns the number of items in the invoking object.

String getItem(int index) Returns the item that is stored at index in the invoking object.

void select(int index) Selects the item at index in the invoking object.

The TextField Class:

TheTextField class implements a single-line text-entry area, usually called anedit control.

TextFieldis a subclass of TextComponent.TextField defines the following constructors:

TextField( ) throws HeadlessException

TextField(int numChars) throws HeadlessException

TextField(String str) throws HeadlessException

TextField(String str, int numChars) throws HeadlessException

The first version creates a default text field. The second form creates a text field that is numChars

characters wide. The third form initializes the text field with the string contained in str.The fourth

form initializes a text field and sets its width.

Method Description

void addActionListener(

ActionListener al)

This method adds the ActionListener al to the set of objects that will

receive action events generated by the invoking object.

void removeActionListener(

ActionListener al)

This method removes the ActionListener al from the set of objects

that will receive action events generated by the invoking object.

The TextArea Class:

The TextArea class provides a simple multiline editor. Following are the constructors for TextArea:

TextArea( ) throws HeadlessException

TextArea(int nLines, int nChars) throws HeadlessException

TextArea(String str) throws HeadlessException

TextArea(String str, int nLines, int nChars) throws HeadlessException

TextArea(String str, int nLines, int nChars, int sBars) throws HeadlessException

Here, nLines specifies the height, in lines, of the textarea, and nChars specifies its width, in

characters. Initial text can be specified by str. In the fifth form, you can specify the scroll bars that

you want the control to have. sBars must be one of these values:

SCROLLBARS_BOTH SCROLLBARS_NONE

SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY

TextArea is a subclass of TextComponent. Therefore, it supports the getText( ),setText( ),

getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in the preceding

section.

TextArea adds the following methods:

void append(String str)

void insert(String str, int index)

void replaceRange(String str, int startIndex, int endIndex)

The append() method appends the string specified by str to the end of the current text. insert() inserts

the string passed instrat the specified index. To replace text, call replaceRange(). It replaces the

characters from startIndex to endIndex–1, with the replacement text passed in str.

Example:

import java.awt.*;

import java.applet.*;

/*

<applet code="TextAreaDemo" width=300 height=250></applet>

*/

public class TextAreaDemo extends Applet {

public void init() {

String val = "Bharathidasan University,\n Trichy.";

Label namep = new Label("Name: ", Label.RIGHT);

Label addp = new Label("Address: ", Label.RIGHT);

name = new TextField(12);

TextArea text = new TextArea(val, 10, 30);

add(namep);

add(name);

add(addp);

add(text);

}

}

The Font Class:

The AWT supports multiple type fonts. Fonts have a family name, a logical font name, and a face

name. The family name is thegeneral name of the font, such as Courier. Thelogical name specifies a

category of font, suchas Monospaced. The face name specifies a specific font, such as Courier Italic.

The Font class defines these variables:

Variable Meaning

String name Name of the font

float pointSize Size of the font in points

int size Size of the font in points

int style Font style

Fonts are encapsulated by the Font class. Several of the methods defined by Font are

Method Description

static Font decode(

String str)

Returns a font given its name.

static Font getFont(

String property)

Returns the font associated with the system property specified by property.null

is returned if property does not exist.

static Font getFont(

String property, Font

defaultFont)

Returns the font associated with the system property specified by property.The

font specified by defaultFontis returned if propertydoes not exist.

String getName( ) Returns the logical name of the invoking font.

int getSize( ) Returns the size, in points, of the invoking font.

int getStyle( ) Returns the style values of the invoking font.

boolean isBold( ) Returns true if the font includes the BOLD style value. Otherwise, return false.

boolean isItalic( ) Returns true if the font includes the ITALIC style value. Otherwise, return false.

boolean isPlain( ) Returns true if the font includes the PLAIN style value. Otherwise, return false.

String toString( ) Returns the string equivalent of the invoking font.

The FontMetrics Class:

The FontMetrics class, which encapsulates various information about a font. Let‘s begin by defining

the common terminology used when describing fonts:

Height The top-to-bottom size of a line of text

Baseline The line that the bottoms of characters are aligned to (not counting descent)

Ascent The distance from the baseline to the top of a character

Descent The distance from the baseline to the bottom of a character

Leading The distance between the bottom of one line of text and the top of the next

FontMetrics defines several methods that help you manage text output. Several commonly used ones

are listed in Table

Method Description

FontMetrics(Font f) It creates a FontMetrics object for the Font f.

int getHeight( ) Returns the height of a line of text. This value can be used to output

multiple lines of text in a window.

int stringWidth(String str) Returns the width of the string specified by str.

Example:

import java.applet.*;

import java.awt.*;

/*

<applet code="FontInfo" width=350 height=60></applet>

*/

public class FontInfo extends Applet {

public void init() {

Font f = new Font("SansSerif", Font.PLAIN, 12);

setFont(f);

}

public void paint(Graphics g) {

Font f = g.getFont();

String fontName = f.getName();

String fontFamily = f.getFamily();

int fontSize = f.getSize();

int fontStyle = f.getStyle();

String msg = "Family: " + fontName + ", Font: " + fontFamily;

msg += ", Size: " + fontSize + ", Style: ";

if((fontStyle & Font.BOLD) == Font.BOLD)

msg += "Bold ";

if((fontStyle & Font.ITALIC) == Font.ITALIC)

msg += "Italic ";

if((fontStyle & Font.PLAIN) == Font.PLAIN)

msg += "Plain ";

g.drawString(msg, 4, 16);

}

}

The Event Classes and Interfaces

java.awt.event is a new package that contains classes and interfaces related to the new way events

are handled.

The classes in java.awt.event are shown here:

Class Description

ActionEvent Generated when a button is pressed, double-clicked, or a menu item is selected.

AdjustmentEvent Generated when a scroll bar is manipulated.

ComponentEvent Generated when a component is hidden, moved, resized, or becomes visible.

ContainerEvent Generated when a component is added to or removed from a container.

FocusEvent Generated when a component gains or loses keyboard focus.

InputEvent Abstract superclass for all component input event classes.

ItemEvent Generated when a check box or list item is clicked; also occurs when a choice

selection is made or a checkable menu item is selected or deselected.

KeyEvent Generated when input is received from the keyboard.

MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released; also

generated when the mouse enters or exits a component.

TextEvent Generated when the value of a text area or text field is changed.

WindowEvent Generated when a window is activated, closed, deactivated, deiconified,

iconified, opened, or quit.

java.awt.event also defines these Interfaces:

Interface Description

ActionListener The listener interface for receiving action events.

AdjustmentListener The listener interface for receiving adjustment events.

FocusListener The listener interface for receiving keyboard focus events on a component.

ItemListener The listener interface for receiving item events.

KeyListener The listener interface for receiving keyboard events (keystrokes).

MouseListener The listener interface for receiving "interesting" mouse events (press,

release, click, enter, and exit) on a component.

MouseMotionListener The listener interface for receiving mouse motion events on a component.

WindowListener The listener interface for receiving window events.

The ActionEvent Class

An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item

is selected.

The ActionEvent class defines seven integer constants that can be used to identify any modifiers

associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK,

ACTION_PERFORMED, ACTION_FIRST, and ACTION_LAST.

You can obtain the command name for the invoking ActionEvent object by using the

getActionCommand( ) method, shown here:

String getActionCommand( )

The getModifiers() method returns a value that indicates which modifier keys (ALT,CTRL, META,

and/or SHIFT) were pressed when the event was generated. Its form is shown here:

int getModifiers( )

The AdjustmentEvent Class

An AdjustmentEvent is generated by a scroll bar. The AdjustmentEvent class defines integer

constants that can be used to identify them. The constants and their meanings are shown here:

BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its value.

BLOCK_INCREMENT The user clicked inside the scroll bar to increase its value.

TRACK The slider was dragged.

UNIT_DECREMENT The button at the end of the scroll bar was clicked to

decrease its value.

UNIT_INCREMENT The button at the end of the scroll bar was clicked to

increase its value.

ADJUSTMENT_VALUE_CHANGED That indicates that a change has occurred.

ADJUSTMENT_VALUE_FIRST That indicates that a starting value.

ADJUSTMENT_VALUE_LAST That indicates that an ending value.

The getAdjustable( ) method returns the object that generated the event. Its form is shown here:

Adjustable getAdjustable( )

The type of the adjustment event may be obtained by the getAdjustmentType( ) method. It returns

one of the constants defined by AdjustmentEvent. The general form is shown here:

int getAdjustmentType( )

The amount of the adjustment can be obtained from the getValue( ) method, shown here:

int getValue( )

For example, when a scroll bar is manipulated, this method returns the value represented by that

change.

The ItemEvent Class

An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item

is selected or deselected.

There are two types of item events, which are identified by the following integer constants:

DESELECTED - The user deselected an item.

SELECTED - The user selected an item.

ITEM_STATE_CHANGED - That signifies a change of state.

ITEM_ FIRST - That indicates that a starting value.

ITEM_ LAST - That indicates that an ending value.

The getItem( ) method can be used to obtain a reference to the item that generated an event. Its

signature is shown here:

Object getItem( )

The getItemSelectable( ) method can be used to obtain a reference to the ItemSelectable object that

generated an event. Its general form is shown here:

ItemSelectable getItemSelectable( )

Lists and choices are examples of user interface elements that implement the ItemSelectable

interface.

The getStateChange( ) method returns the state change (that is, SELECTED or DESELECTED) for

the event. It is shown here:

int getStateChange( )

The KeyEvent Class

A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are

identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The

first two events are generated when any key is pressed or released. The last event occurs only when a

character is generated.

Their general form of getKeyChar( ) method is:

char getKeyChar( )

This method which returns the character that was entered. If no valid character is available, then

getKeyChar( ) returns CHAR_UNDEFINED.

The MouseEvent Class

There are eight types of mouse events. The MouseEvent class defines the following integer constants

that can be used to identify them:

MOUSE_CLICKED - The user clicked the mouse.

MOUSE_DRAGGED - The user dragged the mouse.

MOUSE_ENTERED - The mouse entered a component.

MOUSE_EXITED - The mouse exited from a component.

MOUSE_MOVED - The mouse moved.

MOUSE_PRESSED - The mouse was pressed.

MOUSE_RELEASED - The mouse was released.

MOUSE _ FIRST - That indicates that a starting value.

MOUSE _ LAST - That indicates that an ending value.

Two commonly used methods in this class are getX() and getY(). These return the X and Y

coordinates of the mouse within the component when the event occurred. Their forms are shown

here: int getX( )

int getY( )

The WindowEvent Class

The WindowEvent class defines integer constants that can be used to identify them. The constants

and their meanings are shown here:

WINDOW_ACTIVATED - The window was activated.

WINDOW_CLOSED - The window has been closed.

WINDOW_CLOSING - The user requested that the window be closed.

WINDOW_DEACTIVATED - The window was deactivated.

WINDOW_DEICONIFIED - The window was deiconified.

WINDOW_GAINED_FOCUS - The window gained input focus.

WINDOW_ICONIFIED - The window was iconified.

WINDOW_LOST_FOCUS - The window lost input focus.

WINDOW_OPENED - The window was opened.

WINDOW_STATE_CHANGED - The state of the window changed.

WINDOW _ FIRST - That indicates that a starting value.

WINDOW _ LAST - That indicates that an ending value.

WindowEvent(Window src, int type)

Here, src is a reference to the object that generated this event. The type of the event is type.

Acommonly used method in this class is getWindow( ). It returns the Window object that generated

the event. Its general form is shown here:

Window getWindow( )

The ActionListener Interface

This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its

general form is shown here:

void actionPerformed(ActionEvent ae)

The AdjustmentListener Interface

This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment

event occurs. Its general form is shown here:

void adjustmentValueChanged(AdjustmentEvent ae)

The FocusListener Interface

Thisinterfacedefinestwomethods.Whenacomponentobtainskeyboardfocus,focusGained() is invoked.

When a component loses keyboard focus,focusLost( ) is called. Their general forms are shown here:

void focusGained(FocusEvent fe)

void focusLost(FocusEvent fe)

The ItemListener Interface

This interface defines the itemStateChanged( ) method that is invoked when the state of an item

changes. Its general form is shown here:

void itemStateChanged(ItemEvent ie)

The KeyListener Interface

This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked

when a key is pressed and released, respectively.The keyTyped() method is invoked when a

character has been entered. The general forms of these methods are shown here:

void keyPressed(KeyEvent ke)

void keyReleased(KeyEvent ke)

void keyTyped(KeyEvent ke)

The MouseListener Interface

This interface defines five methods. If the mouse is pressed and released at the same point,

mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is

called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased() methods

are invoked when the mouse is pressed and released, respectively.

The general forms of these methods are shown here:

void mouseClicked(MouseEvent me)

void mouseEntered(MouseEvent me)

void mouseExited(MouseEvent me)

void mousePressed(MouseEvent me)

void mouseReleased(MouseEvent me)

The MouseMotionListener Interface

This interface defines two methods. The mouseDragged( ) method is called multiple times as the

mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their

general forms are shown here:

void mouseDragged(MouseEvent me)

void mouseMoved(MouseEvent me)

The WindowListener Interface

This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods

are invoked when a window is activated or deactivated, respectively. If a window is iconified, the

windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( )

method is called. When a window is opened or closed, the windowOpened() or windowClosed()

methods are called, respectively. The windowClosing() method is called when a window is being

closed.

The general forms of these methods are

void windowActivated(WindowEvent we)

void windowClosed(WindowEvent we)

void windowClosing(WindowEvent we)

void windowDeactivated(WindowEvent we)

void windowDeiconified(WindowEvent we)

void windowIconified(WindowEvent we)

void windowOpened(WindowEvent we)

Example:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="SimpleKey" width=300 height=100></applet>

*/

public class SimpleKey extends Applet implements KeyListener {

String msg = "";

int X = 10, Y = 20;

public void init() {

addKeyListener(this);

addMouseListener(this);

}

public void mouseClicked(MouseEvent me) {

X = me.getX();

Y = me.getY();

showStatus("Mouse clicked ");

repaint();

}

public void keyPressed(KeyEvent ke) {

showStatus("Key Down");

}

public void keyReleased(KeyEvent ke) {

showStatus("Key Up");

}

public void keyTyped(KeyEvent ke) {

msg += ke.getKeyChar();

repaint();

}

public void paint(Graphics g) {

g.drawString(msg, X, Y);

}

}