JAVA Manual remaining

105
Remaining JAVA manual Remaining manual of JAVA 2 F. Ansari 8/10/2014

description

remaining manual of JAVA 2

Transcript of JAVA Manual remaining

Page 1: JAVA Manual remaining

Remaining JAVA manual Remaining manual of JAVA 2

F. Ansari

8/10/2014

Page 2: JAVA Manual remaining

2

Contents Program 75: ................................................................................................................................................... 6

Solution: ........................................................................................................................................................ 6

Output: .......................................................................................................................................................... 8

Discussion: .................................................................................................................................................... 8

Program 76: ................................................................................................................................................... 9

Solution: ........................................................................................................................................................ 9

Output: ........................................................................................................................................................ 13

Discussion: .................................................................................................................................................. 13

Program 77: ................................................................................................................................................. 14

Solution: ...................................................................................................................................................... 14

Output: ........................................................................................................................................................ 18

Discussion: .................................................................................................................................................. 18

Program 78: ................................................................................................................................................. 18

Solution: ...................................................................................................................................................... 18

Output: ........................................................................................................................................................ 22

Discussion: .................................................................................................................................................. 22

Program 79: ................................................................................................................................................. 23

Solution: ...................................................................................................................................................... 23

Output: ........................................................................................................................................................ 27

Discussion: .................................................................................................................................................. 27

Program 80: ................................................................................................................................................. 27

Solution: ...................................................................................................................................................... 27

Output: ........................................................................................................................................................ 30

Discussion: .................................................................................................................................................. 31

Program 81: ................................................................................................................................................. 31

Solution: ...................................................................................................................................................... 31

Output: ........................................................................................................................................................ 34

Discussion: .................................................................................................................................................. 34

Program 82: ................................................................................................................................................. 35

Solution: ...................................................................................................................................................... 35

Output: ........................................................................................................................................................ 38

Page 3: JAVA Manual remaining

3

Discussion: .................................................................................................................................................. 38

Program 83: ................................................................................................................................................. 38

Solution: ...................................................................................................................................................... 38

Output: ........................................................................................................................................................ 42

Discussion: .................................................................................................................................................. 43

Program 84: ................................................................................................................................................. 43

Solution: ...................................................................................................................................................... 43

Output: ........................................................................................................................................................ 47

Discussion: .................................................................................................................................................. 47

Program 85: ................................................................................................................................................. 47

Solution: ...................................................................................................................................................... 47

Output: ........................................................................................................................................................ 52

Discussion: .................................................................................................................................................. 52

Program 86: ................................................................................................................................................. 53

Solution: ...................................................................................................................................................... 53

Output: ........................................................................................................................................................ 55

Discussion: .................................................................................................................................................. 55

Program 87: ................................................................................................................................................. 55

Solution: ...................................................................................................................................................... 55

Output: ........................................................................................................................................................ 57

Discussion: .................................................................................................................................................. 57

Program 88: ................................................................................................................................................. 57

Solution: ...................................................................................................................................................... 57

Output: ........................................................................................................................................................ 60

Discussion: .................................................................................................................................................. 60

Program 89: ................................................................................................................................................. 60

Solution: ...................................................................................................................................................... 60

Output: ........................................................................................................................................................ 61

Discussion: .................................................................................................................................................. 62

Program 90: ................................................................................................................................................. 62

Solution: ...................................................................................................................................................... 62

Output: ........................................................................................................................................................ 64

Page 4: JAVA Manual remaining

4

Discussion: .................................................................................................................................................. 64

Program 91: ................................................................................................................................................. 65

Solution: ...................................................................................................................................................... 65

Output: ........................................................................................................................................................ 68

Discussion: .................................................................................................................................................. 68

Program 92: ................................................................................................................................................. 68

Solution: ...................................................................................................................................................... 68

Output: ........................................................................................................................................................ 71

Discussion: .................................................................................................................................................. 71

Program 93: ................................................................................................................................................. 71

Solution: ...................................................................................................................................................... 71

Output: ........................................................................................................................................................ 75

Discussion: .................................................................................................................................................. 75

Program94: .................................................................................................................................................. 75

Solution: ...................................................................................................................................................... 75

Output: ........................................................................................................................................................ 78

Discussion: .................................................................................................................................................. 78

Program 95: ................................................................................................................................................. 78

Solution: ...................................................................................................................................................... 78

Output: ........................................................................................................................................................ 81

Discussion: .................................................................................................................................................. 81

Program 96: ................................................................................................................................................. 81

Solution: ...................................................................................................................................................... 81

Output: ........................................................................................................................................................ 84

Discussion: .................................................................................................................................................. 84

Program 97: ................................................................................................................................................. 85

Solution: ...................................................................................................................................................... 85

Output: ........................................................................................................................................................ 87

Discussion: .................................................................................................................................................. 87

Program 98: ................................................................................................................................................. 88

Solution: ...................................................................................................................................................... 88

Output: ........................................................................................................................................................ 90

Page 5: JAVA Manual remaining

5

Discussion: .................................................................................................................................................. 90

Program 99: ................................................................................................................................................. 90

Solution: ...................................................................................................................................................... 90

Output: ........................................................................................................................................................ 92

Discussion: .................................................................................................................................................. 92

Program 100: ............................................................................................................................................... 93

Solution: ...................................................................................................................................................... 93

Output: ........................................................................................................................................................ 96

Discussion: .................................................................................................................................................. 97

Program 101: ............................................................................................................................................... 97

Solution: ...................................................................................................................................................... 97

Output: ........................................................................................................................................................ 98

Discussion: .................................................................................................................................................. 99

Program 102: ............................................................................................................................................... 99

Solution: ...................................................................................................................................................... 99

HTML Code: ....................................................................................................................................... 100

Output: ...................................................................................................................................................... 101

Discussion: ................................................................................................................................................ 101

Program 103: ............................................................................................................................................. 102

Solution: .................................................................................................................................................... 102

HTML Code: ..................................................................................................................................... 102

Output: ...................................................................................................................................................... 103

Discussion: ................................................................................................................................................ 103

Program 104: ............................................................................................................................................. 103

Solution: .................................................................................................................................................... 103

HTML Code: ..................................................................................................................................... 104

Output: ...................................................................................................................................................... 105

Discussion: ................................................................................................................................................ 105

Page 6: JAVA Manual remaining

6

Program 75:

Write a code using the concept of multithreading that controls the main

thread.

Solution:

// controlling the main Thread.

class CurrentThreadDemo {

/* this line contains a keyword class that shows that a class is going to start and

CurrentThreadDemo is the name of this class. Opening curly brace { shows that form here a

class’ definition is going to begin */

// Your program begin with a call to main.

public static void main(String args[]){

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Thread t = Thread.currentThread();

// a thread defines a separate path of execution & here an object/local variable of thread is

declared and initialized

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the current thread

that is stored in the object of thread t */

// change the name of the thread

t.setName("My Thread");

/* In this line of code the name of the Thread is changed by calling a built in function setName()

that set the name by taking a String as an argument inside the paranthesis.*/

System.out.println("After name change: " + t);

Page 7: JAVA Manual remaining

7

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the thread after its

name changed that is stored in the object t of thread */

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

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

/*a for loop is declared here it contains three parts initialization that initializes n to 5, condition

i.e n is greater than 0, iteration i.e decrement of n. Firstly loop initialize n to 5 and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

decreasing the value of n by 1 until the condition is not satisfied*/

System.out.println(n);

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. It will display the value of n*/

Thread.sleep(1000);

// thread will sleep/paused for the time given in parenthesis

} // closing curly brace } is used to close the definition of for loop

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. If any exception occurs then this line of code

will display that Main thread interrupted */

} // closing curly brace } is used to close the definition of catch block

} // closing curly brace } is used to close the definition of main() method

Page 8: JAVA Manual remaining

8

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

The program contains a reference to the current thread, obtained by calling

currentThread( ), and this reference is stored in the local variable t. Then the program displays

information about the thread. The program then calls setName( ) method to change the name of

the thread. Information about the thread is then displayed again. Then a loop starts from five and

it sleeps or pauses for one second between each line. Then the try/catch block starts after this

loop. If the sleep( ) method in Thread will throw an InterruptedException then it will be

caught and displayed by the catch block.

Page 9: JAVA Manual remaining

9

Program 76:

Using the concept of multithreading write a code that implements

runnable & will not run until the start() method written within thread is

called.

Solution:

// Create a second thread.

class NewThread implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and NewThread is

