method overloadingdeccancollege.ac.in/itlabmanuals/javalabmanualcbcs.pdf · method overloading is...

51
1 1) Write a Java program to illustrate the concept of class with method overloading Method Overloading In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java supports polymorphism. If you have never used a language that allows the overloading of methods, then the concept may seem strange at first. But as you will see, method overloading is one of Java’s most exciting and useful features. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different turn types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. // Demonstrate method overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); }

Upload: others

Post on 02-Aug-2020

16 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

1

1) Write a Java program to illustrate the concept of class with method overloading

Method Overloading

In Java it is possible to define two or more methods within the same class that share

the same name, as long as their parameter declarations are different. When this is the case, the

methods are said to be overloaded, and the process is referred to as method overloading.

Method overloading is one of the ways that Java supports polymorphism. If you have never

used a language that allows the overloading of methods, then the concept may seem strange at

first. But as you will see, method overloading is one of Java’s most exciting and useful

features. When an overloaded method is invoked, Java uses the type and/or number of

arguments as its guide to determine which version of the overloaded method to actually call.

Thus, overloaded methods must differ in the type and/or number of their parameters. While

overloaded methods may have different turn types, the return type alone is insufficient to

distinguish two versions of a method. When Java encounters a call to an overloaded method,

it simply executes the version of the method whose parameters match

the arguments used in the call.

// Demonstrate method overloading.

class OverloadDemo {

void test() {

System.out.println("No parameters");

}

// Overload test for one integer parameter.

void test(int a) {

System.out.println("a: " + a);

}

// Overload test for two integer parameters.

void test(int a, int b) {

System.out.println("a and b: " + a + " " + b);

}

// overload test for a double parameter

double test(double a) {

System.out.println("double a: " + a);

return a*a;

}

}

class Overload {

public static void main(String args[]) {

OverloadDemo ob = new OverloadDemo();

double result;

// call all versions of test()

ob.test();

ob.test(10);

ob.test(10, 20);

result = ob.test(123.25);

System.out.println("Result of ob.test(123.25): " + result);

}

Page 2: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

2

}

This program generates the following output:

No parameters

a: 10

a and b: 10 20

double a: 123.25

Result of ob.test(123.25): 15190.5625

Page 3: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

3

2) Write a Java Program that reads a line of integers, and then displays each integer, and

the sum of all the integers (Use String Tokenizer class of java. util)

String Tokenizer

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. The StringTokenizer class provides the first step in this parsing process,

often called the lexer (lexical analyzer) or scanner. StringTokenizer implements the

Enumeration interface. Therefore, given an input string, you can enumerate the individual

tokens contained in it using StringTokenizer.

To use StringTokenizer, you 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 whitespace 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)

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.

import java.util.StringTokenizer;

import java.util.Scanner;

public class Lineofint

{

public static void main(String args[])

{

Scanner scan = new Scanner(System.in);

String s = scan.next();

StringTokenizer st = new StringTokenizer(s," ");

while (st.hasMoreTokens())

{

System.out.println(st.nextToken());

} } }

Page 4: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

4

3) Write a Java program to illustrate the concept of Single level and Multi level

Inheritance.

Inheritance

In the terminology of Java, a class that is inherited is called a superclass. The class that does

the inheriting is called a subclass.

To inherit a class, you simply incorporate the definition of one class into another by using the

extends keyword. To see how, let’s begin with a short example. The following program

creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.

However, you can build hierarchies that contain as many layers of inheritance as you like. As

mentioned, it is perfectly acceptable to use a subclass as a superclass of another.

For example, given three classes called A, B, and C, C can be a subclass of B, which is a

subclass of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.

// This program uses inheritance to extend Box.

class Box {

double width;

double height;

double depth;

// construct clone of an object

Box(Box ob) { // pass object to constructor

width = ob.width;

height = ob.height;

depth = ob.depth;

}

// constructor used when all dimensions specified

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

// constructor used when no dimensions specified

Box() {

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

}

// constructor used when cube is created

Box(double len) {

width = height = depth = len;

}

// compute and return volume

double volume() {

Page 5: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

5

return width * height * depth;

}

}

// Here, Box is extended to include weight.

class BoxWeight extends Box {

double weight; // weight of box

// constructor for BoxWeight

BoxWeight(double w, double h, double d, double m) {

width = w;

height = h;

depth = d;

weight = m;

}

}

class DemoBoxWeight {

public static void main(String args[]) {

BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);

BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);

double vol;

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

System.out.println("Weight of mybox1 is " + mybox1.weight);

System.out.println();

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

System.out.println("Weight of mybox2 is " + mybox2.weight);

}

}

The output from this program is shown here:

Volume of mybox1 is 3000.0

Weight of mybox1 is 34.3

Volume of mybox2 is 24.0

Weight of mybox2 is 0.076

// Extend BoxWeight to include shipping costs.

// Start with Box.

class Box {

private double width;

private double height;

private double depth;

// construct clone of an object

Box(Box ob) { // pass object to constructor

width = ob.width;

height = ob.height;

depth = ob.depth;

Page 6: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

6

}

// constructor used when all dimensions specified

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

// constructor used when no dimensions specified

Box() {

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

}

// constructor used when cube is created

Box(double len) {

width = height = depth = len;

}

// compute and return volume

double volume() {

return width * height * depth;

}

}

// Add weight.

class BoxWeight extends Box {

double weight; // weight of box

// construct clone of an object

BoxWeight(BoxWeight ob) { // pass object to constructor

super(ob);

weight = ob.weight;

}

// constructor when all parameters are specified

BoxWeight(double w, double h, double d, double m) {

super(w, h, d); // call superclass constructor

weight = m;

}

// default constructor

BoxWeight() {

super();

weight = -1;

}

// constructor used when cube is created

BoxWeight(double len, double m) {

super(len);

weight = m;

}

}

// Add shipping costs.

class Shipment extends BoxWeight {

Page 7: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

7

double cost;

// construct clone of an object

Shipment(Shipment ob) { // pass object to constructor

super(ob);

cost = ob.cost;

}

// constructor when all parameters are specified

Shipment(double w, double h, double d,

double m, double c) {

super(w, h, d, m); // call superclass constructor

cost = c;

}

// default constructor

Shipment() {

super();

cost = -1;

}

// constructor used when cube is created

Shipment(double len, double m, double c) {

super(len, m);

cost = c;

}

}