the name of this class. Opening curly brace { shows that form here a class’ definition is going

to begin. It implements Runnable an abstract class */

Thread t;

// t is the local variable or an object of Thread is initialized here and stores.

NewThread() {

// Constructor of NewThread() class. Inside NewThread’s constructor, a new Thread object is

created

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

// Create a new, second thread

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

t.start(); // Start the thread

}

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

public void run() {

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

Page 10: JAVA Manual remaining

10

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition

i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

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

// This line of code will display the String written inside the parenthesis for ith time.

Thread.sleep(500);

// thread will sleep/paused for the time given in parenthesis

}

// closing curly brace } is used to close the definition of for loop.

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis if any exception occurs. */

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

Page 11: JAVA Manual remaining

11

} // closing curly brace } is used to close the definition of run() method

} // closing curly brace } is used to close the definition of class

class ThreadDemo {

/* this line contains a keyword class that shows that a class is going to start and ThreadDemo is

the name of this class. Opening curly brace { shows that form here a class’ definition is going

to begin */

// Your program begin with a call to main.

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

new NewThread(); // create a new thread

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition

i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis.*/

Thread.sleep(1000);

Page 12: JAVA Manual remaining

12

// thread will sleep/paused for the time given in parenthesis

}

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis if any exception occurs. */

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 13: JAVA Manual remaining

13

Output:

Discussion:

In this program the first thread is used to call the run() method using this object. Then

start( ) is called, which starts the thread at the run( ) method. This causes the thread’s for loop

to begin. After calling start( ), NewThread’s constructor returns to main( ). When the main

thread starts, it enters its for loop. Both threads continue running, until their loops finish. Hence

they display the output.

Page 14: JAVA Manual remaining

14

Program 77:

Write a code using multithreading concept by extending Thread class.

Solution:

// Create a second thread by extending Thread

class NewThread extends Thread {

/* this line contains a keyword class that shows that a class is going to start and NewThread is

the name of this class and this class extends Thread. Opening curly brace { shows that form

here a class’ definition is going to begin */

NewThread() {

// Constructor of NewThread() class. Inside NewThread’s constructor, a new Thread object is

created

super("Demo Thread");

/* the call to super( ) inside NewThread invokes the following form of the Thread

constructor i.e public Thread(String threadName). Here, threadName specifies the name of the

thread.*/

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the current thread

that is stored in the this keyword. */

start(); // Start the thread

}

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

public void run() {

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

try {

Page 15: JAVA Manual remaining

15

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition

i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print what is written

inside it. */

Thread.sleep(500);

// thread will sleep/paused for the time given in parenthesis

}

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print what is written

inside it if any exception occurs and caught by catch block.*/

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside it. */

Page 16: JAVA Manual remaining

16

}

}

class ExtendThread {

/* this line contains a keyword class that shows that a class is going to start and ExtendThread

is the name of this class. Opening curly brace { shows that form here a class’ definition is going

to begin */

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

new NewThread(); // create a new thread

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition

i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

Thread.sleep(1000);

}

Page 17: JAVA Manual remaining

17

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis if any exception occurs and caught by catch block. */

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 18: JAVA Manual remaining

18

Output:

Discussion:

This program generates the same output as the above program generates. The thread is

created by instantiating an object of NewThread, which is derived from Thread. Notice the call

to super( ) inside NewThread. This runs the Thread constructor and super performs the erasing

behavior.

Program 78:

Write a code using multithreading concept that creates multiple threads

Solution:

// Create multiple threads.

class NewThread implements Runnable {

Page 19: JAVA Manual remaining

19

/* this line contains a keyword class that shows that a class is going to start and NewThread is

the name of this class and it implements an abstract class Runnable(). Opening curly brace {

shows that form here a class’ definition is going to begin */

String name; // name of thread

Thread t;

// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s

constructor, a new Thread object is created

NewThread(String threadname) {

// An argument Constructor of NewThread() class. Inside NewThread’s constructor, a new

Thread object is created

name = threadname;

// String is initialized here.

t = new Thread(this, name);

// Create a new, second thread. t is initialized here and reference to the name is stored in it.

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the new thread that

is stored in the object t of thread */

t.start(); // Start the thread

}

// This is the entry point for thread.

public void run() {

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

try {

Page 20: JAVA Manual remaining

20

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition

i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

Thread.sleep(1000);

// thread will sleep/paused for the time given in parenthesis

}

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println(name + "Interrupted");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis.*/

Page 21: JAVA Manual remaining

21

}

}

class MultiThreadDemo {

// Your program begin with a call to main.

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

new NewThread("One"); // start threads

new NewThread("Two");

new NewThread("Three");

// new threads started here

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

// wait for other threads to end

Thread.sleep(10000);

// thread will sleep/paused for the time given in parenthesis

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. If any exception occurs then this line of code

will display that Main thread interrupted */

Page 22: JAVA Manual remaining

22

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

This program once started, all three new/ child threads start executing/ running. Notice

the call to sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and

ensures that it will finish last.

Page 23: JAVA Manual remaining

23

Program 79:

Write a code that demonstrate thread priorities

Solution:

// Demonstrate thread priorities.

class clicker implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and clicker is the

name of this class and it implements Runnable an abstract class. Opening curly brace { shows

that form here a class’ definition is going to begin */

long click = 0; // local variable to type ling initialized to 0

Thread t;

// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s

constructor, a new Thread object is created

private volatile boolean running = true;

/* here a private volatile Boolean variable is declared and initialized. Private means can’t b

accessible outside the class and volatile variable means the variable whose value is always held in

main memory so that it can be accessed by different threads. */

public clicker(int p) {

// An argument Constructor of Clicker() class.

t = new Thread(this);

// t is initialized here

t.setPriority(p);

// priority is been set here calling setPriority() function

}

public void run() {

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

while (running) {

Page 24: JAVA Manual remaining

24

click++;

}

// if running then click will keep on incrementing

}

public void stop() {

///* public is a keyword which means that this method is publically accessible, void means that

it has no return type, stop() is the method to stop the running thread. Opening Curly Brace {

means that the method’s def. is going to start. */

running = false;

// to stop we will make running false

}

public void start() {

t.start();

}

// this method will start the thread

}

class HiLoPri {

/* this line contains a keyword class that shows that a class is going to start and HiLoPri is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

// Your program begin with a call to main.

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Page 25: JAVA Manual remaining

25

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

clicker hi = new clicker(Thread.NORM_PRIORITY + 2);

clicker lo = new clicker(Thread.NORM_PRIORITY - 2);

// here 2 objects of class clicker are created and instantiated i.e hi, lo and both are set to default

priority using NORM_PRIORITY but by +2 & -2 hi will b of high n lo will b of low priority

lo.start();

hi.start();

// here both objects’s working starts using start() methd

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

Thread.sleep(10000);

// thread will sleep/paused for the time given in parenthesis

} catch (InterruptedException e) {

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis if any exception occurs. */

}

lo.stop();

hi.stop();

// here the working of both the instances of class will stop by calling stop() method

// Wait for child threads to terminate.

try {

Page 26: JAVA Manual remaining

26

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

hi.t.join();

lo.t.join();

// here join() method is called that waits for a thread to finish

} catch (InterruptedException e) {

System.out.println("InterruptedException

caught");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis if any exception occurs.*/

}

System.out.println("Low-priority thread: " + lo.click);

System.out.println("High-priority thread: " + hi.click);

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. These lines of code will display the Strings

written inside the parenthesis. */

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 27: JAVA Manual remaining

27

Output:

Discussion:

Thread priorities are used by the thread scheduler to decide when each thread is allowed

to run. Higher priority threads get more time then lower priority threads. To set the thread

priority setPriority() method is used which is a member of Thread. In this program an instance of

thread is initialized and setPriority() method is called through it. Then run(), stop() and start()

method is called. Then main method is declared in which the class instantiated. Then a join()

method is called with the class’ instances that method waits for a thread to finish. Then high

level and low level threads are stored in hi and lo objects respectively and then displayed as

above.

Program 80:

Write a code that will not synchronized

Solution:

// This program is not synchronized.

class Callme {

/* this line contains a keyword class that shows that a class is going to start and Callme is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

void call(String msg) {

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Page 28: JAVA Manual remaining

28

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

Thread.sleep(1000);

} catch(InterruptedException e) {

System.out.println("Interrupted");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. If any exception occurs then this line of code

will display Interrupted */

}

System.out.println("]");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

}

}

class Caller implements Runnable {

String msg;

Callme target; // instance of class

Thread t;

// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s

constructor, a new Thread object is created

public Caller(Callme targ, String s) {

target = targ;

Page 29: JAVA Manual remaining

29

msg = s;

t = new Thread(this); // t is initializes

t.start(); // thread starts

}

public void run() {

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

target.call(msg); // method is called

}

}

class Synch {

/* this line contains a keyword class that shows that a class is going to start and Synch is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

// Your program begin with a call to main.

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Callme target = new Callme();

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

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

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

// class’ objects are initialized n declared

Page 30: JAVA Manual remaining

30

// wait for threads to end

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

ob1.t.join();

ob2.t.join();

ob3.t.join();

// here join() method is called that waits for a thread to finish

} catch(InterruptedException e) {

System.out.println("Interrupted");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

}// closing curly brace } is used to close the definition of catch()

block

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Page 31: JAVA Manual remaining

31

Discussion:

This program shows that how the output will look like without synchronization. A

class Callme is created first. Then strings are declared and displayed. In class Caller that

implements Runnable a new thread is starts then call() method is called in run method that calls

the String throught msg. Then try catch block try to synchronize the string as shown in output

also using join() method.

Program 81:

write a code that uses synchronized block

Solution:

// This program uses a synchronized block.

class Callme {

/* this line contains a keyword class that shows that a class is going to start and Callme is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

void call(String msg) {

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

Thread.sleep(1000);

// thread will sleep/paused for the time given in parenthesis

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("Interrupted");

Page 32: JAVA Manual remaining

32

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. If any exception occurs then this line of code

will display Interrupted */

}

System.out.println("]");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis.*/

}

}