class DemoShipment {

public static void main(String args[]) {

Shipment shipment1 =

new Shipment(10, 20, 15, 10, 3.41);

Shipment shipment2 =

new Shipment(2, 3, 4, 0.76, 1.28);

double vol;

vol = shipment1.volume();

System.out.println("Volume of shipment1 is " + vol);

System.out.println("Weight of shipment1 is "

+ shipment1.weight);

System.out.println("Shipping cost: $" + shipment1.cost);

System.out.println();

vol = shipment2.volume();

System.out.println("Volume of shipment2 is " + vol);

System.out.println("Weight of shipment2 is "

+ shipment2.weight);

System.out.println("Shipping cost: $" + shipment2.cost); }}

The output of this program is shown here:

Volume of shipment1 is 3000.0

Weight of shipment1 is 10.0

Shipping cost: $3.41

Volume of shipment2 is 24.0

Weight of shipment2 is 0.76

Shipping cost: $1.28

Page 8: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

8

4) Write a Java program to demonstrate the Interfaces & Abstract Classes.

Abstract Class and Interface

You can require that certain methods be overridden by subclasses by specifying the

abstract type modifier. These methods are sometimes referred to as subclasser responsibility

because they have no implementation specified in the superclass. Thus, a subclass must override

them—it cannot simply use the version defined in the superclass. To declare an abstract

method, use this general form:

abstract type name(parameter-list);

As you can see, no method body is present.

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

declare a class abstract, you simply use the abstract keyword in front of the class keyword at

the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator.

Interfaces

are syntactically similar to classes, but they lack instance variables, and their methods are

declared without any body. In practice, this means that you can define interfaces that don’t

make assumptions about how they are implemented. Once it is defined, any number of classes

can implement an interface. Also, one class can implement any number of interfaces.

To implement an interface, a class must create the complete set of methods defined by the

interface. However, each class is free to determine the details of its own implementation. By

providing the interface keyword, Java allows you to fully utilize the “one interface, multiple methods” aspect of polymorphism.

An interface is defined much like a class. This is the general form of an interface:

access interface name {

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;

}

// Using abstract methods and classes.

abstract class Figure {

double dim1;

double dim2;

Figure(double a, double b) {

dim1 = a;

dim2 = b;

}

// area is now an abstract method

Page 9: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

9

abstract double area();

}

class Rectangle extends Figure {

Rectangle(double a, double b) {

super(a, b);

}

// override area for rectangle

double area() {

System.out.println("Inside Area for Rectangle.");

return dim1 * dim2;

}

}

class Triangle extends Figure {

Triangle(double a, double b) {

super(a, b);

}

// override area for right triangle

double area() {

System.out.println("Inside Area for Triangle.");

return dim1 * dim2 / 2;

}

}

class AbstractAreas {

public static void main(String args[]) {

// Figure f = new Figure(10, 10); // illegal now

Rectangle r = new Rectangle(9, 5);

Triangle t = new Triangle(10, 8);

Figure figref; // this is OK, no object is created

figref = r;

System.out.println("Area is " + figref.area());

figref = t;

System.out.println("Area is " + figref.area()); } }

Interface Program

interface Callback {

void callback(int param);

}

class Client implements Callback {

// Implement Callback's interface

public void callback(int p) {

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

}

}

class TestIface {

public static void main(String args[]) {

Callback c = new Client();

c.callback(42); } }

Page 10: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

10

5) Write a Java program to implement the concept of exception handling.

Exception Handling

Java exception handling is managed via five keywords: try, catch, throw, throws,

and finally. Briefly, here is how they work. Program statements that you want to monitor for

exceptions are contained within a try block. If an exception occurs within the try block, it is

thrown. Your 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.

To manually throw an exception, use the keyword throw. Any exception that is thrown out of

a method must be specified as such by a throws clause. Any code that absolutely must be

executed after a try block completes is put in a finally block.

This is the general form of an exception-handling block:

try {

// block of code to monitor for errors

}

catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

}

catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2

}

// ...

finally {

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

}

class Exc2 {

public static void main(String args[]) {

int d, a;

try { // monitor a block of code.

d = 0;

a = 42 / d;

System.out.println("This will not be printed.");

} catch (ArithmeticException e) { // catch divide-by-zero error

System.out.println("Division by zero.");

}

System.out.println("After catch statement.");

}

}

This program generates the following output:

Division by zero.

After catch statement.

Page 11: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

11

// Demonstrate throw.

class ThrowDemo {

static void demoproc() {

try {

throw new NullPointerException("demo");

} catch(NullPointerException e) {

System.out.println("Caught inside demoproc.");

throw e; // rethrow the exception

}

}

public static void main(String args[]) {

try {

demoproc();

} catch(NullPointerException e) {

System.out.println("Recaught: " + e);

}

}

}

Caught inside demoproc.

Recaught: java.lang.NullPointerException: demo

// This is now correct.

class ThrowsDemo {

static void throwOne() throws IllegalAccessException {

System.out.println("Inside throwOne.");

throw new IllegalAccessException("demo");

}

public static void main(String args[]) {

try {

throwOne();

} catch (IllegalAccessException e) {

System.out.println("Caught " + e);

}

}

}

Here is the output generated by running this example program:

inside throwOne

caught java.lang.IllegalAccessException: demo

// Demonstrate finally.

class FinallyDemo {

// Through an exception out of the method.

static void procA() {

Page 12: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

12

try {

System.out.println("inside procA");

throw new RuntimeException("demo");

} finally {

System.out.println("procA's finally");

}

}

// Return from within a try block.

static void procB() {

try {

System.out.println("inside procB");

return;

} finally {

System.out.println("procB's finally");

}

}

// Execute a try block normally.

static void procC() {

try {

System.out.println("inside procC");

} finally {

System.out.println("procC's finally");

}

}

public static void main(String args[]) {

try {

procA();

} catch (Exception e) {

System.out.println("Exception caught");

}

procB();

procC();

}

}

Here is the output generated by the preceding program:

inside procA

procA’s finally

Exception caught

inside procB

procB’s finally

inside procC

procC’s finally

Page 13: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

13

6) Write a Java program to illustrate the concept of threading using Thread Class and runnable

Interface.

Multithreading

The Java run-time system depends on threads for many things, and all the class

libraries are designed with multithreading in mind. In fact, Java uses threads to enable the

entire environment to be asynchronous. This helps reduce inefficiency by preventing the

waste of CPU cycles.

The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated.

One thread can pause without stopping other parts of your program. For example, the idle

time created when a thread reads data from a network or waits for user input can be utilized

elsewhere. Multithreading allows animation loops to sleep for a second between each frame

without causing the whole system to pause. When a thread blocks in a Java program, only the

single thread that is blocked pauses. All other threads continue to run.

Threads exist in several states. A thread can be running. It can be ready to run as soon as it

gets CPU time. Arunning thread can be suspended, which temporarily suspends its activity.

Asuspended thread can then be resumed, allowing it to pick up where it left off. A thread can

be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

In the most general sense, you create a thread by instantiating an object of type Thread.

Java defines two ways in which this can be accomplished:

• You can implement the Runnable interface.

• You can extend the Thread class, itself.

// Create a second thread.

class NewThread implements Runnable {

Thread t;

NewThread() {

// Create a new, second thread

t = new Thread(this, "Demo Thread");

System.out.println("Child thread: " + t);

t.start(); // Start the thread

}

// This is the entry point for the second thread.

public void run() {

try {

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

System.out.println("Child Thread: " + i);

Thread.sleep(500);

}

} catch (InterruptedException e) {

System.out.println("Child interrupted.");

}

System.out.println("Exiting child thread.");

}

Page 14: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

14

}

class ThreadDemo {

public static void main(String args[]) {

new NewThread(); // create a new thread

try {

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

System.out.println("Main Thread: " + i);

Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println("Main thread interrupted.");

}

System.out.println("Main thread exiting.");

}

}

Child thread: Thread[Demo Thread,5,main]

Main Thread: 5

Child Thread: 5

Child Thread: 4

Main Thread: 4

Child Thread: 3

Child Thread: 2

Main Thread: 3

Child Thread: 1

Exiting child thread.

Main Thread: 2

Main Thread: 1

Main thread exiting.

// Create a second thread by extending Thread

class NewThread extends Thread {

NewThread() {

// Create a new, second thread

super("Demo Thread");

System.out.println("Child thread: " + this);

start(); // Start the thread

}

// This is the entry point for the second thread.

public void run() {

try {

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

System.out.println("Child Thread: " + i);

Thread.sleep(500);

}

} catch (InterruptedException e) {

System.out.println("Child interrupted.");

}

Page 15: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

15

System.out.println("Exiting child thread.");

}

}

class ExtendThread {

public static void main(String args[]) {

new NewThread(); // create a new thread

try {

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

System.out.println("Main Thread: " + i);

Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println("Main thread interrupted.");

}

System.out.println("Main thread exiting.");

}

}

Page 16: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

16

7) Write a Java program to illustrate the concept of Thread synchronization.

Synchroinzation

When two or more threads need access to a shared resource, they need some way to

ensure that the resource will be used by only one thread at a time. The process by which this

is achieved is called synchronization. As you will see, Java provides unique, language-level

support for it. Key to synchronization is the concept of the monitor (also called a semaphore).

A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread

can own a monitor at a given time. When a thread acquires a lock, it is said to have entered

the monitor All other threads attempting to enter the locked monitor will be suspended until

the first thread exits the monitor. These other threads are said to be waiting for the monitor. A

thread that owns a monitor can reenter the same monitor if it so desires.

You simply put calls to the methods defined by this class inside

a synchronized block.

This is the general form of the synchronized statement:

synchronized(object) {

// statements to be synchronized

}

// This program uses a synchronized block.

class Callme {

void call(String msg) {

System.out.print("[" + msg);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("Interrupted");

}

System.out.println("]");

}

}

class Caller implements Runnable {

String msg;

Callme target;

Thread t;

public Caller(Callme targ, String s) {

target = targ;

msg = s;

t = new Thread(this);

t.start();

}

// synchronize calls to call()

public void run() {

Page 17: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

17

synchronized(target) { // synchronized block

target.call(msg);

}

}

}

class Synch1 {

public static void main(String args[]) {

Callme target = new Callme();

Caller ob1 = new Caller(target, "Hello");

Caller ob2 = new Caller(target, "Synchronized");

Caller ob3 = new Caller(target, "World");

// wait for threads to end

try {

ob1.t.join();

ob2.t.join();

ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

}

}

[Hello]

[Synchronized]

[World]

Page 18: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

18

8) Write a Java program that correctly implements producer consumer problem using the

concept of inter thread communication.

Inter thread communication

Java includes an elegant interprocess communication mechanism via the wait( ),

notify( ), and notifyAll( ) methods. These methods are implemented as final methods in

Object, so all classes have them. All three methods can be called only from within a

synchronized context. Although conceptually advanced from a computer science perspective,

the rules for using these methods are actually quite simple:

• wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread

enters the same monitor and calls notify( ).

• notify( ) wakes up a thread that called wait( ) on the same object.

• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will be granted access.

// A correct implementation of a producer and consumer.

class Q {

int n;

boolean valueSet = false;

synchronized int get() {

while(!valueSet)

try {

wait();

} catch(InterruptedException e) {

System.out.println("InterruptedException caught");

}

System.out.println("Got: " + n);

valueSet = false;

notify();

return n;

}

synchronized void put(int n) {

while(valueSet)

try {

wait();

} catch(InterruptedException e) {

System.out.println("InterruptedException caught");

}

this.n = n;

valueSet = true;

System.out.println("Put: " + n);

notify();

}

}

class Producer implements Runnable {

Q q;

Producer(Q q) {

Page 19: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

19

this.q = q;

new Thread(this, "Producer").start();

}

public void run() {

int i = 0;

while(true) {

q.put(i++);

}

}

}

class Consumer implements Runnable {

Q q;

Consumer(Q q) {

this.q = q;

new Thread(this, "Consumer").start();

}

public void run() {

while(true) {

q.get();

}

}

}

class PCFixed {

public static void main(String args[]) {

Q q = new Q();

new Producer(q);

new Consumer(q);

System.out.println("Press Control-C to stop.");

}

}

Put: 1

Got: 1

Put: 2

Got: 2

Put: 3

Got: 3

Put: 4

Got: 4

Put: 5

Got: 5

Page 20: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

20

9) Write a Java program to illustrate collection classes like Array List, LinkedList, Tree map

and Hash map.

Collection Framework and Classes

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 for managing groups of objects.

The ArrayList class extends AbstractList and implements the List interface. ArrayList is a

generic class that has this declaration:

class ArrayList<E>

Here, E specifies the type of objects that the list will hold.

ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a

fixed length. After arrays are created, they cannot grow or shrink, which means that you must

know in advance how many elements an array will hold.

The LinkedList class extends AbstractSequentialList and implements the List, Deque, and

Queue interfaces. It provides a linked-list data structure. LinkedList is a generic class that

has this declaration:

class LinkedList<E>

The HashMap class extends AbstractMap and implements the Map interface. It uses a hash

table to store the map. This allows the execution time of get( ) and put( ) to remain constant

even for large sets. HashMap is a generic class that has this declaration:

class HashMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

The following constructors are defined:

HashMap( )

HashMap(Map<? extends K, ? extends V> m)

The TreeMap class extends AbstractMap and implements the NavigableMap interface. It

creates maps stored in a tree structure. A TreeMap provides an efficient means of storing

key/value pairs in sorted order and allows rapid retrieval. You should note that, unlike a hash

map, a tree map guarantees that its elements will be sorted in ascending key order. TreeMap

is a generic class that has this declaration:

class TreeMap<K, V>

// Demonstrate ArrayList.

import java.util.*;

class ArrayListDemo {

public static void main(String args[]) {

// Create an array list.

ArrayList<String> al = new ArrayList<String>();

System.out.println("Initial size of al: " +

Page 21: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

21

al.size());

// Add elements to the array list.

al.add("C");

al.add("A");

al.add("E");

al.add("B");

al.add("D");

al.add("F");

al.add(1, "A2");

System.out.println("Size of al after additions: " +

al.size());

// Display the array list.

System.out.println("Contents of al: " + al);

// Remove elements from the array list.

al.remove("F");

al.remove(2);

System.out.println("Size of al after deletions: " +

al.size());

System.out.println("Contents of al: " + al);

}

}

The output from this program is shown here:

Initial size of al: 0

Size of al after additions: 7

Contents of al: [C, A2, A, E, B, D, F]

Size of al after deletions: 5

Contents of al: [C, A2, E, B, D]

// Demonstrate LinkedList.

import java.util.*;

class LinkedListDemo {

public static void main(String args[]) {

// Create a linked list.

LinkedList<String> ll = new LinkedList<String>();

// Add elements to the linked list.

ll.add("F");

ll.add("B");

ll.add("D");

ll.add("E");

ll.add("C");

ll.addLast("Z");

ll.addFirst("A");

ll.add(1, "A2");

System.out.println("Original contents of ll: " + ll);

// Remove elements from the linked list.

ll.remove("F");

Page 22: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

22

ll.remove(2);

System.out.println("Contents of ll after deletion: "

+ ll);

// Remove first and last elements.

ll.removeFirst();

ll.removeLast();

System.out.println("ll after deleting first and last: "

+ ll);

// Get and set a value.

String val = ll.get(2);

ll.set(2, val + " Changed");

System.out.println("ll after change: " + ll);

}

}

The output from this program is shown here:

Original contents of ll: [A, A2, F, B, D, E, C, Z]

Contents of ll after deletion: [A, A2, D, E, C, Z]

ll after deleting first and last: [A2, D, E, C]

ll after change: [A2, D, E Changed, C]

import java.util.*;

class HashMapDemo {

public static void main(String args[]) {

// Create a hash map.

HashMap<String, Double> hm = new HashMap<String, Double>();

// Put elements to the map

hm.put("John Doe", new Double(3434.34));

hm.put("Tom Smith", new Double(123.22));

hm.put("Jane Baker", new Double(1378.00));

hm.put("Tod Hall", new Double(99.22));

hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries.

Set<Map.Entry<String, Double>> set = hm.entrySet();

// Display the set.

for(Map.Entry<String, Double> me : set) {

System.out.print(me.getKey() + ": ");

System.out.println(me.getValue());

}

System.out.println();

// Deposit 1000 into John Doe's account.

double balance = hm.get("John Doe");

hm.put("John Doe", balance + 1000);

System.out.println("John Doe's new balance: " +

hm.get("John Doe"));

}

}

Page 23: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

23

Output from this program is shown here (the precise order may vary):

Ralph Smith: -19.08

Tom Smith: 123.22

John Doe: 3434.34

Tod Hall: 99.22

Jane Baker: 1378.0

John Doe’s new balance: 4434.34

import java.util.*;

class TreeMapDemo {

public static void main(String args[]) {

// Create a tree map.

TreeMap<String, Double> tm = new TreeMap<String, Double>();

// Put elements to the map.

tm.put("John Doe", new Double(3434.34));

tm.put("Tom Smith", new Double(123.22));

tm.put("Jane Baker", new Double(1378.00));

tm.put("Tod Hall", new Double(99.22));

tm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries.

Set<Map.Entry<String, Double>> set = tm.entrySet();

// Display the elements.

for(Map.Entry<String, Double> me : set) {

System.out.print(me.getKey() + ": ");

System.out.println(me.getValue());

}

System.out.println();

// Deposit 1000 into John Doe's account.

double balance = tm.get("John Doe");

tm.put("John Doe", balance + 1000);

System.out.println("John Doe's new balance: " +

tm.get("John Doe"));

}

}

The following is the output from this program:

Jane Baker: 1378.0

John Doe: 3434.34

Ralph Smith: -19.08

Todd Hall: 99.22

Tom Smith: 123.22

John Doe’s current balance: 4434.34

Page 24: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

24

10) Write a Java program to illustrate Legacy classes like Vector, Hashtable, Dictionary &

Enumeration interface

Legacy Classes

Early versions of java.util did not include the Collections Framework. Instead, it

defined several classes and an interface that provided an ad hoc method of storing objects.

When collections were added (by J2SE 1.2), several of the original classes were reengineered

to support the collection interfaces. Thus, they are fully compatible with the framework.

The legacy classes defined by java.util are shown here:

Dictionary Hashtable Properties Stack Vector

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

Vector is synchronized, and it contains many legacy methods that are not part of the Collections

Vector is declared like this:

class Vector<E>

Here, E specifies the type of element that will be stored.

Here are the Vector constructors:

Vector( )

Vector(int size)

Vector(int size, int incr)

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

However, with the advent of collections, Hashtable was reengineered to also implement the

Map interface. Thus, Hashtable is now integrated into the Collections Framework. It is so

Similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. However, neither keys nor

values can be null. When using a Hashtable, you specify an object that is used as a key, and

the value that you want linked to that key. The key is then hashed, and the resulting hash code

is used as the index at which the value is stored within the table.

Hashtable was made generic by JDK 5. It is declared like this:

class Hashtable<K, V>

// Demonstrate various Vector operations.

import java.util.*;