class Caller implements Runnable {

String msg; // a string msg is declared

Callme target; // class’s object

Thread t;

// t is the local variable or an object of Thread is initialized here and stores. Inside NewThread’s

constructor, a new Thread object is created

public Caller(Callme targ, String s) {

// 2 argument constructor

target = targ;

msg = s;

t = new Thread(this); // t is initializes

t.start(); // t starts

}

// synchronize calls to call()

public void run() {

synchronized(target) { // synchronized block

Page 33: JAVA Manual remaining

33

target.call(msg); // call() is called

}

}

}

class Synch1 {

/* this line contains a keyword class that shows that a class is going to start and Synch1 is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Callme target = new Callme();

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

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

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

// class’ instances are declared and initializes

// wait for threads to end

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

ob1.t.join();

ob2.t.join();

ob3.t.join();

Page 34: JAVA Manual remaining

34

// here join() method is called that waits for a thread to finish

} catch(InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("Interrupted");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis if any exception occurs.*/

} // end of catch block

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

This program shows that how the output will look like if it is synchronized. A class

Callme is created first. Then another class Synch1 is created that contains the main method. Then

a call method is declared having msg string as a parameter and then displays it too. Then try

catch block is declared that displays the strings. In class Caller that implements Runnable a new

thread is starts then caller() method is declared having 2 arguments and it starts the thread using

its object. Then synchronize calls to Call() method is which synchronized block is declared then

in the main method creating 3 objects of Callme class are declared and initialized . Synchronized

statement is used inside the caller’s run() method and shows the synchronized output.

Page 35: JAVA Manual remaining

35

Program 82:

write an incorrect implementation of a producer and consumer

Solution:

// An incorrect implementation of a producer and consumer.

class Q {

/* this line contains a keyword class that shows that a class is going to start and Q is the name of

this class. Opening curly brace { shows that form here a class’ definition is going to begin */

int n; // local variable of type int

synchronized int get() {

// 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 so for this synchronized get() method is

used

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

return n; // it will return n

}

synchronized void put(int n) {

// 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 so for this synchronized put() method is

used

this.n = n; // reference of object n is stored

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

}

Page 36: JAVA Manual remaining

36

}

class Producer implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and Producer is the

name of this class and it implements Runnable an abstract class. Opening curly brace { shows

that form here a class’ definition is going to begin */

Q q; // instance of class Q

Producer(Q q) {

// Constructor of Producer class.

this.q = q; // stores reference of q

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

}

public void run() {

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

int i = 0; /// a variable i of type int

while(true) {

q.put(i++); // if condition is true then i will increment

}

}

}

class Consumer implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and Consumer is the

name of this class & it implements Runnable an abstract class. Opening curly brace { shows

that form here a class’ definition is going to begin */

Q q; // instance of class Q

Consumer(Q q) {

Page 37: JAVA Manual remaining

37

// Constructor of Consumer class.

this.q = q; // reference of q is stored

new Thread(this, "Consumer").start(); // new thread starts here

}

public void run() {

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

while(true) {

q.get(); // if true then get() function works

}

}

}

class PC {

/* this line contains a keyword class that shows that a class is going to start and PC is the name

of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

// Your program begin with a call to main.

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Q q = new Q();

new Producer(q);

new Consumer(q);

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

Page 38: JAVA Manual remaining

38

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

In this program put(), get() and run methods are used. Consumer the threaded object that

is consuming queues entries is also used. In Q put and get methods are synchronized, nothing

stops the producer from overrunning the consumer, nor will anything stop the consumer from

consuming the same queue value twice. Thus, we get the erroneous output shown above.

Program 83:

write a correct implementation of a producer and consumer.

Solution:

// A correct implementation of a producer and consumer.

class Q {

/* this line contains a keyword class that shows that a class is going to start and Q is the name of

this class. Opening curly brace { shows that form here a class’ definition is going to begin */

int n; // local variable is initialized

boolean valueSet = false;

Page 39: JAVA Manual remaining

39

// a variable of type Boolean is initialized and declared

synchronized int get() {

// 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 so for this synchronized get() method is

used

while(!valueSet)

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

wait();

// wait() tells the calling object to gine up the monitor and go to sleep until some other threads

enter the same monitor and calls the notify.

} catch(InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis if any exception occurs. */

}

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

//This line of code will display the String written inside the parenthesis.

valueSet = false;

notify();

// notify() method wakes up the first thread that called wait() on the same object

return n; // returns n

}

synchronized void put(int n) {

Page 40: JAVA Manual remaining

40

while(valueSet)

try {

wait();

} catch(InterruptedException e) {

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

//If any exception occurs then this line of code will display that InterruptedException caught.

}

this.n = n;

valueSet = true;

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

// This line of code will display the String written inside the parenthesis.

notify();

}

}

class Producer implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and Producer is the

name of this class & it implements Runnable an abstract class. Opening curly brace { shows

that form here a class’ definition is going to begin */

Q q;

Producer(Q q) {

this.q = q; // stores reference of q

new Thread(this, "Producer").start(); // new thread starts

}

public void run() {

Page 41: JAVA Manual remaining

41

/* public is a keyword which means that this method is publically accessible, void means that it

has no return type, run() is the abstract method of abstract class Runnable and it is implemented

here, Opening Curly Brace { means that the method’s def. is going to start. */

int i = 0; // local variable of type int

while(true) {

q.put(i++);

// if true the condition is then i will increases

}

}

}

class Consumer implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and Consumer is the

name of this class & it implements Runnable an abstract class. Opening curly brace { shows

that form here a class’ definition is going to begin */

Q q;

Consumer(Q q) {

this.q = q; // stores reference of q

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

// new thread starts here

}

public void run() {

while(true) {

q.get();

}

}

}

class PCFixed {

Page 42: JAVA Manual remaining

42

/* this line contains a keyword class that shows that a class is going to start and PCFixed is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Q q = new Q();

new Producer(q);

new Consumer(q);

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Page 43: JAVA Manual remaining

43

Discussion:

In this program inside get() method another method wait() is called. This causes its

execution to suspend until the Producer Tell us that some data is ready is execute. When this

happens, execution inside get() starts. After the data has been obtained, get() calls notify()

method. Using put() method more data will be added and then again the wait() method is called,

which stops the execution until the data is removed from queue. When execution resumes, the

next item of data is put in the queue, and notify() method is called. This tells the Consumer that it

should now remove it.

Program 84:

write an example of deadlock

Solution:

// An example of deadlock.

class A {

/* this line contains a keyword class that shows that a class is going to start and A is the name of

this class. Opening curly brace { shows that form here a class’ definition is going to begin */

synchronized void foo(B b) {

// 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 so for this synchronized put() method is

used

String name = Thread.currentThread().getName();

// get the name of current thread

System.out.println(name + " entered A.foo");

// This line of code will display the String written inside the parenthesis.

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

Thread.sleep(1000);

// thread sleeps/pauses for given interval of time

} catch(Exception e) {

Page 44: JAVA Manual remaining

44

System.out.println("A Interrupted");

// If any exception occurs then this line of code will display the String written inside the

parenthesis.

}

System.out.println(name + " trying to call B.last()");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

b.last(); // last method is called

}

synchronized void last() {

// 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 so for this synchronized get() method is

used

System.out.println("Inside A.last");

// This line of code will display the String written inside the parenthesis.

}

}