class VectorDemo {

public static void main(String args[]) {

// initial size is 3, increment is 2

Vector<Integer> v = new Vector<Integer>(3, 2);

System.out.println("Initial size: " + v.size());

System.out.println("Initial capacity: " +

v.capacity());

v.addElement(1);

v.addElement(2);

v.addElement(3);

v.addElement(4);

Page 25: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

25

System.out.println("Capacity after four additions: " +

v.capacity());

v.addElement(5);

System.out.println("Current capacity: " +

v.capacity());

v.addElement(6);

v.addElement(7);

System.out.println("Current capacity: " +

v.capacity());

v.addElement(9);

v.addElement(10);

System.out.println("Current capacity: " +

v.capacity());

v.addElement(11);

v.addElement(12);

System.out.println("First element: " + v.firstElement());

System.out.println("Last element: " + v.lastElement());

if(v.contains(3))

System.out.println("Vector contains 3.");

// Enumerate the elements in the vector.

Enumeration vEnum = v.elements();

System.out.println("\nElements in vector:");

while(vEnum.hasMoreElements())

System.out.print(vEnum.nextElement() + " ");

System.out.println();

}

}

The output from this program is shown here:

Initial size: 0

Initial capacity: 3

Capacity after four additions: 5

Current capacity: 5

Current capacity: 7

Current capacity: 9

First element: 1

Last element: 12

Vector contains 3.

Elements in vector:

1 2 3 4 5 6 7 9 10 11 12

// Demonstrate a Hashtable.

import java.util.*;

class HTDemo {

public static void main(String args[]) {

Hashtable<String, Double> balance =

new Hashtable<String, Double>();

Page 26: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

26

Enumeration<String> names;

String str;

double bal;

balance.put("John Doe", 3434.34);

balance.put("Tom Smith", 123.22);

balance.put("Jane Baker", 1378.00);

balance.put("Tod Hall", 99.22);

balance.put("Ralph Smith", -19.08);

// Show all balances in hashtable.

names = balance.keys();

while(names.hasMoreElements()) {

str = names.nextElement();

System.out.println(str + ": " +

balance.get(str));

}

System.out.println();

// Deposit 1,000 into John Doe's account.

bal = balance.get("John Doe");

balance.put("John Doe", bal+1000);

System.out.println("John Doe's new balance: " +

balance.get("John Doe"));

}

}

The output from this program is shown here:

Todd Hall: 99.22

Ralph Smith: -19.08

John Doe: 3434.34

Jane Baker: 1378.0

Tom Smith: 123.22

John Doe’s new balance: 4434.34

Dictionary

import java.util.*;

class DictionaryDemo {

public static void main(String args[]) {

// Create a hash map.

HashMap<String, Double> hm = new HashMap<String, Double>();

// Put elements to the map

hm.put("John Doe", new Double(3434.34));

hm.put("Tom Smith", new Double(123.22));

hm.put("Jane Baker", new Double(1378.00));

hm.put("Tod Hall", new Double(99.22));

hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries.

Set<Map.Entry<String, Double>> set = hm.entrySet();

// Display the set.

Page 27: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

27

for(Map.Entry<String, Double> me : set) {

System.out.print(me.getKey() + ": ");

System.out.println(me.getValue());

}

System.out.println();

// Deposit 1000 into John Doe's account.

double balance = hm.get("John Doe");

hm.put("John Doe", balance + 1000);

System.out.println("John Doe's new balance: " +

hm.get("John Doe"));

}

}

Page 28: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

28

11) Write a Java program to implement iteration over Collection using Iterator interface and

ListIterator interface

// Demonstrate iterators.

import java.util.*;

class IteratorDemo {

public static void main(String args[]) {

// Create an array list.

ArrayList<String> al = new ArrayList<String>();

// Add elements to the array list.

al.add("C");

al.add("A");

al.add("E");

al.add("B");

al.add("D");

al.add("F");

// Use iterator to display contents of al.

System.out.print("Original contents of al: ");

Iterator<String> itr = al.iterator();

while(itr.hasNext()) {

String element = itr.next();

System.out.print(element + " ");

}

System.out.println();

// Modify objects being iterated.

ListIterator<String> litr = al.listIterator();

while(litr.hasNext()) {

String element = litr.next();

litr.set(element + "+");

}

System.out.print("Modified contents of al: ");

itr = al.iterator();

while(itr.hasNext()) {

String element = itr.next();

System.out.print(element + " ");

}

System.out.println();

// Now, display the list backwards.

System.out.print("Modified list backwards: ");

while(litr.hasPrevious()) {

String element = litr.previous();

System.out.print(element + " ");

}

System.out.println();

} }

The output is shown here:

Original contents of al: C A E B D F

Modified contents of al: C+ A+ E+ B+ D+ F+

Modified list backwards: F+ D+ B+ E+ A+ C+

Page 29: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

29

12) Write a Java program that reads a file name from the user, and then displays information

about whether the file exists, whether the file is readable, whether the file is writable, the type

of file and the length of the file in bytes.

File

Although most of the classes defined by java.io operate on streams, the File class does

not. It deals directly with files and the file system. That is, the File class does not specify how

information is retrieved from or stored in files; it describes the properties of a file itself. A

File object is used to obtain or manipulate the information associated with a disk file, such as

the permissions, time, date, and directory path, and to navigate subdirectory hierarchies. Files

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

severe restrictions on their use within applets for security reasons, files are still a central

resource for storing persistent and shared information. A directory in Java is treated simply as

a File with one additional property—a list of filenames that can be examined by

the list( ) method.

The following constructors can be used to create File objects:

File(String directoryPath)

File(String directoryPath, String filename)

File(File dirObj, String filename)

File(URI uriObj)

Java’s stream-based I/O is built upon four abstract classes: InputStream, OutputStream,

Reader, and Writer. These classes were briefly discussed in Chapter 13. They are used to

create several concrete stream subclasses. Although your programs perform their I/O

operations through concrete subclasses, the top-level classes define the basic functionality

common to all stream classes.

InputStream and OutputStream are designed for byte streams. Reader and Writer are

designed for character streams. The byte stream classes and the character stream classes form

separate hierarchies. In general, you should use the character stream classes when working

with characters or strings, and use the byte stream classes when working with bytes or other binary objects.

// Demonstrate File.

import java.io.File;

class FileDemo {

static void p(String s) {

System.out.println(s);

}

public static void main(String args[]) {

File f1 = new File("/java/COPYRIGHT");

p("File Name: " + f1.getName());

p("Path: " + f1.getPath());

p("Abs Path: " + f1.getAbsolutePath());

p("Parent: " + f1.getParent());

p(f1.exists() ? "exists" : "does not exist");

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

p(f1.canRead() ? "is readable" : "is not readable");

Page 30: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

30

p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));