class B {

synchronized void bar(A a) {

String name = Thread.currentThread().getName();

System.out.println(name + " entered B.bar");

// This line of code will display the String written inside the parenthesis.

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

Thread.sleep(1000);

Page 45: JAVA Manual remaining

45

} catch(Exception e) {

System.out.println("B Interrupted");

// If any exception occurs then this line of code will displays the String written inside the

parenthesis.

} // end of catch block

System.out.println(name + " trying to call A.last()");

// This line of code will display the String written inside the parenthesis.

a.last();

}

synchronized void last() {

System.out.println("Inside A.last");

// This line of code will display the String written inside the parenthesis.

}

}

class Deadlock implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and Deadlock is the

name of this class & it implements Runnable an abstract class. Opening curly brace { shows

that form here a class’ definition is going to begin */

A a = new A(); // an object of class A in initialized and declared

B b = new B(); // an object of class B in initialized and declared

Deadlock() { // constructor of the class

Thread.currentThread().setName("MainThread");

// set the name of default constructor

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

// new thread is initialized

t.start();

Page 46: JAVA Manual remaining

46

a.foo(b); // get lock on a in this thread.

System.out.println("Back in main thread");

// This line of code will display the String written inside the parenthesis.

}

public void run() {

b.bar(a); // get lock on b in other thread.

System.out.println("Back in other thread");

// This line of code will display the String written inside the parenthesis.

}

// Your program begin with a call to main.

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

new Deadlock();

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 47: JAVA Manual remaining

47

Output:

Discussion:

In this program deadlock is used which is a special type of error that needs to be avoid. It

relates specifically to multitasking which occurs when two threads have a circular dependency

on a pair of synchronized objects. As the program has deadlocked, we have to press CTRL-C to

end the program. The RacingThread owns the monitor on b, while it is waiting for the monitor

on a. At the same time, MainThread owns a and is waiting to get b. This program will never

complete.

Program 85:

write a code that demonstrates the use of suspend() and resume().

Solution:

// Using suspend() and resume().

class NewThread implements Runnable {

/* this line contains a keyword class that shows that a class is going to start and NewThread is

the name of this class & it implements Runnable. Opening curly brace { shows that form here a

class’ definition is going to begin */

String name;

// name of thread. A variable of type String known as name

Thread t;

// a thread t is declared

NewThread(String threadname) { // an argument constructor is created

Page 48: JAVA Manual remaining

48

name = threadname;

t = new Thread(this, name);

// thread is initialized and stores reference of name

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the new thread that

is stored in the object of thread i.e t */

t.start(); // Start the thread

}

// This is the entry point for thread.

public void run() {

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 5, condition

i.e i is greater than 0, iteration i.e decrement of i. Firstly loop initialize i to five and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will display the String

written inside the parenthesis. */

Thread.sleep(200);

}

Page 49: JAVA Manual remaining

49

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println(name + " interrupted.");

// If any exception occurs then this line of code will display the string written inside parenthesis.

}

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

// This line of code will display the String written inside the parenthesis.

}

}

class SuspendResume {

/* this line contains a keyword class that shows that a class is going to start and

SuspendResume is the name of this class. Opening curly brace { shows that form here a class’

definition is going to begin */

// Your program begin with a call to main.

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

NewThread ob1 = new NewThread("One");

NewThread ob2 = new NewThread("Two");

// 2 new objects of class are initialized and declared

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

Page 50: JAVA Manual remaining

50

Thread.sleep(1000);

ob1.t.suspend(); // obj1 is suspended

System.out.println("Suspending thread One");

// This line of code will display the String written inside the parenthesis.

Thread.sleep(1000);

ob1.t.resume(); //// obj1 is resumed

System.out.println("Resuming thread One");

// This line of code will display the String written inside the parenthesis.

ob2.t.suspend(); // obj2 is suspended

System.out.println("Suspending thread Two");

// This line of code will display the String written inside the parenthesis.

Thread.sleep(1000);

// thread sleeps for the given interval of time

ob2.t.resume(); //// obj1 is resumes

System.out.println("Resuming thread Two");

// This line of code will display the String written inside the parenthesis.

} catch (InterruptedException e) {

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

// If any exception occurs then this line of code will display that Main thread interrupted.

}

// wait for threads to finish

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

System.out.println("Waiting for threads to finish.");

Page 51: JAVA Manual remaining

51

// This line of code will display the String written inside the parenthesis.

ob1.t.join();

ob2.t.join();

// here join() method is called that waits for a thread to finish

} catch (InterruptedException e) {

// catch block catches exception if it occurs and stored it in its object e

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. If any exception occurs then this line of code

will display that Main thread interrupted */

} // closing curly brace } is used to close the definition of catch block

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. It will print the String written inside it in

double quotes*/

}

}

Page 52: JAVA Manual remaining

52

Output:

Discussion: The demo contains suspend() and resume() methods. These methods are defined by Thread to

pause and restart the execution of thread. This program creates 2 objects ob1 and ob2 and displays each’

thread with an interval or pause by suspend() and sleep() methods. It also resumes the working of both the

Page 53: JAVA Manual remaining

53

objects and then displays that both the threads are exiting including main thread. The thread class also

defines a method called stop() that stops a thread. Once a thread has been stopped, it cannot be restarted

using resume() method.

Program 86:

Write a program that uses buffer reader to read the characters.

Solution:

// Use a BufferedReader to read characters from the console.

import java.io.*;

/* first of all import a java.io package which is knows as basic input output package. It is a

package that handles byte streams like input stream, output stream etc*/

class BRRead {

/* this line contains a keyword class that shows that a class is going to start and BRRead is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

public static void main(String args[])

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

throws IOException{

char c; // character c is declared

BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));

/* use to create a character stream Br is a character based stream that is linked to the console

through system.in and buffer reader supports a buffer input stream. System.in is a line buffered

by default*/

System.out.println("Enter characters, 'q' to quit.");

Page 54: JAVA Manual remaining

54

/* read characters. System is a built in function used to give access to the system. Out is used for

the output. Println is used to print or display the string passed to it & ln is used to goto the next

line. Semicolon is used to terminate the statement/line */

Do { // loop starts

c = (char) br.read();

// characters will be read from the console and stored in c

System.out.println(c);

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. // This line of code will display the String

written inside the parenthesis. */

}

while(c != 'q');

// it will give output until we press q ( loop ends)

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 55: JAVA Manual remaining

55

Output:

Discussion:

This demo first wants the user to type a string then reads a character from the console

using BufferedReader and read() methods. Each time that read() method is called, it reads a

character from the input stream and returns it one by one. It returns –1 when the end of the

stream is encountered. No input is passed to the program until we press enter. This program

continues it’s working until user type q to quit.

Program 87:

write a program that reads the string from console.

Solution:

// Read a string from console using a BufferedReader.

import java.io.*;

/* first of all import a java.io package which is knows as basic input output package. It is a

package that handles byte streams like input stream, output stream etc*/

class BRReadLines {

Page 56: JAVA Manual remaining

56

/* this line contains a keyword class that shows that a class is going to start and BRReadLines is

the name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

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

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin and throwsIOException

means that this code can throw exception*/

// create a BufferedReader using System.in

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

/* use to create a character stream Br is a character based stream that is linked to the console

through system.in and buffer reader supports a buffer input stream. System.in is a line buffered

by default*/

String str; // a variable str of type string is declared

System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. // These lines of code will display the String

written inside the parenthesis. */

do { // loop starts

str = br.readLine();

/* br is the instance of BufferReader that by using dot operator calls a readLine() method and

stores it in the variable str of type string */

System.out.println(str);

// This line of code will display the String written inside the parenthesis.

} while(!str.equals("stop"));

Page 57: JAVA Manual remaining

57

// when the entered string will be equal to stop then the program quit

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

In this demo BufferedReader()and inputSteamReader() methods are used that first wants

the user to type a string then they read it and dislay is again. To read a string from the console

readLine() method is used that is a member of the BufferedReader class. The process

continues until the user type stop.

Program 88:

Write a program that reads upto 100 lines or until you enter stop. It

uses buffer reader to read from the console.

Solution:

// A tiny editor.

import java.io.*;

Page 58: JAVA Manual remaining

58

/* first of all import a java.io package which is knows as basic input output package. It is a

package that handles byte streams like input stream, output stream etc*/

class TinyEdit {

/* this line contains a keyword class that shows that a class is going to start and TinyEdit is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

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

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin and throwsIOException

means that this code can throw exception */

// create a BufferedReader using System.in

BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));

/* use to create a character stream Br is a character based stream that is linked to the console

through system.in and buffer reader supports a buffer input stream. System.in is a line buffered

by default*/

String str[] = new String[100];

// a string str of size 100 is declared and initialized here.

System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. These line of code will display the String

written inside the parenthesis. */

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

/*a for loop is declared here it contains three parts initialization that initializes n to 0, condition

i.e n is less than 100, iteration i.e increment of n. Firstly loop initialize n to 0 and then it will

check the condition that either it is true or not, if it is true then the next statement will be

Page 59: JAVA Manual remaining

59

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of n by 1 until the condition is not satisfied*/

str[i] = br.readLine();

/* br is the instance of BufferReader that by using dot operator calls a readLine() method and

stores it in the variable str[i] of type string */

if(str[i].equals("stop")) break;

// if the given condition is satisfied then it will break

}