p(f1.isFile() ? "is normal file" : "might be a named pipe");

p(f1.isAbsolute() ? "is absolute" : "is not absolute");

p("File last modified: " + f1.lastModified());

p("File size: " + f1.length() + " Bytes");

}

}

File Name: COPYRIGHT

Path: /java/COPYRIGHT

Abs Path: /java/COPYRIGHT

Parent: /java

exists

is writeable

is readable

is not a directory

is normal file

is absolute

File last modified: 812465204000

File size: 695 Bytes

Page 31: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

31

13) Write a Java program to illustrate the concept of I/O Streams

// Demonstrate FileInputStream.

import java.io.*;

class FileInputStreamDemo {

public static void main(String args[]) throws IOException {

int size;

InputStream f =

new FileInputStream("FileInputStreamDemo.java");

System.out.println("Total Available Bytes: " +

(size = f.available()));

int n = size/40;

System.out.println("First " + n +

" bytes of the file one read() at a time");

for (int i=0; i < n; i++) {

System.out.print((char) f.read());

}

System.out.println("\nStill Available: " + f.available());

System.out.println("Reading the next " + n +

" with one read(b[])");

byte b[] = new byte[n];

if (f.read(b) != n) {

System.err.println("couldn't read " + n + " bytes.");

}

System.out.println(new String(b, 0, n));

System.out.println("\nStill Available: " + (size = f.available()));

System.out.println("Skipping half of remaining bytes with skip()");

f.skip(size/2);

System.out.println("Still Available: " + f.available());

System.out.println("Reading " + n/2 + " into the end of array");

if (f.read(b, n/2, n/2) != n/2) {

System.err.println("couldn't read " + n/2 + " bytes.");

}

System.out.println(new String(b, 0, b.length));

System.out.println("\nStill Available: " + f.available());

f.close();

}

}

Here is the output produced by this program:

Total Available Bytes: 1433

First 35 bytes of the file one read() at a time

// Demonstrate FileInputStream.

im

Still Available: 1398

Reading the next 35 with one read(b[])

port java.io.*;

class FileInputS

Still Available: 1363

Page 32: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

32

Skipping half of remaining bytes with skip()

Still Available: 682

Reading 17 into the end of array

port java.io.*;

read(b) != n) {

S

Still Available: 665

// Demonstrate FileOutputStream.

import java.io.*;

class FileOutputStreamDemo {

public static void main(String args[]) throws IOException {

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();

OutputStream f1 = new FileOutputStream("file2.txt");

f1.write(buf);

f1.close();

OutputStream f2 = new FileOutputStream("file3.txt");

f2.write(buf,buf.length-buf.length/4,buf.length/4);

f2.close();

}

}

Here are the contents of each file after running this program. First, file1.txt:

Nwi h iefralgo e

t oet h i ftercuty n a hi u ae.

Next, file2.txt:

Now is the time for all good men

to come to the aid of their country

and pay their due taxes.

Finally, file3.txt:

nd pay their due taxes.

Page 33: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

33

14) Write a Java program to implement serialization concept

import java.io.*;

public class SerializationDemo {

public static void main(String args[]) {

// Object serialization

try {

MyClass object1 = new MyClass("Hello", -7, 2.7e10);

System.out.println("object1: " + object1);

FileOutputStream fos = new FileOutputStream("serial");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(object1);

oos.flush();

oos.close();

}

catch(IOException e) {

System.out.println("Exception during serialization: " + e);

System.exit(0);

}

// Object deserialization

try {

MyClass object2;

FileInputStream fis = new FileInputStream("serial");

ObjectInputStream ois = new ObjectInputStream(fis);

object2 = (MyClass)ois.readObject();

ois.close();

System.out.println("object2: " + object2);

}

catch(Exception e) {

System.out.println("Exception during deserialization: " + e);

System.exit(0);

}}}

class MyClass implements Serializable {

String s;

int i;

double d;

public MyClass(String s, int i, double d) {

this.s = s;

this.i = i;

this.d = d;

}

public String toString() {

return "s=" + s + "; i=" + i + "; d=" + d;

}

}

This program demonstrates that the instance variables of object1 and object2 are identical.

The output is shown here:

object1: s=Hello; i=-7; d=2.7E10

object2: s=Hello; i=-7; d=2.7E10

Page 34: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

34

15) Write a Java applet program to implement Color and Graphics class

AWT Controls

It is important to state at the outset that there are two varieties of applets. The first are those

based directly on the Applet class described in this chapter. These applets use the Abstract

Window Toolkit (AWT) to provide the graphic user interface (or use no GUI at all). This style

of applet has been available since Java was first created.

The second type of applets are those based on the Swing class JApplet. Swing applets use the

Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user interface than does the AWT.

All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-alone

programs. Instead, they run within either a web browser or an applet viewer. The illustrations

shown in this chapter were created with the standard applet viewer, called appletviewer, provided by the JDK.

It is important to understand the order in which the various methods shown in the skeleton are

called. When an applet begins, the following methods are called, in this sequence:

1. init( )

2. start( )

3. paint( )

When an applet is terminated, the following sequence of method calls takes place:

1. stop( )

2. destroy( )

// Demonstrate color.

import java.awt.*;

import java.applet.*;

/*

<applet code="ColorDemo" width=300 height=200>

</applet>

*/

public class ColorDemo extends Applet {

// draw lines

public void paint(Graphics g) {

Color c1 = new Color(255, 100, 100);

Color c2 = new Color(100, 255, 100);

Color c3 = new Color(100, 100, 255);

g.setColor(c1);

g.drawLine(20, 10, 20, 50);

g.setColor(c2);

Page 35: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

35

g.drawLine(40, 10, 40, 50);

g.setColor(c3);

g.drawLine(60,10, 60, 50);

g.setColor(Color.red);

g.drawOval(30, 90, 40, 40);

g.fillOval(80, 90, 40, 40);

g.setColor(Color.blue);

g.drawRect(130, 90, 40, 40);

g.fillRect(190, 90, 40, 40);

g.setColor(Color.cyan);

g.drawRoundRect(100, 150, 50, 50, 15, 15);

g.fillRoundRect(170, 150, 50, 50, 15, 15);

}

}

Page 36: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

36

16) Write a Java applet program to implement AWT classes like Label, TextField, Checkbox,

CheckboxGroup, Button, TextAreaetc

Events

In the delegation model, an event is an object that describes a state change in a source.

It can be generated as a consequence of a person interacting with the elements in a graphical

user interface. Some of the activities that cause events to be generated are pressing a button,

entering a character via the keyboard, selecting an item in a list, and clicking the mouse.

Many other user operations could also be cited as examples.

Events may also occur that are not directly caused by interactions with a user interface. For

example, an event may be generated when a timer expires, a counter exceeds a value, a

software or hardware failure occurs, or an operation is completed. You are free to define

events that are appropriate for your application.

Event Sources

Asource is an object that generates an event. This occurs when the internal state of that object

changes in some way. Sources may generate more than one type of event. Asource must

register listeners in order for the listeners to receive notifications about a specific type of

event. Each type of event has its own registration method. Here is the general form:

public void addTypeListener(TypeListener el)

Here, Type is the name of the event, and el is a reference to the event listener. For example,

the method that registers a keyboard event listener is called addKeyListener( ). The method

that registers a mouse motion listener is called addMouseMotionListener( ). When an event

occurs, all registered listeners are notified and receive a copy of the event object. This is

known as multicasting the event. In all cases, notifications are sent only to listeners that

register to receive them.

Event Listeners

Alistener is an object that is notified when an event occurs. It has two major requirements.

First, it must have been registered with one or more sources to receive notifications about

specific types of events. Second, it must implement methods to receive and process these

notifications. The methods that receive and process events are defined in a set of interfaces

found in java.awt.event. For example, the MouseMotionListener interface defines two

methods to receive notifications when the mouse is dragged or moved. Any object may

receive and process one or both of these events if it provides an implementation of this interface

The AWT defines windows according to a class hierarchy that adds functionality and

specificity with each level. The two most common windows are those derived from Panel,

which is used by applets, and those derived from Frame, which creates a standard application

window. Much of the functionality of these windows is derived from their parent classes.

Thus, a description of the class hierarchies relating to these two classes is fundamental to their

understanding. Figure 23-1 shows the class hierarchy for Panel and Frame. Let’s look at each

of these classes now.

Component

At the top of the AWT hierarchy is the Component class. Component is an abstract class

that encapsulates all of the attributes of a visual component. All user interface elements that

are displayed on the screen and that interact with the user are subclasses of Component. It

Page 37: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

37

defines over a hundred public methods that are responsible for managing events, such as

mouse and keyboard input, positioning and sizing the window, and repainting. (You already

used many of these methods when you created applets in Chapters 21 and 22.) A Component

object is responsible for remembering the current foreground and background colors and the

currently selected text font.

Container

The Container class is a subclass of Component. It has additional methods that allow other

Component objects to be nested within it. Other Container objects can be stored inside of a

Container (since they are themselves instances of Component). This makes for a

multileveled containment system. A container is responsible for laying out (that is, positioning) any components that it contains. It does this through the use of various layout managers import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class awtdemo extends Applet implements ActionListener, ItemListener

{

TextField name, pass;

Checkbox java, db,m,f;

CheckboxGroup cbg;

Choice cs;

TextArea text;

String msg="";

String val = "Java SE 6 is the latest version of the most\n";

public void init()

{

setLayout(new FlowLayout());

Label namep = new Label("Name: ");

Label passp = new Label("Password: ");

name = new TextField(12);

pass = new TextField(8);

pass.setEchoChar('?');

java= new Checkbox("Java");

db = new Checkbox("Oracle");

cbg = new CheckboxGroup();

m= new Checkbox("Male", cbg, true);

f = new Checkbox("Female", cbg, false);

cs= new Choice();

text = new TextArea(val, 10, 30);

Page 38: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

38

cs.add("CSE");

cs.add("IT");

cs.add("MECH");

cs.add("CIVIL");

add(namep);

add(name);

add(passp);

add(pass);

add(java);

add(db);

add(m);

add(f);

add(cs);

add(text);

name.addActionListener(this);

pass.addActionListener(this);

java.addItemListener(this);

db.addItemListener(this);

m.addItemListener(this);

f.addItemListener(this);

cs.addItemListener(this);

}

public void actionPerformed(ActionEvent ae)

{

repaint();

}

public void itemStateChanged(ItemEvent ie) {

repaint();

}

public void paint(Graphics g)

{

g.drawString("Name: " + name.getText(), 2, 140);

g.drawString("Password: " + pass.getText(), 2,160);

if(java.getState())

g.drawString("programming language: " +java.getLabel(),2,180) ;

Page 39: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

39

else

g.drawString("No Programming language",2,180);

if(db.getState())

g.drawString("Database: " +db.getLabel(),2,200) ;

else

g.drawString("No database",2,200);

g.drawString(cbg.getSelectedCheckbox().getLabel(),2,220);

g.drawString(cs.getSelectedItem(),2,240);

}

}

Page 40: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

40

17) Write a Java applet program for handling mouse & key events

// Demonstrate the mouse event handlers.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="MouseEvents" width=300 height=100>

</applet>

*/

public class MouseEvents extends Applet

implements MouseListener, MouseMotionListener {

String msg = "";

int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {

addMouseListener(this);

addMouseMotionListener(this);

}

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse clicked.";

repaint();

}

// Handle mouse entered.

public void mouseEntered(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse entered.";

repaint();

}

// Handle mouse exited.

public void mouseExited(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

Page 41: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

41

msg = "Mouse exited.";

repaint();

}

// Handle button pressed.

public void mousePressed(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();

}

// Handle button released.

public void mouseReleased(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Up";

repaint();

}

// Handle mouse dragged.

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "*";

showStatus("Dragging mouse at " + mouseX + ", " + mouseY);

repaint();

}

// Handle mouse moved.

public void mouseMoved(MouseEvent me) {

// show status

showStatus("Moving mouse at " + me.getX() + ", " + me.getY());

}

// Display msg in applet window at current X,Y location.

public void paint(Graphics g) {

g.drawString(msg, mouseX, mouseY);

}

}

Page 42: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

42

Key Event Handling

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class KeyEventDemo extends Applet implements KeyListener

{

String msg="";

public void init()

{

addKeyListener(this);

}

public void keyPressed(KeyEvent k)

{

showStatus("KeyPressed");

}

public void keyReleased(KeyEvent k)

{

showStatus("KeyRealesed");

}

public void keyTyped(KeyEvent k)

{

msg = msg+k.getKeyChar();

repaint();

}

public void paint(Graphics g)

{

g.drawString(msg, 20, 40);

}

}

Page 43: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

43

18) Write a Java applet program to implement Adapter classes

// Handle mouse events in both child and applet windows.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