System.out.println("\nHere is your file:");

// This line of code will display the String written inside the parenthesis.

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

/*a for loop is declared here it contains three parts initialization that initializes n to 0, condition

i.e n is less than 100, iteration i.e increment of n. Firstly loop initialize n to 0 and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of n by 1 until the condition is not satisfied*/

if(str[i].equals("stop")) break;

// if the given condition is satisfied then it will break

System.out.println(str[i]);

// This line of code will display the String written inside the parenthesis.

}

}// closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 60: JAVA Manual remaining

60

Output:

Discussion: In this demo using BufferedReader() and fileInputStreamReader() the data written on the

console will be displayed again on it. BufferedReader() method reads the text from the console. This

demo first wants us to write the lines of the text then if we want to stop then wants us to type stop just in

the same way as it is mentione on console then the compiler compares it to the string already declared to

“stop” if it matches then it will display what you entered/ type. It will read up to 100 lines or until we

enter stop.

Program 89:

write a program that uses Print Writer to handle the console.

Solution:

// Demonstrate PrintWriter

import java.io.*;

/* first of all import a java.io package which is knows as basic input output package. It is a

package that handles byte streams like input stream, output stream etc*/

public class PrintWriterDemo {

Page 61: JAVA Manual remaining

61

/* this line contains a keyword class that shows that a class is going to start and

PrintWriterDemo is the name of this class. Opening curly brace { shows that form here a

class’ definition is going to begin */

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

PrintWriter pw = new PrintWriter(System.out, true);

// printWriter is used to write to the console. system.out is used for the output stream and flush

the stream after each new line

pw.println("This is a string"); // display this text

int i = -7; // a local variable i of type int

pw.println(i); // displays i on the command prompt

double d = 4.5e-7; // a local variable d of type double

pw.println(d); // displays d on the console

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Page 62: JAVA Manual remaining

62

Discussion:

This demo displays the use of writing the data on the console or command prompt using

printWritter method. Console output is most easily accomplished with print( ) and println( ).

These methods are defined by the class PrintStream (which is the type of the object referenced

by System.out). System.out is a byte stream, using it for simple program. Because PrintStream

is an output stream derived from OutputStream, it also implements the low-level method write(

). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by

PrintStream.

Program 90:

Write a program that displays a text. Create text file first.

Solution:

/* Display a text file. To use this program, specify the name of the file that you want to

see. For example, to see a file called TEST.TXT, use the following command line. java ShowFile

TEST.TXT */

import java.io.*;

// first of all import a java.io package which is knows as basic input output package. It is a

package that handles byte streams like input stream, output stream etc*/

class ShowFile {

/* this line contains a keyword class that shows that a class is going to start and ShowFile is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

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

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared and IOException

means it can throw inputoutput Exception. Then opening curly brace { shows that form here the

method’s definition is going to begin */

int i; // a local variable is decalred

FileInputStream fin;

Page 63: JAVA Manual remaining

63

/* when we do work on files we use fileInputStream try/catch blocks handle the two errors that

might occur when this program is used the specified file not being found or we forget to include

the name of the file.*/

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

fin = new FileInputStream(args[0]);

// fin stores the input of the file from the console

} catch(FileNotFoundException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("File Not Found");

// This line of code will display the String written inside the parenthesis.

return; // returns the control

} catch(ArrayIndexOutOfBoundsException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("Usage: ShowFile File");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line */

return; // returns the control

}

// read characters until EOF is encountered

do { // loop begins

i = fin.read();

// read file and store it in i

if(i != -1) System.out.print((char) i);

Page 64: JAVA Manual remaining

64

// if condition is satisfies then this line of code will display the String written inside the

parenthesis.

} while(i != -1);

fin.close(); // file will close if i != -1

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

In this program we use read() method for input and to display the contents of a text file,

the name of which is specified as a command-line argument. try/catch blocks handle the two

errors that might occur when this program is used the specified file not being found or the user

forgetting to include the name of the file. fileInputStream is used get the input stored in file.

Page 65: JAVA Manual remaining

65

Program 91:

Write a program that uses write() to copy a text file by making two text

files of different names.

Solution:

import java.io.*;

/* first of all import a java.io package which is knows as basic input output package. It is a

package that handles byte streams like input stream, output stream etc*/

class CopyFile {

/* this line contains a keyword class that shows that a class is going to start and CopyFile is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

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

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared and it can throw an

exception. Then opening curly brace { shows that form here the method’s definition is going to

begin */

int i; // local variable i declares of type int

FileInputStream fin;

// when we do work on files we use fileInputStream for the input of the file

FileOutputStream fout;

// when we do work on files we use fileoutputStream to get the input of the file

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

// open input file

Page 66: JAVA Manual remaining

66

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

fin = new FileInputStream(args[0]);

// this line of code will get input for the file at the 0 position and stores it in fin

} catch(FileNotFoundException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("Input File Not Found");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line */

return; // returns the control

}

// open output file

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

fout = new FileOutputStream(args[1]);

// fout stores the output of the file at 1 position

} catch(FileNotFoundException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("Error Opening Output File");

// This line of code will display the String written inside the parenthesis.

return; // returns the control

}

Page 67: JAVA Manual remaining

67

} catch(ArrayIndexOutOfBoundsException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("Usage: CopyFile From To");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line */

return; // returns the control

}

// Copy File

try {

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

do { // loop begins

i = fin.read(); // i stores the read characters

if(i != -1) fout.write(i);

// write the data that is stored in i if the condition satisfies

} while(i != -1);

} catch(IOException e) {

// catch block catches exception if it occurs and stored it in its object e

System.out.println("File Error");

// This line of code will display the String written inside the parenthesis.

}

fin.close(); // input closed

fout.close(); // output closed

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 68: JAVA Manual remaining

68

Output:

Discussion:

In this demo the copying of one text file to another text file is done. Java COPY.txt

WILLCOPY.txt command is used to copy the WILLCOPY file’s text on COPY’s file. We can

run this program only when we made two different files of notepad having something written on

‘em.

Program 92:

Write a code that using arc draw diff. shapes

Solution:

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class Arcs extends JPanel{

Page 69: JAVA Manual remaining

69

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and Arcs is its name and it extends JPanel*/

public void paintComponent(Graphics g) {

/* public method having no return type known as paintComponent and is used for painting and it

takes Graphics g as a parameter, g is the object of Graphics used to do graphics painting. */

Graphics2D g2 = (Graphics2D)g;

// for 2D graphics we create an object g2 of Graphics2D and initializes it

g2.drawArc(10, 40, 70, 70, 0, 75);

g2.fillArc(100, 40, 70, 70, 0, 75);

g2.drawArc(10, 100, 70, 80, 0, 175);

g2.fillArc(100, 100, 70, 90, 0, 270);

g2.drawArc(200, 80, 80, 80, 0, 180);

/* these lines of code using 2D graphics call drawArc method which draw the arc at the position

written in parentheses and also call the fillArc method that fills the arc at the position defined in

parentheses. */

} // closing curly brace } is used to close the definition of pintComponent

} // closing curly brace } is used to close the definition of class