// Create a subclass of Frame.

class SampleFrame extends Frame implements MouseListener, MouseMotionListener

{

String msg = "";

int mouseX=10, mouseY=40;

int movX=0, movY=0;

SampleFrame(String title) {

super(title);

// register this object to receive its own mouse events

addMouseListener(this);

addMouseMotionListener(this);

// create an object to handle window events

MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events

addWindowListener(adapter);

}

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

}

// Handle mouse entered.

public void mouseEntered(MouseEvent evtObj) {

// save coordinates

mouseX = 10;

mouseY = 54;

msg = "Mouse just entered child.";

repaint();

}

// Handle mouse exited.

public void mouseExited(MouseEvent evtObj) {

// save coordinates

mouseX = 10;

mouseY = 54;

Page 44: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

44

msg = "Mouse just left child window.";

repaint();

}

// Handle mouse pressed.

public void mousePressed(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();

}

// Handle mouse released.

public void mouseReleased(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Up";

repaint();

}

// Handle mouse dragged.

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

movX = me.getX();

movY = me.getY();

msg = "*";

repaint();

}

// Handle mouse moved.

public void mouseMoved(MouseEvent me) {

// save coordinates

movX = me.getX();

movY = me.getY();

repaint(0, 0, 100, 60);

}

public void paint(Graphics g) {

g.drawString(msg, mouseX, mouseY);

g.drawString("Mouse at " + movX + ", " + movY, 10, 40);

Page 45: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

45

}

}

class MyWindowAdapter extends WindowAdapter

{

SampleFrame sampleFrame;

public MyWindowAdapter(SampleFrame sampleFrame)

{

this.sampleFrame = sampleFrame;

}

public void windowClosing(WindowEvent we) {

sampleFrame.setVisible(false);

}

}

// Applet window.

public class WindowEvents extends Applet

//implements MouseListener, MouseMotionListener

{

SampleFrame f;

String msg = "";

int mouseX=0, mouseY=10;

int movX=0, movY=0;

// Create a frame window.

public void init() {

f = new SampleFrame("Handle Mouse Events");

f.setSize(300, 200);

f.setVisible(true);

// register this object to receive its own mouse events

addMouseListener(this);

addMouseMotionListener(this);

}

// Remove frame window when stopping applet.

public void stop() {

f.setVisible(false);

}

// Show frame window when starting applet.

public void start() {

f.setVisible(true);

}

Page 46: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

46

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

}

// Handle mouse entered.

public void mouseEntered(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 24;

msg = "Mouse just entered applet window.";

repaint();

}

// Handle mouse exited.

public void mouseExited(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 24;

msg = "Mouse just left applet window.";

repaint();

}

// Handle button pressed.

public void mousePressed(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();

}

// Handle button released.

public void mouseReleased(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Up";

repaint();

}

// Handle mouse dragged.

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX = me.getX();

Page 47: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

47

mouseY = me.getY();

movX = me.getX();

movY = me.getY();

msg = "*";

repaint();

}

// Handle mouse moved.

public void mouseMoved(MouseEvent me) {

// save coordinates

movX = me.getX();

movY = me.getY();

repaint(0, 0, 100, 20);

}

// Display msg in applet window.

public void paint(Graphics g) {

g.drawString(msg, mouseX, mouseY);

g.drawString("Mouse at " + movX + ", " + movY, 0, 10);

}

}

Page 48: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

48

19) Write a Java program that works as a simple calculator. Use a grid layout to arrange

buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class calc extends Applet implements ActionListener

{

Panel p1,p2;

TextField t;

String v="";

String d="";

String s1;

int a=0;

int b=0;

int c=0;

Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;

public void init()

{

p1=new Panel();

p2=new Panel();

t=new TextField(25);

b1=new Button("1");

b2=new Button("2");

b3=new Button("3");

b4=new Button("4");

b5=new Button("5");

b6=new Button("6");

b7=new Button("7");

b8=new Button("8");

b9=new Button("9");

b10=new Button("0");

b11=new Button("+");

b12=new Button("-");

b13=new Button("*");

b14=new Button("/");

b15=new Button("=");

setLayout(new BorderLayout());

p1.setLayout(new BorderLayout());

p2.setLayout(new GridLayout(4,4));

Page 49: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

49

add(p1,BorderLayout.NORTH);

add(p2,BorderLayout.SOUTH);

p1.add(t,BorderLayout.CENTER);

p2.add(b1);

p2.add(b2);

p2.add(b3);

p2.add(b4);

p2.add(b5);

p2.add(b6);

p2.add(b7);

p2.add(b8);

p2.add(b9);

p2.add(b10);

p2.add(b11);

p2.add(b12);

p2.add(b13);

p2.add(b14);

p2.add(b15);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

b5.addActionListener(this);

b6.addActionListener(this);

b7.addActionListener(this);

b8.addActionListener(this);

b9.addActionListener(this);

b10.addActionListener(this);

b10.addActionListener(this);

b10.addActionListener(this);

b11.addActionListener(this);

b12.addActionListener(this);

b13.addActionListener(this);

b14.addActionListener(this);

b15.addActionListener(this);

}

public void actionPerformed(ActionEvent ae)

{

String s=new String(ae.getActionCommand());

if(s.equals("="))

{

b=Integer.parseInt(t.getText());

Page 50: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

50

c=a+b;

switch(d.charAt(0))

{

case '+': c=a+b;

break;

case '-': c=a-b;

break;

case '*': c=a*b;

break;

case '/': c=a/b;

break;

default: c=0;

}

t.setText(String.valueOf(c));

}

else

{

if(s.equals("1")|s.equals("2")|s.equals("3")|s.equals("4")|s.equals("5")|s.equals("6")|s.eq

uals("7")|s.equals("8")|s.equals("9")|s.equals("0"))

{

v="";

v=v+s;

}

else if(s.equals("+"))

{

d=s;

a=Integer.parseInt(t.getText());

v="";

}

else if(s.equals("-"))

{

d=s;

a=Integer.parseInt(t.getText());

v="";

}

else if(s.equals("*"))

{

d=s;

a=Integer.parseInt(t.getText());

v="";

}

else if(s.equals("/"))

{

d=s;

a=Integer.parseInt(t.getText());

v="";

}

Page 51: Method Overloadingdeccancollege.ac.in/ITLABMANUALS/JAVALABMANUALCBCS.pdf · Method overloading is one of the ways that Java supports polymorphism. If you have never used a language

51

t.setText(v);

}

}

public void paint(Graphics g)

{

}

}