// through this class the above class is instantiated and will give output

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class TestA{

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and TestA is its name */

public TestA(){ // Constructor of the TestA class

JFrame f = new JFrame();

Page 70: JAVA Manual remaining

70

// a frame is declared and initialized to show the output on this frame

Container c = f.getContentPane();

// a container is then initialized by calling the getContentPane() method. Everything that will be

shown on frame will first be added to it

c.setLayout(new BorderLayout());

// BorderLayout of the container is set by calling setLayout method

Arcs p = new Arcs();

// the above class is instantiated in this class in order to get access to that class

c.add(p);

// that particular instance of the class is than added to the container means that class is copied

here

f.setSize(400,400);

f.setVisible(true);

// firstly, size of the frame is set and then it makes visible in order to see the output

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// that frame is setDefaultCloseOperation when close buttin is pressed the frame completely exits

itself

} // end constructor

public static void main(String args[]){

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

TestA t = new TestA();

// the object of TestA is created in the main method as the compiler or interpreter interpret the

code from the main method so we give access to our code bt instantiating that class

Page 71: JAVA Manual remaining

71

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

In this demo arcs are drawn on the panel of our frame. Arcs can be drawn with drawArc(

) and fillArc( ) methods that can draw and fill the arc. We use paintComponent method for

grphic work.The method of drawArc contains int top, int left, int width, int height, int startAngle,

int sweepAngle while fillArc contains int top, int left, int width, int height, int startAngle, int

sweepAngle. All of this working of first class is then copied to another class so that it can be

displayed on the frame.

Program 93:

Write a code that display different colorful shapes.

Solution:

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class ColorDemo extends JPanel{

Page 72: JAVA Manual remaining

72

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and ColorDemo is its name and it extends JPanel*/

public void paintComponent(Graphics g) {

/* public method having no return type known as paintComponent and is used for painting and it

takes Graphics g as a parameter, g is the object of Graphics used to do graphics painting. */

Graphics2D g2 = (Graphics2D)g;

// for 2D graphics we create an object g2 of Graphics2D and initializes it

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

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

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

g2.setColor(c1);

// Color of g2 is set

g2.drawLine(0, 0, 100, 100);g.drawLine(0, 100, 100, 0);

g2.setColor(c2);

g2.drawLine(40, 25, 250, 180);

g2.drawLine(75, 90, 400, 400);

g2.setColor(c3);

g2.drawLine(20, 150, 400, 40);

g2.drawLine(5, 290, 80, 19);

g2.setColor(Color.red);

/* these lines of code using 2D graphics call drawLine() method which draw the Line at the

position written in parentheses and also call the setColor method that assigns different Colors at

the position defined in parentheses. */

g2.drawOval(10, 10, 50, 50);

g2.fillOval(70, 90, 140, 100);

Page 73: JAVA Manual remaining

73

g2.setColor(Color.blue);

g2.drawOval(190, 10, 90, 30);

/* these lines of code using 2D graphics call drawOval() method which draw the Oval at the

position written in parentheses and also call the setColor method that assigns different Colors at

the position defined in parentheses. */

g2.drawRect(10, 10, 60, 50);

g2.setColor(Color.cyan);

g2.fillRect(100, 10, 60, 50);

/* these lines of code using 2D graphics call drawRect() method which draw the Rectangle at the

position written in parentheses and also call the setColor method that assigns different Colors at

the position defined in parentheses and fillRect() method is called to fill the rectangle with the

color defines above. */

g2.drawRoundRect(190, 10, 60, 50, 15, 15);

/* these lines of code using 2D graphics call drawRoundRect() method which draw the

RundRectangle at the position written in parentheses. */

}

}

// through this class the above class is instantiated and will give output

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class Colrdemo{

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and TestA is its name */

public Colrdemo (){ // Constructor of the Colrdemo class

JFrame f = new JFrame();

// a frame is declared and initialized to show the output on this frame

Page 74: JAVA Manual remaining

74

Container c = f.getContentPane();

// a container is then initialized by calling the getContentPane() method. Everything that will be

shown on frame will first be added to it

c.setLayout(new BorderLayout());

// BorderLayout of the container is set by calling setLayout method

ColorDemo p = new ColorDemo ();

// the above class is instantiated in this class in order to get access to that class

c.add(p);

// that particular instance of the class is than added to the container means that class is copied

here

f.setSize(400,400);

f.setVisible(true);

// firstly, size of the frame is set and then it makes visible in order to see the output

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// that frame is setDefaultCloseOperation when close buttin is pressed the frame completely exits

itself

} // end constructor

public static void main(String args[]){

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Colrdemo t = new Colrdemo ();

// the object of Colrdemo is created in the main method as the compiler or interpreter interpret

the code from the main method so we give access to our code bt instantiating that class

} // closing curly brace } is used to close the definition of main() method

Page 75: JAVA Manual remaining

75

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

This demo displays the arcs and outlined square, oval, circle and filled square and oval

using drawRect( ), fillRect( ), and drawOval(), fillOval() and drawArc(), fillArc() methods. To

draw a rounded rectangle drawRoundRect() method is used. All of this work is performed by

using paintcomponent() method that perform this graphic’s work. The methods used in this

demo contains these things: drawRect contains int top, int left, int width, int height, fillRect

contains int top, int left, int width, int height.

Program94:

Write a code using graphics that draw ellipses

Solution:

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class Ellipses extends JPanel {

Page 76: JAVA Manual remaining

76

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and Ellipses is its name and it extends JPanel*/

public void paintComponent(Graphics g) {

/* public method having no return type known as paintComponent and is used for painting and it

takes Graphics g as a parameter, g is the object of Graphics used to do graphics painting. */

Graphics2D g2 = (Graphics2D)g;

// for 2D graphics we create an object g2 of Graphics2D and initializes it

g2.drawOval(10, 10, 50, 50);

g2.fillOval(100, 10, 75, 50);

g2.drawOval(190, 10, 90, 30);

g2.fillOval(70, 90, 140, 100);

/* these lines of code using 2D graphics call drawOval() method which draw the oval at the

position written in parentheses and also call the fillOval() method that fills the oval at the

position defined in parentheses. */

}

}

// through this class the above class is instantiated and will give output

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class ETest{

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and ETest is its name */

public ETest (){ // Constructor of the ETest class

JFrame f = new JFrame();

// a frame is declared and initialized to show the output on this frame

Page 77: JAVA Manual remaining

77

Container c = f.getContentPane();

// a container is then initialized by calling the getContentPane() method. Everything that will be

shown on frame will first be added to it

c.setLayout(new BorderLayout());

// BorderLayout of the container is set by calling setLayout method

Ellipses p = new Ellipses ();

// the above class is instantiated in this class in order to get access to that class

c.add(p);

// that particular instance of the class is than added to the container means that class is copied

here

f.setSize(400,400);

f.setVisible(true);

// firstly, size of the frame is set and then it makes visible in order to see the output

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// that frame is setDefaultCloseOperation when close buttin is pressed the frame completely exits

itself

} // end constructor

public static void main(String args[]){

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

ETest t = new ETest ();

// the object of ETest is created in the main method as the compiler or interpreter interpret the

code from the main method so we give access to our code bt instantiating that class

} // closing curly brace } is used to close the definition of main() method

Page 78: JAVA Manual remaining

78

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

In this program ellipse of different shapes are drawn using paintComponent() method of

graphics. To draw an ellipse drawOval() method is used and to assign different colors fillOval()

method is used. Both the methods Contains int top, int left, int width, int height and int top, int

left, int width, int height respectively.

Program 95:

Using graphics write a code that draws lines

Solution:

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class Lines extends JPanel{

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and Lines is its name and it extends JPanel*/

Page 79: JAVA Manual remaining

79

public void paintComponent(Graphics g) {

/* public method having no return type known as paintComponent and is used for painting and it

takes Graphics g as a parameter, g is the object of Graphics used to do graphics painting. */

Graphics2D g2 = (Graphics2D)g;

// for 2D graphics we create an object g2 of Graphics2D and initializes it

g2.drawLine(0, 0, 100, 100);

g2.drawLine(0, 100, 100, 0);

g2.drawLine(40, 25, 250, 180);

g2.drawLine(75, 90, 400, 400);

g2.drawLine(20, 150, 400, 40);

g2.drawLine(5, 290, 80, 19);

/* these lines of code using 2D graphics call drawLine() method which draw the different Lines

at the different position written in parentheses. */

}

}

// through this class the above class is instantiated and will give output

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class Test1 {

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and Test1 is its name */

public Test1 (){ // Constructor of the Test1 class

JFrame f = new JFrame();

// a frame is declared and initialized to show the output on this frame

Container c = f.getContentPane();

Page 80: JAVA Manual remaining

80

// a container is then initialized by calling the getContentPane() method. Everything that will be

shown on frame will first be added to it

c.setLayout(new BorderLayout());

// BorderLayout of the container is set by calling setLayout method

Lines p = new Lines ();

// the above class is instantiated in this class in order to get access to that class

c.add(p);

// that particular instance of the class is than added to the container means that class is copied

here

f.setSize(400,400);

f.setVisible(true);

// firstly, size of the frame is set and then it makes visible in order to see the output

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// that frame is setDefaultCloseOperation when close buttin is pressed the frame completely exits

itself

} // end constructor

public static void main(String args[]){

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Test1 t = new Test1 ();

// the object of Test1 is created in the main method as the compiler or interpreter interpret the

code from the main method so we give access to our code bt instantiating that class

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 81: JAVA Manual remaining

81

Output:

Discussion:

In this demo drawLine(int startX, int startY, int endX, int endY) method is used. The

drawLine() method displays a line on the panel of the frame that begins at startX, startY and

ends at endX, endY. Using the drawLine() method this demo draws different types of lines. All

of this is done by paintComponent() method of graphics.

Program 96:

Using graphics write a code that draw rectangles

Solution:

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

Page 82: JAVA Manual remaining

82

public class Rectangles extends JPanel {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and Rectangles is its name and it extends JPanel*/

public void paintComponent(Graphics g) {

/* public method having no return type known as paintComponent and is used for painting and it

takes Graphics g as a parameter, g is the object of Graphics used to do graphics painting. */

super.paintComponent(g);

// erasing behavior. It clears the output’s frame

Graphics2D g2 = (Graphics2D)g;

// for 2D graphics we create an object g2 of Graphics2D and initializes it

g2.drawRect(10, 10, 60, 50);

g2.fillRect(100, 10, 60, 50);

g2.drawRoundRect(190, 10, 60, 50, 15, 15);

g2.fillRoundRect(70, 90, 140, 100, 30, 40);

/* these lines of code using 2D graphics call drawRect() & drawRoundRect() method which

draw the rectangle and round rectangle at the position written in parentheses and also call the

fillRect() & fillRoundRect() method that fills both the shapes at the position defined in

parentheses. */

}

}

// through this class the above class is instantiated and will give output

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class Rec{

Page 83: JAVA Manual remaining

83

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and Rec is its name */

public Rec (){ // Constructor of the Rec class

JFrame f = new JFrame();

// a frame is declared and initialized to show the output on this frame

Container c = f.getContentPane();

// a container is then initialized by calling the getContentPane() method. Everything that will be

shown on frame will first be added to it

c.setLayout(new BorderLayout());

// BorderLayout of the container is set by calling setLayout method

Rectangles p = new Rectangles ();

// the above class is instantiated in this class in order to get access to that class

c.add(p);

// that particular instance of the class is than added to the container means that class is copied

here

f.setSize(400,400);

f.setVisible(true);

// firstly, size of the frame is set and then it makes visible in order to see the output

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// that frame is setDefaultCloseOperation when close buttin is pressed the frame completely exits

itself

} // end constructor

public static void main(String args[]){

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

Page 84: JAVA Manual remaining

84

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Rec t = new Rec ();

// the object of Rec is created in the main method as the compiler or interpreter interpret the

code from the main method so we give access to our code bt instantiating that class

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

In this program firstly packages are imported then our class Rectangles extends JPanel

and then using paintComponent() method to perform graphic’s work this program draw

rectangles of different shapes. In this code fillRect(), drawRect(), drawRoundRect() methods are

used to put colors, to draw and to make it round cornered respectively.

Page 85: JAVA Manual remaining

85

Program 97:

Write a code that shows the local environment’s Font list family

Solution:

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class ShowFonts extends JPanel {

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and ShowFonts is its name and it extends JPanel*/

public void paint(Graphics g) {

/* public method having no return type known as paint and is used for painting and it takes

Graphics g as a parameter, g is the object of Graphics used to do graphics painting. */

String msg = ""; // msg a variable of type string

String FontList[]; // string to get FontList[]

GraphicsEnvironment ge =

GraphicsEnvironment.getLocalGraphicsEnvironment();

// GraphicsEnvironment a built in class used to get LocalGraphicsEnvironment and it will be

stored in ge object

FontList = ge.getAvailableFontFamilyNames();

// FontList stores the available font family names

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

/*a for loop is declared here it contains three parts initialization that initializes i to 0, condition

i.e 1 is greater than FontList.length, iteration i.e increment of i. Firstly loop initialize i to 0 and

then it will check the condition that either it is true or not, if it is true then the next statement will

be compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

msg += FontList[i] + " ";g.drawString(msg, 4, 16);

Page 86: JAVA Manual remaining

86

// stores font list and its draw properties in msg string

}

}

// through this class the above class is instantiated and will give output

import javax.swing.*;

import java.awt.*;

// first of all import two libraries awt and swing so that they can handle our code

public class Show{

// /*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and Show is its name */

public Show (){ // Constructor of the Show class

JFrame f = new JFrame();

// a frame is declared and initialized to show the output on this frame

Container c = f.getContentPane();

// a container is then initialized by calling the getContentPane() method. Everything that will be

shown on frame will first be added to it

c.setLayout(new BorderLayout());

// BorderLayout of the container is set by calling setLayout method

ShowFonts p = new ShowFonts ();

// the above class is instantiated in this class in order to get access to that class

c.add(p);

// that particular instance of the class is than added to the container means that class is copied

here

f.setSize(400,400);

f.setVisible(true);

// firstly, size of the frame is set and then it makes visible in order to see the output

Page 87: JAVA Manual remaining

87

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// that frame is setDefaultCloseOperation when close buttin is pressed the frame completely exits

itself

} // end constructor

public static void main(String args[]){

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

Show t = new Show ();

// the object of Show is created in the main method as the compiler or interpreter interpret the

code from the main method so we give access to our code bt instantiating that class

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

The getAvailableFontFamilyNames( ) method is used and is defined by the

GraphicsEnvironment class. This method returns an array of strings that contains the names of

the available font families. The getAllFonts( ) method is defined by the GraphicsEnvironment

class. Then this reference is obtained by using the getLocalGraphicsEnvironment( ) static

method, which is defined by Graphics Environment.

Page 88: JAVA Manual remaining

88

Program 98:

Write a program to import java. io. file.

Solution:

class FileDemo {

/* this line contains a keyword class that shows that a class is going to start and FileDemo is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

static void p(String s) {

// a static method having string as a parameter

System.out.println(s);

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the code written

inside the parentheses. */

}

public static void main(String args[]) {

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared. Then opening curly

brace { shows that form here the method’s definition is going to begin */

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

// a file’s object is declared and initializes

p("File Name: " + f1.getName()); // prints file name

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

// prints path after getting it throught getPath() method

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

// prints path after getting an absolute path by calling its method

Page 89: JAVA Manual remaining

89

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

// this statement will get the parent of the file and print it

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

// if file exists then it will print exists otherwise does not exists will print. This is done by using

ternary opeartor

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

// if file is writeable then it will print is writeable otherwise is not writeable will print. This is

done by using ternary opeartor

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

// if file is readable then it will print is readable otherwise is not readable will print. This is

done by using ternary opeartor

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

// if file is a directory then it will print a directory otherwise not will print. This is done by using

ternary opeartor

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

// if file is a normal file then it will print is normal file otherwise might be a named pipe will

print. This is done by using ternary opeartor

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

// if file is absolut then it will print is absolute otherwise is not absolute will print. This is done

by using ternary opeartor

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

// displays when the file was last modified

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

// displays the size of the file by calling .lenght() method

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Page 90: JAVA Manual remaining

90

Output:

Discussion:

In this demo getName(), getPath(), getAbsolutePath(), getParent(), exists(), canwrite(),

canRead(), isDirectory(), isFile(), isAbsolute(), lastModfied() and length() methods are used that

checks the name, path, absolute path of the file and displays ‘em. Using getParent() method it

displays its origin and then checks if it exists then checks either it is readable and writable and is

it a directory?. Then checks if it is a file or not. The isFile() method returns true if called on a file

and false if called on a directory. Hence this method can be used to make sure the file will

behave as a file. The isAbsolute( ) method returns true if the file has an absolute path and false if

its path is relative. The isFile() and isAbsolute() methods are called using ternary operator.

Program 99:

Write a java program to import java’s directory files.

Solution:

class DirList {

Page 91: JAVA Manual remaining

91

/* this line contains a keyword class that shows that a class is going to start and DirList is the

name of this class. Opening curly brace { shows that form here a class’ definition is going to

begin */

public static void main(String args[]) {

String dirname = "/java";

// a variable dirname of type string is declared and initialized

File f1 = new File(dirname);

// a new File of dirname is declared and initialized here

if (f1.isDirectory()) { // checks the condition

System.out.println("Directory of " + dirname);

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the String written

inside parentheses */

String s[] = f1.list(); // invoking obj.

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 0, condition

i.e i is less than s.lenght, iteration i.e increment of i. Firstly loop initialize i to 0 and then it will

check the condition that either it is true or not, if it is true then the next statement will be

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

File f = new File(dirname + "/" + s[i]);

// another file is created here that is store in f object of file

if (f.isDirectory()) { //condition check

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

} else { // condition statement

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

Page 92: JAVA Manual remaining

92

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

}

}

} else { // jump statement

System.out.println(dirname + " is not a directory");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

}

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Discussion:

This program demonstrates how to check if the file is directory or not. This demo using

isDirectory() method checks the file whose name is stored in the string dirname is directory or

not if so then it will do on further checking else it will display that it is not a directory file. The

isDirectory() method is a built in method.

Page 93: JAVA Manual remaining

93

Program 100:

Write a simple java program to demonstrate the file input stream.

Solution:

class FileInputStreamDemo {

/* this line contains a keyword class that shows that a class is going to start and

FileInputStreamDemo is the name of this class. Opening curly brace { shows that form here a

class’ definition is going to begin */

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

// Your program begin with a call to main.

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared and it can throw

IOException. Then opening curly brace { shows that form here the method’s definition is going

to begin */

int size; // declaring local variable of type int

InputStream f =new FileInputStream("FileInputStreamDemo.java");

// input stream creates a new file of input stream with the name of FileInputStreamDemo.java

System.out.println("Total Available Bytes: " +(size = f.available()));

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses i.e includes the available sie of file also */

int n = size/40; // declaring another local variable of type int

System.out.println("First " + n +" bytes of the file one read() at a time");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

Page 94: JAVA Manual remaining

94

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 0, condition

i.e i is less than n which is the size /40, iteration i.e increment of i. Firstly loop initialize i to 0

and then it will check the condition that either it is true or not, if it is true then the next statement

will be compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 1 until the condition is not satisfied*/

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

System.out.println("Reading the next " + n +" with one read(b[])");

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

byte b[] = new byte[n];

// an object of byte is declared and initialized here

if (f.read(b) != n) { // check condition

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

}

Page 95: JAVA Manual remaining

95

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

f.skip(size/2);

// skip half of the remaining bytes with skip() method

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

if (f.read(b, n/2, n/2) != n/2) { // check condition if true then proceed

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Page 96: JAVA Manual remaining

96

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

}

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

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

/* System is a built in function used to give access to the system. Out is used for the output.

Println is used to print or display the string passed to it & ln is used to goto the next line.

Semicolon is used to terminate the statement/line. This line of code will print the statement

written inside the parentheses */

f.close(); // close the file

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Page 97: JAVA Manual remaining

97

Discussion:

This is java program in which firstly a file of java is created then using available() method it

search for the available size for this file and displays it but this program throws an exception. Here

filepath is the full path name of the file and fileObj is a file object that describes the file. This demo also

displays the number of remaining bytes and skip half of the remaining bytes with skip() method.

Program 101:

Write a program to demonstrate the file output stream output.

Solution:

class FileOutputStreamDemo {

/* this line contains a keyword class that shows that a class is going to start and

FileOutputStreamDemo is the name of this class. Opening curly brace { shows that form here

a class’ definition is going to begin */

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

/*this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it. Static is a keyword that allows the main() method to be execute

without instantiating an instance of that class. Void means this main() method has no return

type. In parenthesis a parameter args[], an array of type String is declared and can throw

IOException. Then opening curly brace { shows that form here the method’s definition is going

to begin */

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.";

// a string for the file is declared and initialized

byte buf[] = source.getBytes(); // gets bytes of the string

OutputStream f0 = new FileOutputStream("file1.txt");

// creating another file of output stream

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

/*a for loop is declared here it contains three parts initialization i.e initializes i to 0, condition

i.e i is less than buf.lenght, iteration i.e increment of i. Firstly loop initialize i to 0 and then it

will check the condition that either it is true or not, if it is true then the next statement will be

Page 98: JAVA Manual remaining

98

compiled, after that control/system will pass to the iteration process then it will check the

condition if it is fulfilled then the statement given below will be executed again i.e it will go on

increasing the value of i by 2 until the condition is not satisfied*/

f0.write(buf[i]); // writes the string in the file

}

f0.close(); // stream to close file.

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

// another file is declared and initialized

f1.write(buf); // writing file of output stream

f1.close(); // close file of output stream

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

// another file of output stream is declared and initialized with name file3.txt

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

// writes what’s written inside the parentheses

f2.close(); // close stream

} // closing curly brace } is used to close the definition of main() method

} // closing curly brace } is used to close the definition of class

Output:

Page 99: JAVA Manual remaining

99

Discussion:

In this demo firstly a string is declared and initialized then using bytes data structure the

array of bytes of that string is stored in buf[] then a file of name file1.txt is created using

outputStream() and in it that bytes of string are stored using write.buf[] method then this file is

cloed then in the same way file2 and file3 is created and written.

Program 102:

Write a code that displays an applet having something written in it.

Solution:

import java.awt.*;

import java.applet.*;

import java.net.*;

// import all the required packages first

public class ACDemo extends Applet {

/* this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and ACDemo is its name and it extends Applet*/

Page 100: JAVA Manual remaining

100

public void start(){

/* public means it is publically accessible and void means it has no return type and start() is the

name of this method*/

AppletContext ac = getAppletContext();

/* AppletContext is an interface that provides means to control the browser environment in

which it is running that stores the applet Context by calling getAppletContext() method*/

URL url = getCodeBase();

/* The getCodeBase() method gets the base URL and commonly used to establish a path to other

files or folders that are in the same location as the class being run. This is the URL of the

directory which contains this applet.*/

try{

/* From this line of code the try block starts. Opening delimiter shows that try block’s definition

is going to start. This block will try to interpret what is written inside it. Otherwise exception will

occur that will be caught by the catch block, written right after the try block*/

ac.showDocument(new URL(url + "Test.html"));

/*using ac the object of AppletContext the showDocument method is called that inialize the URL

and shows the url and the html file of the applet*/

}catch(MalformedURLException e){ // catch block starts

showStatus("URL not Found!");

/*if the MalformedURLException occurs then the above line of code will execute. This

exception occurs if the URL string is not parse-able or contains an unsupported protocol.*/

} // catch block closed

} // start method closed

} // class closed

HTML Code:

<html> // html is extension and this file is going to start fron here

<head> // head starts from here

<title> ACDemo </title> // title starts and ends

Page 101: JAVA Manual remaining

101

<h1> Java </h1>

</head> // head ends

<body> // body starts

<p> Object Oriented Programming </p>

<applet code = "ACDemo.class" width = 300 height = 300>

// applet starts and conatains the applet's class file's name that will be displayed in the

mentioned size

</applet> //applet ends

</body> // body ends

</html> // html file ends

Output:

Discussion:

This demo creates a simple applet that using getAppletContext() method get the context

and then gat the url of the code base and then tries to show the document using the

showDocument() method. Then the HLML file of this source code is created and hence the

applet is shown on the browser.

Page 102: JAVA Manual remaining

102

Program 103:

Write a demo by extending applet that shows the status of the window

Solution:

import java.awt.*;

import java.applet.*;

// import all the required packages

public class StatusWindow extends Applet{

/* this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and StatusWindow is its name and it extends Applet*/

public void init(){

/* public means it is publically accessible and void means it has no return type and init() is the

name of this method*/

setBackground(Color.pink); // sets the background color

}

public void paint(Graphics g){ // paints the statements written in it using

graphics g

g.drawString("This is my applet window..",10,20); // draws string

showStatus("This is my status window.."); // shows the status

written in parentheses.

}

}

HTML Code:

<html> // html is extension and this file is going to start fron here

<head> // head starts from here

<title>Status Window</title> // title starts and ends

Page 103: JAVA Manual remaining

103

</head> // head ends

<body> // body starts

<applet code = "StatusWindow.class" width = 100 height = 50>

// applet starts and contains the applet's class file's name that will be displayed in the

mentioned size

</applet> //applet ends

</body> // body ends

</html> // html file ends

Output:

Discussion:

This is a simple applet demo that first import all the packages and then extends the

applet and then create a function in which it sets the background color to pink and then shows the

status of the window by calling the showStatus() method.

Program 104:

Write a demo using applets that draw string on the applet’s page .

Solution:

import java.awt.*;

Page 104: JAVA Manual remaining

104

import javax.swing.JApplet;

// import all required packages

public class HelloApplet extends JApplet {

/* this line of code shows that public is an access specifier that allows a programmer to control

its visibility or access, means this class is accessible out of the class in which it is declared i.e

anyone publically can access it and HelloApplet is its name and it extends Applet*/

public void paint(Graphics g) {

/* public means it is publicly accessible and void means it has no return type and paint() is the

name of this method that do graphic work*/

g.drawString( "Hello World!", 30, 30 );

// draws string written in parentheses

}

}

HTML Code:

<html> // html is extension and this file is going to start fron here

<head> // head starts from here

<title> Hello Applet </title> // title starts and ends

<body> // body starts

<applet code = "HelloApplet.class" width=150 height=100>

// applet starts and conatains the applet's class file's name that will be displayed in the

mentioned size

</applet> //applet ends

</body> // body ends

</html> // html file ends

Page 105: JAVA Manual remaining

105

Output:

Discussion:

This demo first import the required packages then create a class and calls the paint

method to do drawing and then using graphics g displays the string that is “Hello World”.