200

Manual of JAVA (more than Half)

Embed Size (px)

DESCRIPTION

Manual of java more than half contains at least 77 programs.. remaining is also uploaded.. Hope u guys love it because it is the best version

Citation preview

Page 1: Manual of JAVA (more than Half)
Page 2: Manual of JAVA (more than Half)

2

Table of ContentsProgram 1:.................................................................................................................................................11

Solution:....................................................................................................................................................11

Output:......................................................................................................................................................12

Discussion:................................................................................................................................................12

Program 2:.................................................................................................................................................13

Solution:....................................................................................................................................................13

Output:......................................................................................................................................................14

Discussion:................................................................................................................................................14

Program 3:.................................................................................................................................................14

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

Output:......................................................................................................................................................16

Discussion:................................................................................................................................................17

Program 4:.................................................................................................................................................17

Solution:....................................................................................................................................................17

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

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

Program 5:.................................................................................................................................................19

Solution:....................................................................................................................................................19

Output:......................................................................................................................................................21

Discussion:................................................................................................................................................21

Program 6:.................................................................................................................................................21

Solution:....................................................................................................................................................21

Output:......................................................................................................................................................23

Discussion:................................................................................................................................................23

Program 7:.................................................................................................................................................23

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

Output:......................................................................................................................................................24

Discussion:................................................................................................................................................25

Program 8:.................................................................................................................................................25

Page 3: Manual of JAVA (more than Half)

3

Solution:....................................................................................................................................................25

Output:......................................................................................................................................................26

Discussion:................................................................................................................................................26

Program 9:.................................................................................................................................................27

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

Output:......................................................................................................................................................29

Discussion:................................................................................................................................................29

Program 10:...............................................................................................................................................29

Solution:....................................................................................................................................................30

Output:......................................................................................................................................................32

Discussion:................................................................................................................................................32

Program 11:...............................................................................................................................................32

Solution:....................................................................................................................................................32

Output:......................................................................................................................................................33

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

Program 12:...............................................................................................................................................34

Solution:....................................................................................................................................................34

Output:......................................................................................................................................................35

Discussion:................................................................................................................................................36

Program 13:...............................................................................................................................................36

Solution:....................................................................................................................................................36

Output:......................................................................................................................................................37

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

Program14:................................................................................................................................................38

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

Output:......................................................................................................................................................41

Discussion:................................................................................................................................................41

Program 15:...............................................................................................................................................42

Solution:....................................................................................................................................................42

Output:......................................................................................................................................................43

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

Program 16:...............................................................................................................................................43

Page 4: Manual of JAVA (more than Half)

4

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

Output:......................................................................................................................................................46

Discussion:................................................................................................................................................46

Program 17:...............................................................................................................................................46

Solution:....................................................................................................................................................46

Output:......................................................................................................................................................48

Discussion:................................................................................................................................................48

Program 18:...............................................................................................................................................48

Solution:....................................................................................................................................................48

Output:......................................................................................................................................................50

Discussion:................................................................................................................................................50

Program 19:...............................................................................................................................................50

Solution:....................................................................................................................................................50

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

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

Program 20:...............................................................................................................................................52

Solution:....................................................................................................................................................52

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

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

Program 21:...............................................................................................................................................55

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

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

Discussion:................................................................................................................................................58

Program 22:...............................................................................................................................................58

Solution:....................................................................................................................................................58

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

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

Program 23:...............................................................................................................................................60

Solution:....................................................................................................................................................61

Output:......................................................................................................................................................63

Discussion:................................................................................................................................................63

Program 24:...............................................................................................................................................63

Page 5: Manual of JAVA (more than Half)

5

Solution:....................................................................................................................................................63

Output:......................................................................................................................................................66

Discussion:................................................................................................................................................66

Program 25:...............................................................................................................................................66

Solution:....................................................................................................................................................66

Output:......................................................................................................................................................69

Discussion:................................................................................................................................................69

Program 26:...............................................................................................................................................69

Solution:....................................................................................................................................................69

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

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

Program 27:...............................................................................................................................................71

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

Output:......................................................................................................................................................73

Discussion:................................................................................................................................................73

Program 28:...............................................................................................................................................73

Solution:....................................................................................................................................................73

Output:......................................................................................................................................................76

Discussion:................................................................................................................................................76

Program 29:...............................................................................................................................................76

Solution:....................................................................................................................................................76

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

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

Program 30:...............................................................................................................................................78

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

Output:......................................................................................................................................................79

Discussion:................................................................................................................................................79

Program 31:...............................................................................................................................................80

Solution:....................................................................................................................................................80

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

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

Program 32:...............................................................................................................................................81

Page 6: Manual of JAVA (more than Half)

6

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

Output:......................................................................................................................................................83

Discussion:................................................................................................................................................83

Program 33:...............................................................................................................................................83

Solution:....................................................................................................................................................83

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

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

Program 34:...............................................................................................................................................85

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

Output:......................................................................................................................................................88

Discussion:................................................................................................................................................88

Program 35:...............................................................................................................................................88

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

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

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

Program 36:...............................................................................................................................................91

Solution:....................................................................................................................................................91

Output:......................................................................................................................................................94

Discussion:................................................................................................................................................94

Program 37:...............................................................................................................................................94

Solution:....................................................................................................................................................94

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

Discussion:................................................................................................................................................96

Program 38:...............................................................................................................................................96

Solution:....................................................................................................................................................96

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

Discussion:................................................................................................................................................98

Program 39:...............................................................................................................................................99

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

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

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

Program 40:.............................................................................................................................................101

Page 7: Manual of JAVA (more than Half)

7

Solution:..................................................................................................................................................101

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

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

Program 41:.............................................................................................................................................103

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

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

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

Program 42:.............................................................................................................................................105

Solution:..................................................................................................................................................105

Output:....................................................................................................................................................107

Discussion:..............................................................................................................................................107

Program 43:.............................................................................................................................................107

Solution:..................................................................................................................................................107

Output:....................................................................................................................................................110

Discussion:..............................................................................................................................................110

Program 44:.............................................................................................................................................110

Solution:..................................................................................................................................................110

Output:....................................................................................................................................................111

Discussion:..............................................................................................................................................111

Program 45:.............................................................................................................................................112

Solution:..................................................................................................................................................112

Output:....................................................................................................................................................113

Discussion:..............................................................................................................................................113

Program 46:.............................................................................................................................................113

Solution:..................................................................................................................................................113

Output:....................................................................................................................................................114

Discussion:..............................................................................................................................................114

Program 47:.............................................................................................................................................115

Solution:..................................................................................................................................................115

Output:....................................................................................................................................................116

Discussion:..............................................................................................................................................116

Program 48:.............................................................................................................................................116

Page 8: Manual of JAVA (more than Half)

8

Solution:..................................................................................................................................................116

Output:....................................................................................................................................................117

Discussion:..............................................................................................................................................117

Program 49:.............................................................................................................................................118

Solution:..................................................................................................................................................118

Output:....................................................................................................................................................119

Discussion:..............................................................................................................................................119

Program 50:.............................................................................................................................................119

Solution:..................................................................................................................................................119

Output:....................................................................................................................................................120

Discussion:..............................................................................................................................................120

Program 51:.............................................................................................................................................120

Solution:..................................................................................................................................................120

Output:....................................................................................................................................................122

Discussion:..............................................................................................................................................122

Program 52:.............................................................................................................................................122

Solution:..................................................................................................................................................122

Output:....................................................................................................................................................123

Discussion:..............................................................................................................................................123

Program 53:.............................................................................................................................................124

Solution:..................................................................................................................................................124

Output:....................................................................................................................................................124

Discussion:..............................................................................................................................................125

Program 54:.............................................................................................................................................125

Solution:..................................................................................................................................................125

Output:....................................................................................................................................................126

Discussion:..............................................................................................................................................126

Program 55:.............................................................................................................................................127

Solution:..................................................................................................................................................127

Output:....................................................................................................................................................127

Discussion:..............................................................................................................................................128

Program 56:.............................................................................................................................................128

Page 9: Manual of JAVA (more than Half)

9

Solution:..................................................................................................................................................128

Output:....................................................................................................................................................129

Discussion:..............................................................................................................................................130

Program 57:.............................................................................................................................................130

Solution:..................................................................................................................................................130

Output:....................................................................................................................................................131

Discussion:..............................................................................................................................................131

Program 58:.............................................................................................................................................131

Solution:..................................................................................................................................................131

Output:....................................................................................................................................................132

Discussion:..............................................................................................................................................132

Program 59:.............................................................................................................................................132

Solution:..................................................................................................................................................133

Output:....................................................................................................................................................133

Discussion:..............................................................................................................................................134

Program 60:.............................................................................................................................................134

Solution:..................................................................................................................................................134

Output:....................................................................................................................................................135

Discussion:..............................................................................................................................................135

Program 61:.............................................................................................................................................135

Solution:..................................................................................................................................................136

Output:....................................................................................................................................................136

Discussion:..............................................................................................................................................136

Program 62:.............................................................................................................................................137

Write a program of interface....................................................................................................................137

Solution:..................................................................................................................................................137

Output:....................................................................................................................................................139

Description:.............................................................................................................................................140

Program 63:.............................................................................................................................................140

Write a program in which one interface can extend another....................................................................140

Solution:..................................................................................................................................................140

Output:....................................................................................................................................................141

Page 10: Manual of JAVA (more than Half)

10

Description:.............................................................................................................................................142

Program 64:.............................................................................................................................................142

Solution:..................................................................................................................................................142

Output:....................................................................................................................................................143

Discussion:...............................................................................................................................................143

Program 65:.............................................................................................................................................143

Solution:..................................................................................................................................................143

Output:....................................................................................................................................................144

Discussion:...............................................................................................................................................144

Program 66:.............................................................................................................................................144

Solution:..................................................................................................................................................144

Output:....................................................................................................................................................146

Discussion:...............................................................................................................................................146

Program 67:.............................................................................................................................................146

Solution:..................................................................................................................................................146

Output:....................................................................................................................................................147

Discussion:...............................................................................................................................................147

Program 68:.............................................................................................................................................148

Solution:..................................................................................................................................................148

Output:....................................................................................................................................................149

Discussion:...............................................................................................................................................149

Program 69:.............................................................................................................................................149

Solution:..................................................................................................................................................149

Output:....................................................................................................................................................151

Discussion:...............................................................................................................................................151

Program 70:.............................................................................................................................................151

Solution:..................................................................................................................................................151

Output:....................................................................................................................................................153

Discussion:...............................................................................................................................................153

Program 71:.............................................................................................................................................153

Solution:..................................................................................................................................................153

Output:....................................................................................................................................................154

Page 11: Manual of JAVA (more than Half)

11

Discussion:...............................................................................................................................................154

Program 72:.............................................................................................................................................155

Solution:..................................................................................................................................................155

Output:....................................................................................................................................................155

Discussion:...............................................................................................................................................156

Program 73:.............................................................................................................................................156

Solution:..................................................................................................................................................156

Output:....................................................................................................................................................158

Discussion:...............................................................................................................................................158

Program 74:.............................................................................................................................................158

Solution:..................................................................................................................................................158

Output:....................................................................................................................................................159

Discussion:...............................................................................................................................................159

Page 12: Manual of JAVA (more than Half)

12

Program 1:Write a simple program that explains the syntax of java code or

demonstrate how to write it.

Solution:class Example {

/* this line contains a keyword class that shows that a class is going to start and Example 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 */

System.out.println("This is a simple java program.");

/* 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 */

} // 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: Manual of JAVA (more than Half)

13

Output:

Discussion:In this program a class of name Example is declared then its definition starts. Its definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. This program simply displays the string that is “This is a simple java program”.

Program 2:Write a program that initializes a variable and display it times two.

Solution:class Example2 {

/* this line contains a keyword class that shows that a class is going to start and Example2 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

Page 14: Manual of JAVA (more than Half)

14

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 */

int num; // a variable of type integer is declared

num = 100; // a variable num is initialized to 100

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

/* 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. This statement of code prints the value of num variable of type int i.e 100*/

num = num * 2;

/*increases the value of num variable by 2. Semicolon is used to terminate the statement/line*/

System.out.println("num * 2: " + num);

/* 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. This statement of code prints the value of num times 2 i.e 200. Semicolon is used to terminate the statement/line */

} // 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 15: Manual of JAVA (more than Half)

15

Discussion:In this program a class of name Example2 is declared then its definition starts. Its definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. This program declares a variable called num then assigns the value to num that is 100 and then it displays the value of num by multiplying it by 2

Program 3:Write a program that demonstrate the use of “ if ” statement in java.

Solution:class ifsample {

/* this line contains a keyword class that shows that a class is going to start and ifsample 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 */

int x , y;

/*two variables of type int are declared. Semicolon is used to terminate the statement/line*/

x = 10;

y = 20;

// variables x & y are initialized. Semicolon is used to terminate the statement/line

if(x < y)

/*in this line of code an if statement with a condition is declared, that if x is less than y then the next statement will be interpret. The next statement will be interpret because this condition is true*/

Page 16: Manual of JAVA (more than Half)

16

System.out.println (" 'X' is less than 'Y' ");

/* 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. This statement of code will print out that 'X' is less than 'Y' only if the above statement is true which is true. Semicolon is used to terminate the statement/line */

x = x * 2;

/* increase the value of x from 10 to 20 and stores it in x. Semicolon is used to terminate the statement/line*/

if(x == y)

/* an if statement with a condition is declared, that if x == y then the next statement will be interpret or displayed or execute. So the above condition is true because now x is equal to y i.e 20*/

System.out.println (" 'X' is equal to 'Y' ");

/* 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. This statement of code will print out that 'X' is less than 'Y' only if the above statement is true which is true already. Semicolon is used to terminate the statement/line */

x = x * 2;

/* increase the value of x from 20 to 40 and stores it in x. Semicolon is used to terminate the statement/line*/

if(x == y)

/*an if statement with a condition is declared, that if x == y then the next statement will be interpret but here it is not true because x is not equal to y, it is greater than y*/

System.out.println (" You won't see anything ");

/*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. This statement of code will not print anything because the above if statement is not true so it will exit. Semicolon is used to terminate the statement/line */

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

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

Page 17: Manual of JAVA (more than Half)

17

Output:

Discussion:In this program a class of name ifsample is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. This program declares & defines two variables then it checks if x is less than y then it displays “x is less than y”. x is incremented x times 2 it will become equal to y so it displays that “x is now equal to y”. it again incremented x and checks if x is greater than y and displays it.

Program 4:Write a program that demonstrate the use of “ for ” loop in java.

Solution:/* Demonstrate the for loop. Call this file "fortest.java*/

class fortest {

/*this line contains a keyword class that shows that a class is going to start and fortest 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[]) {

Page 18: Manual of JAVA (more than Half)

18

/* 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 */

int x;

// a variable x of type int is declared. Semicolon is used to terminate the statement/line

for(x=0; x<10; x=x+1)

/*a for loop is declared here it contains three parts initialization i.e initializes x to 0, condition i.e x is less than 10, iteration i.e increment of x. Firstly loop initialize x to zero 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 x by 1 until the condition is not satisfied*/

System.out.println("This is x: " + x);

/* 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. This statement of code will print the string written in brackets and also print out the value of x until it is less than 10 i.e it will print it out only if the condition of for statement is true. Semicolon is used to terminate the statement/line */

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

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

Page 19: Manual of JAVA (more than Half)

19

Output:

Discussion:In this program a class of name fortest is declared then its definition starts. Its definition

is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. This class displays the value of x 10 times using for loop

Program 5:Write a program that uses a block of code as the target of a “for” loop.

Solution:class blocktest {

/* this line contains a keyword class that shows that a class is going to start and blocktest 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[]) {

Page 20: Manual of JAVA (more than Half)

20

/*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 */

int x, y;

// two variables x and y of type int are declared. Semicolon is used to terminate the statement/line

y = 20;

// variable y is initializes to 20. Semicolon is used to terminate the statement/line

for ( x=0; x<10; x++) {

/*a for loop is declared here it contains three parts initialization i.e initializes x to 0, condition i.e x is less than 10, iteration i.e increment of x. Firstly loop initialize x to zero 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 x by 1 until the condition is not satisfied i.e x<10. Opening curly brace { will separate the block of code of for loop i.e it means begin of block*/

System.out.println ("This is X: " + x);

System.out.println ("This is y: " + y);

/* 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. These statements of code will print the string written in brackets and also print out the value of x and y. Semicolon is used to terminate the statement/line */

y = y - 2;

/* here Y will be decreased by 2 and then the control passes to iteration portion in for loop and then the portion below that loop will be displayed until the condition will be less than 10 i.e it will print it out only if the condition of for statement is true i.e x<10. It after displaying them once check the decrement of Y by 2 and goes on further until x<10. Semicolon is used to terminate the statement/line */

Page 21: Manual of JAVA (more than Half)

21

} /* closing curly brace } is used to close the definition of for loop. Closing curly brace { will separate the block of code of for loop i.e it means end of 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:In this program a class of name blocktest is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. In this code the target of for loop is the block of code not just the statement of code.

Page 22: Manual of JAVA (more than Half)

22

Program 6:Write a program that calculates the distance traveled by light in

thousand days using long variables.

Solution:class Light {

/* this line contains a keyword class that shows that a class is going to start and Light 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 */

int lightspeed = 186000;

/*approximate light speed in miles per second. Lightspeed is a variable of type int. Semicolon is used to terminate the statement/line*/

long seconds, days, distance;

/*three variables of type long are declared. Semicolon is used to terminate the statement/line*/

days = 1000;

/*specify number of days here i.e initializes days to 1000. Semicolon is used to terminate the statement/line of code*/

seconds = days * 24 * 60 * 60;

// convert to seconds. Semicolon is used to terminate the statement/line

distance = lightspeed * seconds ;

/* calculating distance by multiplying lightspeed & seconds. Semicolon is used to terminate the statement/line*/

System.out.print("In " + days);

Page 23: Manual of JAVA (more than Half)

23

/* 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. This statement of code will print the string written in brackets and also print out the value of days. Semicolon is used to terminate the statement/line */

System.out.print(" days light will trevel about ");

System.out.println(distance + " miles");

/* 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 & ln is used to goto the next line. These statements of code will print the string written in brackets and also print out the value of miles written in 2nd one. Semicolon is used to terminate the statement/line */

} // 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 a class of name Light is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It computes distance light travels using 3 long variables. Then stores approximate speed of light in miles per second and specify number of days then convert to seconds and compute distance and displays it.

Page 24: Manual of JAVA (more than Half)

24

Program 7:Write a code to calculate area using double variables

Solution:class Area {

/* this line contains a keyword class that shows that a class is going to start and Area 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 */

double pi, r , a;

/* three variables of type double are declared . Semicolon is used to terminate the statement/line*/

r = 10.8;

// radius of circle . Semicolon is used to terminate the statement/line

pi = 3.1416;

/*approx. value of pi. Pi is declared . Semicolon is used to terminate the statement/line*/

a = pi * r * r;

//area’s formula to calculate area . Semicolon is used to terminate the statement/line

System.out.println("Area of circle is " + a);

/* 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. This statement of code will print the string written in brackets and also print out the value of a . Semicolon is used to terminate the statement/line */

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

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

Page 25: Manual of JAVA (more than Half)

25

Output:

Discussion:In this program a class of name Area is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It compute area of circle

Program 8:Write a program that demonstrate the use of char data type

Solution:class CharDemo {

/* this line contains a keyword class that shows that a class is going to start and CharDemo 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

Page 26: Manual of JAVA (more than Half)

26

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 */

char ch1, ch2;

// two variables of type char(character). Semicolon is used to terminate the statement/line

ch1 = 88;

/* code for X i.e ch1 variable is defined . Semicolon is used to terminate the statement/line*/

ch2 = 'Y';

//2nd character is defined to y. Semicolon is used to terminate the statement/line

System.out.println("ch1 and ch2: " + ch1 + " and " + ch2);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of ch1 and ch2 . Semicolon is used to terminate the statement/line*/

} // 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 27: Manual of JAVA (more than Half)

27

Discussion:In this program a class of name CharDemo is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It demonstrate char data type ch1 is assigned the value 88 which is ASCII letter that correspond to letter X

Program 9:Write a program that demonstrates how char variables behave like

integers.

Solution:class CharDemo2 {

/* this line contains a keyword class that shows that a class is going to start and CharDemo2 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 */

char ch1 = 'X';

//a variable X of char type is declared. Semicolon is used to terminate the statement/line

char ch2 = 'A';

//a variable A of char type is declared. Semicolon is used to terminate the statement/line

System .out.println("ch1 contains " + ch1);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of ch1. Semicolon is used to terminate the statement/line*/

Page 28: Manual of JAVA (more than Half)

28

ch1++;

/*an increment operator is used here to increase the value of ch1. Semicolon is used to terminate the statement/line*/

System.out.println("Now ch1 contains " +ch1);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of ch1. Semicolon is used to terminate the statement/line*/

System.out.println("ch2 contains " + ch2);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of ch2. Semicolon is used to terminate the statement/line */

System.out.println(" ~~~ LOOP ~~~ ");

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets. Semicolon is used to terminate the statement/line */

for (int i = 0; i<25 ; 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 25, iteration i.e increment of i. Firstly loop initialize i to zero 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 i.e x<25. Opening curly brace { will separate the block of code of for loop i.e it means begin of block*/

ch2 ++;

// ch2 is incremented by 1

System.out.println("Now value of ch2 is " +ch2);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of ch2 */

Page 29: Manual of JAVA (more than Half)

29

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

} // 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 a class of name CharDemo2 is declared then its definition starts.

Its definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. In this code ch1 is first given the value X. then it is incremented. Then it displays the incremented value of ch1 i.e the character in ASCII sequence.

Page 30: Manual of JAVA (more than Half)

30

Program 10:Write a program that demonstrate the use of Boolean values.

Solution:class BoolTest {

/* this line contains a keyword class that shows that a class is going to start and BoolTest 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 */

boolean b;

//booleab b is declared . Semicolon is used to terminate the statement/line

b = false;

/* bolean of varable b is initialized to false. Semicolon is used to terminate the statement/line*/

System.out.println("b is: " + 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of b */

b = true;

//now Boolean is initialized to true. Semicolon is used to terminate the statement/line

System.out.println("b is: " + 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of b*/

if(b)

Page 31: Manual of JAVA (more than Half)

31

// a boolean value can control the if statement

System.out.println("This statement is executed ");

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets */

b = false;

//now Boolean is initialized to false. Semicolon is used to terminate the statement/line

if(b)

// a boolean value can control the if statement.

System.out.println("This statement is not executed ");

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets which will not be displayed because the above if statement is not fulfilled. Semicolon is used to terminate the statement/line */

System.out.println("10 > 9 is " + (10 > 9));

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of 10 > 9 and outcome of this relational operator is a boolean value. Semicolon is used to terminate the statement/line */

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

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

Page 32: Manual of JAVA (more than Half)

32

Output:

Discussion:In this program a class of name BoolTest is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It demonstrate the Boolean values it can control the if statement. Then it displays the outcome of a relational operator i.e a Boolean value

Program 11:Write a program that demonstrate the use of dynamically initialized

values.

Solution:class DynInit {

/* this line contains a keyword class that shows that a class is going to start and DynInit 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

Page 33: Manual of JAVA (more than Half)

33

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 */

double a = 3.0, b = 4.0;

/*initialized two variables of type double. Semicolon is used to terminate the statement/line*/

double c = Math.sqrt(a * a + b * b);

/* c is dynamically initialized. Math.sqrt is used to take the square root of value which we get after multiplying a to a and b to b then adding them we get square root. Semicolon is used to terminate the statement/line*/

System.out.println("Hypotenuse is: " + 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of c*/

} // 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 34: Manual of JAVA (more than Half)

34

Discussion:In this program three local variables a, b and c are declared. C is dynamically initialized

that is by calling the function of square root i.e Math.Sqrt. at the end it displays the value of hypotenuse that is stored in c.

Program 12:Write a program that demonstrate the scope of block

Solution:class Scope {

/* this line contains a keyword class that shows that a class is going to start and Scope 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 */

int x = 10;

/* a variable x of type int is initialized to 10. Semicolon is used to terminate the statement/line */

if(x == 10) {

/* start new scope followed by the if condition if it is true then next code will be executed. Semicolon is used to terminate the statement/line*/

int y = 20;

/*initializes a variable of type int known only to this block. Semicolon is used to terminate the statement/line*/

System.out.println("X and Y: " + x + " and " + y);

/* 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 & ln is used to goto the next line. This statement of code will

Page 35: Manual of JAVA (more than Half)

35

print the string written in brackets and also print out the value of x and y. x and y both known here

*/

x = y * 2;

// x will store the value twice of y. Semicolon is used to terminate the statement/line

} // end of block scope

y = 100;

/* Error y not known here because y is initialized after the block scope as it is declared inside the block scope. Semicolon is used to terminate the statement/line*/

System.out.println("x is " + x);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of x. x is still known here because it is declared outside the block scope*/

} // 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 36: Manual of JAVA (more than Half)

36

Discussion:In this program the scope of a variable is described. Firstly a variable x of type int is

declared that is known to all code within main. Then it is initialized. Then another scope of if statement is started. Then a variable y is declared that is known only to the block of if. Then their values are displayed. Then the block is closed. After that y is again initialized but it will display error that y is not known here but x is still known here because it is declared within the main not in the block of if.

Program 13:Write a program that demonstrate the life time of variable.

Solution:class LifeTime {

/* this line contains a keyword class that shows that a class is going to start and LifeTime 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 */

int x;

//a variable x of type int is declared. Semicolon is used to terminate the statement/line

for(x = 0; x<3; x++) {

/*a for loop is declared here it contains three parts initialization i.e initializes x to 0, condition i.e x is less than 3, iteration i.e increment of x. Firstly loop initialize x to zero 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 x by 1 until the condition is not satisfied i.e x<10. Opening curly brace { will separate the block of code of for loop i.e it means begin of block*/

int y = -1; // y is initialized each time block is entered;

Page 37: Manual of JAVA (more than Half)

37

System.out.println("Y is : " + y);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of y */

y = 10; // changes the value of y by 10 i.e its life time is changed

System.out.println("Y is now: " + y);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of y */

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

} // 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 38: Manual of JAVA (more than Half)

38

Discussion:In this program a class of name LifeTime is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It demonstrate the lifetime of a variable. Variable x is declared in the main but the 2nd variable y is initialized each time block is entered. In the block of for loop value of y can be changed and displayed not outside it.

Program14:Write a code that demonstrate the basic arithmetic operators.

Solution:class BasicMath {

/* this line contains a keyword class that shows that a class is going to start and BasicMath 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 */

int a = 1 + 1;

/* addition arithmetic operation using integers. Variable a of type int is declared and initialized. Semicolon is used to terminate the statement/line*/

int b = a * 3;

/* multiplication arithmetic operation using integers. Variable b of type int is declared and initialized. Semicolon is used to terminate the statement/line*/

int c = b / 4;

/* division arithmetic operation using integers. Variable c of type int is declared and initialized. Semicolon is used to terminate the statement/line*/

Page 39: Manual of JAVA (more than Half)

39

int d = c - a;

/* subtraction arithmetic operation using integers. Variable d of type int is declared and initialized. Semicolon is used to terminate the statement/line*/

int e = -d;

/*variable e of type int is initialized and stores the negative value of d. Semicolon is used to terminate the statement/line*/

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

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of a */

System.out.println("b = " + 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of b */

System.out.println("c = " + 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of c */

System.out.println("d = " + d);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of d */

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

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of e */

double da = 1 + 1;

/* addition arithmetic operation using double. Variable da of type double is declared and initialized. Semicolon is used to terminate the statement/line*/

double db = da * 3;

Page 40: Manual of JAVA (more than Half)

40

/* multiplication arithmetic operation using double. Variable db of type double is declared and initialized. Semicolon is used to terminate the statement/line*/

double dc = db / 4;

/* division arithmetic operation using double. Variable dc of type double is declared and initialized. Semicolon is used to terminate the statement/line*/

double dd = dc - a;

/* subtraction arithmetic operation using double. Variable dd of type double is declared and initialized. Semicolon is used to terminate the statement/line*/

double de = -dd;

/*variable de of type int is initialized and stores the negative value of dd. Semicolon is used to terminate the statement/line*/

System.out.println("da = " + da);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of da */

System.out.println("db = " + db);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of db */

System.out.println("dc = " + dc);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of dc */

System.out.println("dd = " + dd);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of dd */

System.out.println("de = " + de);

Page 41: Manual of JAVA (more than Half)

41

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of de */

} // 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 performs the basic arithmetic operations of multiplication, division,

subtraction and addition using variables of type double and int and displays them.

Page 42: Manual of JAVA (more than Half)

42

Program 15:Write a program that demonstrates the use of modulus operator.

Solution:class modulus {

/* this line contains a keyword class that shows that a class is going to start and modulus 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 */

int x = 42;

double y = 42.25;

/* variables x and y of type int & double are initialized and declared respectively. Semicolon is used to terminate the statement/line*/

System.out.println("x mod 10 = " + x % 10);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of x % 10 */

System.out.println("y mod 10 = " + y % 10);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of y % 10 */

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

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

Page 43: Manual of JAVA (more than Half)

43

Output:

Discussion:In this program a class of name modulus is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It displays the value of x and y’s modulus 10.

Program 16:Write a program that demonstrates the use of assignment operator.

Solution:class OpEquals {

/* this line contains a keyword class that shows that a class is going to start and OpEquals 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 */

Page 44: Manual of JAVA (more than Half)

44

int a = 1;

/* a variable a of type int in initialized and declared. Semicolon is used to terminate the statement/line*/

int b = 2;

/* a variable b of type int in initialized and declared. Semicolon is used to terminate the statement/line*/

int c = 3;

/* a variable c of type int in initialized and declared. Semicolon is used to terminate the statement/line*/

int d = 4;

/* a variable d of type int in initialized and declared. Semicolon is used to terminate the statement/line*/

int e = 5;

/* a variable e of type int in initialized and declared. Semicolon is used to terminate the statement/line*/

int f = 5;

/* a variable f of type int in initialized and declared. Semicolon is used to terminate the statement/line*/

a += 5;

// increment in a by 5. Semicolon is used to terminate the statement/line

b *= 4;

// multiply b by 4. Semicolon is used to terminate the statement/line

c /= 6;

// divide c by 6. Semicolon is used to terminate the statement/line

d %= 8;

// modulus of d by 8. Semicolon is used to terminate the statement/line

f -= 10;

Page 45: Manual of JAVA (more than Half)

45

// decrement in f by 5. Semicolon is used to terminate the statement/line

e += d * c;

// increment in e by d * c. Semicolon is used to terminate the statement/line

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

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of a. Semicolon is used to terminate the statement/line */

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

/* This statement of code will print the string written in brackets and also print out the value of b. Semicolon is used to terminate the statement/line */

System.out.println(" c = " + c);

/* This statement of code will print the string written in brackets and also print out the value of c. Semicolon is used to terminate the statement/line */

System.out.println(" d = " + d);

/* This statement of code will print the string written in brackets and also print out the value of d. Semicolon is used to terminate the statement/line */

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

/* This statement of code will print the string written in brackets and also print out the value of e. Semicolon is used to terminate the statement/line */

System.out.println(" f = " + f);

/* This statement of code will print the string written in brackets and also print out the value of f. Semicolon is used to terminate the statement/line */

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

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

Page 46: Manual of JAVA (more than Half)

46

Output:

Discussion:In this program a class of name OpEquals is declared then its definition starts.

Its definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It demonstrate several assignment operators i.e += , *=, %= and displays their values

Program 17:Write a program that demonstrates the use of increment operator.

Solution:class IncDec {

/* this line contains a keyword class that shows that a class is going to start and IncDec 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[]) {

Page 47: Manual of JAVA (more than Half)

47

/*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 */

int a = 1;

int b = 2;

/* initializes a and b variables of type int to 1 and 2 resoectively. Semicolon is used to terminate the statement/line*/

int c;

int d;

/* declares c and d variables of type int. Semicolon is used to terminate the statement/line*/

c = ++b;

//c stores value of b incremented by 1. Semicolon is used to terminate the statement/line

d = a++;

//d stores value of a incremented by 1. Semicolon is used to terminate the statement/line

c++;

//c is incremented by 1

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

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

System.out.println("c = " + c);

System.out.println("d = " + d);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of a, b, c, d */

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

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

Page 48: Manual of JAVA (more than Half)

48

Output:

Discussion:In this program a class of name IncDec is declared then its definition starts. Its definition

is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. This program demonstrate the Increment operator i.e ++.

Program 18:Write a program that demonstrates the use of Ternary operator.

Solution:class Ternary {

/* this line contains a keyword class that shows that a class is going to start and Ternary 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

Page 49: Manual of JAVA (more than Half)

49

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 */

int i,k;

// two variables i and j of type int are declared

i = 10;

// variable I is initialized

k = i < 10 ? -i : i;

// get absolute value of i i.e if condition at left side is true then statement before colon will be displayed otherwise right one will be shown

System.out.println("Absolute value of " + i +" is " + k);

/* 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 & ln is used to goto the next line. This statement of code will print the string written in brackets and also print out the value of k */

i = -10;

k = i < 10 ? -i : i; // get absolute value of i

System.out.println("Absolute value of " + i +" is " + k);

/* This statement of code will print the string written in brackets and also print out the value of k*/

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

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

Page 50: Manual of JAVA (more than Half)

50

Output:

Discussion:In this program a class of name Ternary is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. This program demonstrate the ternary operator that get absolute value of i.

Program 19:Write a program that uses the box class and contains three variables

width, height, and depth and assign them values using a Box method.

Solution:/* A program that uses the Box class.

Call this file BoxDemo.java

*/

class Box {

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

double height;

Page 51: Manual of JAVA (more than Half)

51

double depth;

/* three variables width, height, depth of type double are declared here. Semicolon is used to terminate the statement/line*/

} //end of class definition

// The below class declares an object of type Box.

class BoxDemo {

/* this line contains a keyword class that shows that a class is going to start and BoxDemo 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 */

Box mybox = new Box();

// this line of code creates a box object called mybox

double vol;

/* a variable vol of type double is declared here. Semicolon is used to terminate the statement/line*/

mybox.width = 10;

mybox.height = 20;

mybox.depth = 15;

// these 3 lines assign values to mybox's instance variables

vol = mybox.width * mybox.height * mybox.depth;

// compute volume of box

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

Page 52: Manual of JAVA (more than Half)

52

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol */

} // end of main method

} // end of class

Output:

Discussion:In this program a class called box defines three variables width, height, length of type

double. Then a class called BoxDemo declares an object of type Box and then assign values to mybox’s instance variables. In the second last step it compute the value for the volume of box and stored it in variable vol and at the end it displays its value. In the output we get its value that is Volume is 3000.0

Program 20:Write a program that declares two objects of box’s class and then after

computing the volume of each object, display it.

Solution:// This program declares two Box objects.

class Box {

Page 53: Manual of JAVA (more than Half)

53

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

double height;

double depth;

/* three variables width, height, depth of type double are declared here. Semicolon is used to terminate the statement/line*/

} // end of Box class’s definition

class BoxDemo2 {

/* this line contains a keyword class that shows that a class is going to start and BoxDemo2 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 */

Box mybox1 = new Box();

Box mybox2 = new Box();

// these lines of code create 2 box object called mybox1 and mybox2

double vol;

/* a variable vol of type double is declared here. Semicolon is used to terminate the statement/line*/

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

// assigns different values to mybox1's instance variables

Page 54: Manual of JAVA (more than Half)

54

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// assigns different values to mybox1's instance variables

vol = mybox1.width * mybox1.height * mybox1.depth;

// compute volume of first box

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol of first box */

vol = mybox2.width * mybox2.height * mybox2.depth;

// compute volume of second box

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol of second box*/

} // end of main method

} // end of the class

Page 55: Manual of JAVA (more than Half)

55

Output:

Discussion:In this program a box class containing three variables width, height, length of type

double. Then a class BoxDemo2 declares two objects of box class namely mybox1, mybox2. Then it assigns different values to both of the objects separately using dot operator and after calculating the volume of both boxes it stores them in a variable vol and displays them separately.

Program 21:Write a program that includes a method to calculate and display

volume of box inside the box class.

Solution:// This program includes a method inside the box class.

class Box {

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

double height;

Page 56: Manual of JAVA (more than Half)

56

double depth;

/* three variables width, height, depth of type double are declared here. Semicolon is used to terminate the statement/line*/

void volume() {

/* display volume of a box. Void means this method of volume has no return type. Opening curly brace { shows that form here a method’s definition is going to begin*/

System.out.print("Volume is ");

/* System is a built in function used to give access to the system. Out is used for the output. Print 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. */

System.out.println(width * height * depth);

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol by calculating it */

} // end of method’s def.

} // end of class def

class BoxDemo3 {

/* this line contains a keyword class that shows that a class is going to start and BoxDemo3 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 */

Box mybox1 = new Box();

Box mybox2 = new Box();

Page 57: Manual of JAVA (more than Half)

57

// These lines of code create box object called mybox1 and mybox2

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

// these 3 lines assign different values to mybox1’s instance variables

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// these 3 lines assign different values to mybox1’s instance variables

mybox1.volume();

// display volume of first box by calling the volume method declared before inside the class

mybox2.volume();

// display volume of second box by calling the volume method declared before inside the class

} // end of main method

} // end of class’ definition

Output:

Page 58: Manual of JAVA (more than Half)

58

Discussion:In this program three instance variables width, height, depth of type double are declared.

Then a method of volume for a box is defined. Then a class BoxDemo3 is defined that contains 2 objects of class box and then assigns values to both of them separately. And then it displays the volume of each box separately by calling the function of volume declares inside the class.

Program 22:Write a program that returns the volume of a box by defining a box’

volume.

Solution:// Now, volume() returns the volume of a box.

class Box {

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

double height;

double depth;

/* three variables width, height, depth of type double are declared here. Semicolon is used to terminate the statement/line*/

double volume() {

return width * height * depth;

// here a method called volume is defined that compute and return volume

} // ending of method def.

} // ending of class def.

class BoxDemo4 {

/* this line contains a keyword class that shows that a class is going to start and BoxDemo4 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[]) {

Page 59: Manual of JAVA (more than Half)

59

/*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 */

Box mybox1 = new Box();

Box mybox2 = new Box();

// these lines of code create box’s objects called mybox1 and mybox2

double vol;

/* a variable vol of type double is declared here. Semicolon is used to terminate the statement/line*/

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

// assign different values to mybox1's instance variables

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// assign different values to mybox1's instance variables

vol = mybox1.volume();

// get volume of first box. Semicolon is used to terminate the statement/line

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol */

// get volume of second box

vol = mybox2.volume();

Page 60: Manual of JAVA (more than Half)

60

// get volume of second box. Semicolon is used to terminate the statement/line

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol */

} // end of the main method

} // end of class def.

Output:

Discussion:In this program three instance variables width, height, depth of type double are declared.

Then a method of volume for a box’s volume is defined that compute and return volume. Then a class BoxDemo4 is defined that contains 2 objects of class box and then assigns values to both of them separately. And then it displays the volume of each box separately by calling the function of volume declares inside the class.

Program 23:Write a program that uses the parameterized method inside the class to

display the volume of box.

Page 61: Manual of JAVA (more than Half)

61

Solution:// This program uses a parameterized method.

class Box {

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

double height;

double depth;

/* three variables width, height, depth of type double are declared here. Semicolon is used to terminate the statement/line*/

double volume() {

// It’s a method of type double called as volume.

return width * height * depth;

// compute and return volume.

} // end of method’s def

void setDim(double w, double h, double d) {

// this method sets dimensions of box ans is of no return type and is called as setDim

width = w;

height = h;

depth = d;

// three objects are used to set the dimensions.

} // end of method’s def.

} // end of class’ def.

class BoxDemo5 {

/* this line contains a keyword class that shows that a class is going to start and BoxDemo5 is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

Page 62: Manual of JAVA (more than Half)

62

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 */

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

/* these lines of code create box’s objects called mybox1 and mybox2 and a variable vol of type double is declared here. Semicolon is used to terminate the statement/line*/

mybox1.setDim(10, 20, 15);

mybox2.setDim(3, 6, 9);

// initialize each box and call the method setDim

vol = mybox1.volume();

// get volume of first box and stores it in vol variable

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol of first box*/

vol = mybox2.volume();

// get volume of second box and stores it in vol variable

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol of second box*/

} // end of main method

Page 63: Manual of JAVA (more than Half)

63

} // end of class def.

Output:

Discussion:In this program three instance variables width, height, depth of type double are declared.

Then a method of volume for a box is defined. Then a class BoxDemo3 is defined that contains 2 objects of class box and then assigns values to both of them separately. And then it displays the volume of each box separately by calling the function of volume declares inside the class.

Program 24:Write a program of class box that uses a constructor to initialize the

dimension of a box

Solution:/* Here, Box uses a constructor to initialize the dimensions of a box.

*/

class Box {

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

Page 64: Manual of JAVA (more than Half)

64

double height;

double depth;

/* three variables width, height, depth of type double are declared here. Semicolon is used to terminate the statement/line*/

Box() {

// This is the constructor for Box.

System.out.println("Constructing Box");

/* System is a built in function used to give access to the system. Out is used for the output. Print 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. */

width = 10;

height = 10;

depth = 10;

// the three variables declared above are initialized here

} // end of constructor def.

double volume() {

// It is a function of type double called as volume

return width * height * depth;

// compute and return volume.

} // end of method / function

} // end of class def.

class BoxDemo6 {

/* this line contains a keyword class that shows that a class is going to start and BoxDemo6 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[]) {

Page 65: Manual of JAVA (more than Half)

65

/*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 */

Box mybox1 = new Box();

Box mybox2 = new Box();

// declare, allocate, and initialize Box objects

double vol;

vol = mybox1.volume();

// get volume of first box

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

vol = mybox2.volume();

// get volume of second box

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol */

} // End of main method

} // end of class

Page 66: Manual of JAVA (more than Half)

66

Output:

Discussion:In this program Box uses a constructor to initialize the dimensions of a box. A class

named as Box is defined. In this class three variables of type double are declared then a constructor is defined that initialize them. Then a method volume of type double is defined that compute and return the volume. Then a class named as BoxDemo6 is defined that contain the man method. In it two objects of super class and a variable vol of type double are declared. Then the method of volume is called through the main method. Then the values are displayed.

Program 25:Write a program that uses parameterized constructor to initialize the

dimensions of a box

Solution:/* Here, Box uses a parameterized constructor to initialize the dimensions of a box.

*/

class Box {

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

Page 67: Manual of JAVA (more than Half)

67

double height;

double depth;

/* three variables width, height, depth of type double are declared here. Semicolon is used to terminate the statement/line*/

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

// This is the parameterized constructor for Box having 3 parameters.

width = w;

height = h;

depth = d;

// three object type variables are declared

} // end of constructor’s def.

double volume() {

// a method of type double called as volume is defined.

return width * height * depth;

// compute and return volume.

} // end of method’s def

} // end of class

class BoxDemo7 {

/* this line contains a keyword class that shows that a class is going to start and BoxDemo7 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 */

Page 68: Manual of JAVA (more than Half)

68

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box(3, 6, 9);

// declare, allocate, and initialize Box objects

double vol;

vol = mybox1.volume();

// get volume of first box

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol */

vol = mybox2.volume();

// get volume of second box

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

/* System is a built in function used to give access to the system. Out is used for the output. Print 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 displays the value of vol */

} // end of main method

} // end of class

Page 69: Manual of JAVA (more than Half)

69

Output:

Discussion:In this program three instance variables width, height, depth of type double are declared.

Then a constructor for a box is defined and a method of type double called as Volume is defined that returns the volume. Then a class BoxDemo7 is defined that contains 2 objects of class box and then assigns values to both of them separately. And then it displays the volume of each box separately by calling the function of volume and constructor declares inside the class.

Program 26:Write a program that demonstrate method overloading

Solution:class overloadDemo { // a class named as overloadDemo

void test() { //method named test with no return type

System.out.println("No parameters"); //prints the string written inside

} // end of method

void test(int a) { //method is overloading with a parameter

System.out.println("a is " +a); //prints the string written inside

} // end of method

Page 70: Manual of JAVA (more than Half)

70

void test(int a,int b ) { // method is overloaded with two parameters

System.out.println("a and b are "+ a +" " + b); //prints the string written inside

} // end of method

double test(double a) // again method is overloaded with one double type parameter and method is also of type double

System.out.println("double a:" +a); //prints the string written inside

return a*a; //will return square of a

} // end of method

} // end of class

class overload { // a class with name overload is going to start its definition

public static void main ( String args[]) { // main method

double result; // a variable result of type double

overloadDemo ob = new overloadDemo(); //creating an object ob of class overloadDemo

ob.test(); // default function call

ob.test(5); // one argument function call

ob.test(2,3); // two argument function call

result = ob.test(332.2); // a function of type double is called and value is stored in variable result

System.out.println("result of square of a is :" + result); //prints the string written inside

} // end of main

} // end of class

Page 71: Manual of JAVA (more than Half)

71

Output:

Discussion:In this program method overloading is described. A method named as test is overloaded 4

times. The first one takes no argument. The second one contain 3 and the third one contain 4 arguments and the forth contain one double parameter. When the method is called java compares the arguments and parameters and displays the output.

Program 27:Write a program in which automatic type conversion apply to

overloading

Solution:class overloadDemo { // class named as overloadDemo

void test() { //method created with name test

System.out.println("No parameters"); //prints the string written inside

} // end of method

Page 72: Manual of JAVA (more than Half)

72

void test(int a,int b ) { //method is overloading with two parameters

System.out.println("a and b are "+ a +" " + b); //prints the string written inside

} // end of method

double test(double a) { //function with double type of parameter

System.out.println("double a:" +a); //prints the string written inside

return a*a; //return square of a

} // end of method

} // end of class

class overload2{ //a class with name overload2

public static void main ( String args[]) { //main method

overloadDemo ob = new overloadDemo(); // an object ob of class overloadDemo

int i = 88; //initialize and define i

ob.test();

ob.test(5 ,20 );

ob.test( i );

ob.test(332.2);

// all the functions are called here

} // end of main

} // end of class

Page 73: Manual of JAVA (more than Half)

73

Output:

Discussion:In this program when an object called a function like ob.test(int) then no matching

method will be found. So java can automatically convert an int into double. Rest of the methods can be called the same way and values will be displayed

Program 28:Write a program that define three constructors to initialize the

dimensions of a box various ways

Solution:class box { // class name

double width;

double height;

double depth;

// three variables of typr double

box (box ob) { //construct clone of an object is overloaded

width= ob.width;

height=ob.height;

Page 74: Manual of JAVA (more than Half)

74

depth=ob.depth;

// reference of 3 variables is stored

}

box(double w , double h , double d) { //constructor used when all dimensions specified

width = w;

height=h;

depth=d;

}

box() { //constructor used when no dimensions specified

width=-1;

height=-1;

depth=-1;

}

box(double lenght) {//constructor used when cube is created

width = height = depth = lenght;

}

double volume() {

return width * height * depth ;//formula of finding area

}

}

class overloadCons2 {// class nanme

public static void main(String args[]) {

// main mehod

Page 75: Manual of JAVA (more than Half)

75

box mybox1 = new box(10,32,85);

box mybox2 = new box(); //creating objects of class box

box mycube= new box(7); //creating objects of class box

box myclone = new box(mybox1); // cloning objct of class box

double vol; // variable vol of type double

vol = mybox1.volume();

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

//get and display volume for first box

vol = mybox2.volume();

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

//get and display volume for second box

vol = mycube.volume();

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

//get and display volume for myclone

vol = myclone.volume();

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

//get and display volume for clone box

}

}

Page 76: Manual of JAVA (more than Half)

76

Output:

Discussion:This program displays the value of volume using constructor overloading. Constructor is

loaded when all dimensions are specified, when no dimension is satisfied and the variables a re initialized to -1 i.e empty. A constructor used to create an object then compute and return volume all this is done by calling them through main

Program 29:Write a program in which objects are passed to methods.

Solution:class test {

int a , b ; // two variables of type int

test (int i , int j ) { //constructor with two parameters

a=i;

j=b;

// variables are stored in I and j

}

boolean equals(test o) { //using object as parameters

Page 77: Manual of JAVA (more than Half)

77

if(o.a == a && o.b == b)

return true;

else

return false;

// if statement to check if statement is true or false and return the outcome

}

} // end of class

class PassObj { // class with a nems PassObj

public static void main(String args[]) { // main method

test ob1 = new test(100,22); // invoking constructor by creating object of that class

test ob2 =new test(100,22); //invoking constructor by creating object of that class

test ob3 = new test(12,63); //invoking constructor by creating object of that class

System.out.println("ob1==ob2 : " + ob1.equals(ob2));

System.out.println("ob1==ob3 : " + ob1.equals(ob3));

// print out the values. (.equals) is used to compare the strings

} // end of main

} // end of class

Page 78: Manual of JAVA (more than Half)

78

Output:

Discussion:In this program use of Boolean is described that on comparing two objects check that

both are identical or not and displays the result

Program 30:Write a program that demonstrate how simple types are passed by value.

Solution:class test { // class name

void meth(int i , int j) { //method with two int parameters

i *= 2;

j /= 2;

//performing operations of multiplication and division

} // en dof method

} // end of class

class callByValue { // class with a namecallByValue

public static void main(String args[]) { // main method

test ts = new test(); //creating object

Page 79: Manual of JAVA (more than Half)

79

int a =15;

int b = 20;

/* two variables of type int known as a and b are declared.Semicoln is used to terminated the statement*/

System.out.println("a and b before calling " + a +" "+ b); // prints the values

ts.meth(a , b); //invoking meth

System.out.println("a and b after calling " + a +" "+ b);//prints the string written inside

} // end of main

} // end of class

Output:

Discussion:In this program two variable a and b are displayed first before call and second after call

both will show same values because after calling constructor the it copies the values only not their address.

Page 80: Manual of JAVA (more than Half)

80

Program 31:Write a program that shows how to return an object

Solution:class test { // a clas with name test

int a; //initialize a

test(int i){ // one argument constructor

a=i; // a is stored or copied in I

} // end of constructor

test incByTen() { // a method of class test

test temp = new test(a+10); //an object of test class

return temp; // return temp

}

}

class ReturnObj { // class name

public static void main(String args[]) { // main method

test ob1 = new test(2); //creating object

test ob2; // object ob2 of class test

ob2 = ob1.incByTen(); //invoking function

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

System.out.println("ob2.a : " + ob2.a);// prints the values of both objects

ob2 = ob2.incByTen(); //for second object’s increment

System.out.println("ob2.a after second increse :" + ob2.a);

// prints the value of ob2 after increment

} // end of main

} // end of class

Page 81: Manual of JAVA (more than Half)

81

Output:

Discussion:In this code a variable a is declared and defined also. Then it is incremented by 10 using

method then in main method it is called through 2 objects. And displayed after that it is againg incremented by ten and its value is displayed

Program 32:Using java’s coding make a class of simple recursion

Solution:// A simple example of recursion.

class Factorial { // class with a name of factorial

// this is a recursive method

int fact(int n) { // recursive method to calculate factorial

int result; // result variable of type int

if(n==1) return 1; // returns 1 if n is 1

result = fact(n-1) * n; // a same method is called within its on body to calculate the factorial

System.out.println("n is " + n);

Page 82: Manual of JAVA (more than Half)

82

// prints n

return result; // return result

} // end of recursive method

} // end of class

class Recursion { // class with recursion name

public static void main(String args[]) { // main method of class

Factorial f = new Factorial(); // factorial function ‘s data is copied in f object of that class

System.out.println("Factorial of 3 is " + f.fact(3));

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

System.out.println("Factorial of 5 is " + f.fact(5));

// displays different factorials

} // end of main

} // end of class

Page 83: Manual of JAVA (more than Half)

83

Output:

Discussion: This code uses a recursive method that calls within its own body to calculate the factorial

of an integer and then this method is called through main and is diaplayed

Program 33:Using java’s coding demonstrate the use of static methods, variables

and blocks

Solution:class UseStatic { // a class of UseStatic

static int a = 3;// a static int a

static int b; // a static int b

static void meth(int x) { // a static method with one argument

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

Page 84: Manual of JAVA (more than Half)

84

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

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

// displays the values

} // end of class

static { // a static constructor

System.out.println("Static block initialized."); //prints the string written inside

b = a * 4; // b stores value of a times 4

} // end of constructor

public static void main(String args[]) { // main method

meth(42); //function is called

} // end of method

} // end of class

Output:

Discussion:This code demonstrate the use of static. As soon as the class UseStatic is loaded all of the

static statements are run and displays the value required.

Page 85: Manual of JAVA (more than Half)

85

Program 34:Write a simple program that demonstrate the syntax and usage of

inheritance.

Solution:// A simple example of inheritance.

// Create a superclass.

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 */

int i, j;

// two variables I and j of type int are declared

void showij() {

// a method of no return type called as showij is declared and its definition is going to begin

System.out.println("i and j: " + i + " " + j);

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line displays the value of i and j */

} // end of method

} // end of class

class B extends A {

/* Create a subclass class B by extending class A. extends mean class B is inherited from class A that is class B is child / sub class and class A is a parent or super class*/

int k;

// a variable K of type int is declared

void showk() {

// a method of no return type called as showk is declared and its definition is going to begin

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

Page 86: Manual of JAVA (more than Half)

86

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line displays the value of k */

} // end of method

void sum() {

// a method of no return type called as sum is declared and its definition is going to begin

System.out.println("i+j+k: " + (i+j+k));

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. This line displays the value of sum of i, j and k */

} // end of method

} // end of class

class SimpleInheritance {

/* this line contains a keyword class that shows that a class is going to start and SimpleInheritance 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 */

A superOb = new A();

// created an object of super class A.

B subOb = new B();

// created an object of child class B.

superOb.i = 10;

superOb.j = 20;

Page 87: Manual of JAVA (more than Half)

87

// The super class may be used by itself.

System.out.println("Contents of superOb: ");

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

superOb.showij();

System.out.println();

// The subclass has access to all public members of its super class.

subOb.i = 7;

subOb.j = 8;

subOb.k = 9;

System.out.println("Contents of subOb: ");

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line.*/

subOb.showij();

// showij method is called here

subOb.showk();

// showk method is called here

System.out.println();

System.out.println("Sum of i, j and k in subOb:");

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

subOb.sum();

// sum method is called here

}

Page 88: Manual of JAVA (more than Half)

88

}

Output:

Discussion:In this program a super class is created first in which a showij method is declared. Then

create a subclass by extending super class named as A. In the sub class two methods showk and sum are declared and the definition of every method is given in the main method. Then the simple inheritance class is defined in which all the functions are called or implemented. The super class may be used by itself and subclass has access to all public members or its superclass. At the end after the values are passed they are displayed in the manner they are shown in output.

Program 35:Write a program that demonstrate the concept of a super class

Solution:// Create a superclass.

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 */

Page 89: Manual of JAVA (more than Half)

89

int i; // a variable of type int is declared and it is public by default

private int j; //a variable I of type int is declared and it is private to A

void setij(int x, int y) {

i = x;

j = y;

}

/* a method of no data type called as setij is defined. Two parameters of type int are passed by value and are assigned to i and j. The whole definition is defined inside the delimiters. */

} // end of class’ def.

// A's j is not accessible here because it is private

class B extends A {

int total;

void sum() {

total = i + j; // ERROR, j is not accessible here

}

/* a child class B of super class A is defined here. In it a variable total of type int is declared. Inside the class a method of no return type called as sum is declared that claims to compute the sum but as the j variable is private so it shows an error i.e j is not accessible */

} // end of subclass’s def.

class Access {

/* this line contains a keyword class that shows that a class is going to start and Access 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

Page 90: Manual of JAVA (more than Half)

90

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 */

B subOb = new B(); // an object known as subOb of class B is created

subOb.setij(10, 12); // call of a function setij

subOb.sum(); // call of a function sum

System.out.println("Total is " + subOb.total);

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

} // end of main method

} // end of class’ def.

Output:

Discussion:This program does not compile because reference to j inside the sum method b causes an

access violation. Since j is declared private. It is only accessible by other members of its own class. Subclass has no access to it.

Page 91: Manual of JAVA (more than Half)

91

Program 36:Write a program that demonstrate the uses of inheritance to extend the

subclass

Solution:// This program uses inheritance to extend Box.

class Box {

/* this line contains a keyword class that shows that a class is going to start and Box is the name of this class. Opening curly brace { shows that form here a class’ definition is going to begin */

double width;

double height;

double depth;

// threevariables of type double are declared

// construct clone of an object

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

width = ob.width;

height = ob.height;

depth = ob.depth;

}

// constructor used when all dimensions specified

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

// a constructor with three argument is defined

width = w;

height = h;

depth = d;

}

Box() {

Page 92: Manual of JAVA (more than Half)

92

width = -1;

height = -1;

depth = -1;

}

// a constructor used when no dimensions specified, used -1 to indicate an uninitialized box

Box(double len) {

width = height = depth = len;

}

// constructor used when cube is created

double volume() {

return width * height * depth;

}

// this method compute and return volume

}

// Here, Box is extended to include weight.

class BoxWeight extends Box {

// a child class BoxWeight of super class Box is defined here

double weight; // weight of box of type double

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

// 4 argument constructor for BoxWeight

width = w;

height = h;

depth = d;

weight = m;

}

Page 93: Manual of JAVA (more than Half)

93

}

class DemoBoxWeight {

/* this line contains a keyword class that shows that a class is going to start and DemoBoxWeight 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 */

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

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

// two objects of BoxWeight class are creaed that is mybox1 and mybox2 and values are assigned

double vol; // a variable vol of type double is declared

vol = mybox1.volume(); // value of volume is stored in vol

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

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

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

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

System.out.println();

vol = mybox2.volume();

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

Page 94: Manual of JAVA (more than Half)

94

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

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

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

} // end of main method

} // end of class’ def

Output:

Discussion:DemoBoxWeight inherits all the characteristics of Box added the weight component to

them. It calls all the methods of super class and displays the values computed.

Program 37:Using super to overcome space hiding

Solution:// Using super to overcome name hiding.

Page 95: Manual of JAVA (more than Half)

95

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 */

int i; // a variable i of type int is declared

}

class B extends A { // Create a subclass B by extending class A.

int i; // this i hides the i in A

B(int a, int b) { // constructor of class B having 2 argument of type int

super.i = a; // i in A

i = b; // i in B

}

void show() {

// a method of no return type named as show is defined

System.out.println("i in superclass: " + super.i);

System.out.println("i in subclass: " + i);

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

}

}

class UseSuper {

/* this line contains a keyword class that shows that a class is going to start and UseSuper 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

Page 96: Manual of JAVA (more than Half)

96

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 */

B subOb = new B(1, 2); // object of subclass B is created

subOb.show(); // method show is called

}

}

Output:

Discussion:In his code the instance variable I in B hides the I in A. Super allows access to the i

defined in super class. The subclass access its data creating objects of it and by calling the methods of it and displays the output.

Program 38:Create a super class that demonstrate the use of constructors

Solution:// Create a super class.

Page 97: Manual of JAVA (more than Half)

97

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 */

A() { // constructor

System.out.println("Inside A's constructor.");

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

} // end of constructor’s def.

} // end of class’ def.

class B extends A { // Create a subclass by extending class A.

B() { // constructor of class B

System.out.println("Inside B's constructor.");

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

}

}

class C extends B { // Create another subclass by extending B.

C() { // constructor of class C

System.out.println("Inside C's constructor.");

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

}

}

class CallingCons {

Page 98: Manual of JAVA (more than Half)

98

/* this line contains a keyword class that shows that a class is going to start and CallingCons 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 */

C c = new C(); // object of class C is created

}

} // end of class

Output:

Discussion:In this code constructors are declared and defined and displays as they are defined and

declared.

Page 99: Manual of JAVA (more than Half)

99

Program 39:Writs a program that demonstrate that the methods with differing type

signatures are overloaded – overridden

Solution: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 */

int i, j; // two variables of type int

A(int a, int b) { // a 2 argument constructor

i = a;

j = b;

}

void show() {

// a method of no return type called as show is declared and its definition is going to begin

System.out.println("i and j: " + i + " " + j);

/* System is a built in function used to give access to the system. Out is used for the output. Print is used to print or display the value shows in braces & ln is used to goto the next line. Semicolon is used to terminate the statement/line. */

}

}

class B extends A { // Create a subclass by extending class A.

int k; // a variable k of type int

B(int a, int b, int c) { // 3 argument constructor of B

super(a, b);

k = c;

}

Page 100: Manual of JAVA (more than Half)

100

void show(String msg) { // a method sow of no type

System.out.println(msg + k);

// overload show()

}

}

class Override2 {

/* this line contains a keyword class that shows that a class is going to start and Override2 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 */

B subOb = new B(1, 2, 3); // object of class B

subOb.show("This is k: "); // this calls show() in B

subOb.show(); // this calls show() in A

} // end of main method

} // end of class

Page 101: Manual of JAVA (more than Half)

101

Output:

Discussion:In this code the method show() in B takes a string as a parameter. This makes its type

signature different from the one in A, which takes no parameter. Hence n overriding takes place.

Program 40:Write a program that demonstrates the use of if – else – if statement.

Solution:class IfElse {

/* this line contains a keyword class that shows that a class is going to start and IfElse 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 */

Page 102: Manual of JAVA (more than Half)

102

int month = 4;

// a variable month of type int is declared and define / initialize

String season;

/* a variable season of type string is declared. Semicolon is used to terminate the statement/line*/

if(month == 12 || month == 1 || month == 2)

/* an if statement is declared having three conditions in it i.e if month is equal to 12 or month is equal to 1 or month is equal to 2 matches the value of month initialized already then it will execute further and statement given below will be printed but as month is 4 so this condition will not execute*/

season = "Winter";

//winter is stored in string season. Semicolon is used to terminate the statement/line

else if(month == 3 || month == 4 || month == 5)

/* else if statement is declared having three conditions in it i.e if month is equal to 3 or month is equal to 4 or month is equal to 9 matches the value of month initialized already then it will execute further and statement given below will be printed but as month is 4 so this condition will not execute. Semicolon is used to terminate the statement/line*/

season = "Spring";

//spring is stored in string season. Semicolon is used to terminate the statement/line

else if(month == 6 || month == 7 || month == 8)

season = "Summer";

else if(month == 9 || month == 10 || month == 11)

season = "Autumn";

else

season = "Bogus Month";

System.out.println("April is in the " + season);

}

}

Page 103: Manual of JAVA (more than Half)

103

Output:

Discussion:In this program a class of name IfElse is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. In this class a variable month of type int is declared and initialized and a string season is also declared then an if – else – if ladder executes that calculate for accurate month that is 4 if condition satisfies then it will display the output.

Program 41:Write a program that demonstrates the use of switch.

Solution:class SampleSwitch { // a class with a name SampleSwitch

public static void main(String args[]) { // main method of no return type and is public

for(int i=0; i<6; i++) { // for loop’s working starts from here it has 6 iteration

switch(i) { // switch statement that switch on value of i

case 0: // first case

Page 104: Manual of JAVA (more than Half)

104

System.out.println("i is zero"); //prints the string written inside

break; // first case ends here. Break is a jump statement that passes the control to the end

case 1: // second case

System.out.println("i is one"); //prints the string written inside

break; // second case ends here. Break is a jump statement that passes the control to the end

case 2: // third case

System.out.println("i is two"); //prints the string written inside

break; // third case ends here. Break is a jump statement that passes the control to the end

case 3: // case four

System.out.println("i is three"); //prints the string written inside

break; // fourth case ends here. Break is a jump statement that passes the control to the end

default: // if neither of the case is satisfied thenits body will work

System.out.println("i is greater than 3"); //prints the string written inside

} // end of switch

} // end of for

} // end of main method

} // end of class’ body

Page 105: Manual of JAVA (more than Half)

105

Output:

Discussion:In this program a class of name SampleSwitch is declared then its definition

starts. Its definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It demonstrate the working of switch statement using for loop.

Program 42:Write a program that demonstrates that in switch break statements are optional.

Solution:class MissingBreak { // a class with a name MissingBreak

public static void main(String args[]) { // main method having no return type

for(int i=0; i<12; i++) // for loop having 12 iterations

switch(i) { // switch statement that operates on i

case 0:

Page 106: Manual of JAVA (more than Half)

106

case 1:

case 2:

case 3:

case 4:

System.out.println("i is less than 5");

break;

/* when i will be zero the control passes to case 0 as no break is used here so it will pass to next and so on but at case 4 it will print the string that is to be printed and then break statement let the control to pass to the end */

case 5:

case 6:

case 7:

case 8:

case 9:

System.out.println("i is less than 10");

break;

/* when i will be 5 the control passes to case 5 as no break is used here so it will pass to next and so on but at case 9 it will print the string that is to be printed and then break statement let the control to pass to the end */

default: // if none of the above statements a fulfilled then this will execute

System.out.println("i is 10 or more"); // the string shown in brackets will be printed

} //end of for

} // end of main

} // end of class

Page 107: Manual of JAVA (more than Half)

107

Output:

Discussion:In this program a class of name MissingBreak is declared then its definition

starts. Its definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It is showing that in a switch break statements are optional i.e by keeping some of the cases empty and defining only 1 or 2 with break we can get required output.

Program 43:Write a program that shows an improved version of switch statement i.e

using break in some cases.

Solution:class Switch { // a class with a name of Switch

public static void main(String args[]) { // main method of the class with no return type and is public having anrgument of type String

int month = 4; // a variable month of type int is initialized

Page 108: Manual of JAVA (more than Half)

108

String season; // a variable of type String is declared here

switch (month) { // it’s a switch statement that switch month to get the required month

case 12:

case 1:

case 2:

season = "Winter";

break;

/* firstly two cases of month are shown then third case is written as the 1st two cases do not have any break statement so control will continues to pass on until it meets the break statement, it does so if the month is 12 but if the month is 2 then case 2 will be execute and stores Winter in the season’s String and then go to the switch’s block due to break statement. Semicolon is used to terminate the line of code*/

case 3:

case 4:

case 5:

season = "Spring";

break;

/* firstly two cases of month are shown then third case is written as the 1st two cases do not have any break statement so control will continues to pass on until it meets the break statement, it does so if the month is 3 but if the month is 5 then case 5 will be execute and stores Winter in the season’s String and go to the out of the switch statement due to break statement. Semicolon is used to terminate the line of code*/

case 6:

case 7:

case 8:

season = "Summer";

break;

Page 109: Manual of JAVA (more than Half)

109

/* firstly two cases of month are shown then third case is written as the 1st two cases do not have any break statement so control will continues to pass on until it meets the break statement, it does so if the month is 6 but if the month is 8 then case 8 will be execute and stores Winter in the season’s String and go to the out of the switch due to break statement. Semicolon is used to terminate the line of code*/

case 9:

case 10:

case 11:

season = "Autumn";

break;

/* firstly two cases of month are shown then third case is written as the 1st two cases do not have any break statement so control will continues to pass on until it meets the break statement, it does so if the month is 9 but if the month is 11 then case 11 will be execute and stores Winter in the season’s String and go to out of the switch due to break statement. Semicolon is used to terminate the line of code*/

default:

season = "Bogus Month";

// if none of the above statement is true then this default statement will execute

} // end of switch statement’s def.

System.out.println("April is in the " + season + " season.");

// after break control comes here and print it

} // end of main method

} // end of class’ def.

Page 110: Manual of JAVA (more than Half)

110

Output:

Discussion:In this program a class of name Switch is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It contains a variable month of type int and season of type String and switch month to different cases and after gating the exact/required month it displays it

Program 44:Write a program that demonstrates the use of while loop.

Solution:// Demonstrate the while loop.

class While { // a class having class name While

public static void main(String args[]) { /* main method of no return type and is public having an argument args[] of type string and is static that is it can be execute without initialization */

int n = 10; // a variable n of type int is initialized here

while(n > 0) { // while n is greater than 0 then the body of while will execute until n = 10

System.out.println("Its JAVA's chapter number " +n);

Page 111: Manual of JAVA (more than Half)

111

/* 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. This statement of code prints statement written inside it and als displays the value of n. Semicolon is used to terminate the statement/line */

n--; //causes decrement of 1 in n

} // end of while loop

} // end of main method

} // end of class’s def.

Output:

Discussion:In this program a class of name While is declared then its definition starts. Its definition

is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. In the main method a variable n is initialized to 10 and then while loop work until n is greater than 0 and displays the corresponding output.

Page 112: Manual of JAVA (more than Half)

112

Program 45:Write a program that demonstrates the use of while loop having nobody

in it.

Solution:// the target of the loop can be empty

class Nobody { // class with a name of Nobody is defined

public static void main(String args[]){ // main method of no return type and is public having an argument args[] of type String

int i,j; // two variables of type int

i=500; // i is initialized to 500

j=1000; // j is initialized to 1000

// find midpoint between i and j

while(++i<--j); // no body in this loop

System.out.println("Midpoint is " + i);

//displays the statement written in brackets and also the value of i

} // end of main method

} // end of class’s def.

Page 113: Manual of JAVA (more than Half)

113

Output:

Discussion:In this program a class of name Nobody is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. This code works for the midpoint of i and j using while loop.

Program 46:Write a program that demonstrates the use of do – while loop

Solution:// Demonstrate the do-while loop.

class DoWhile { // a class with a name DoWhile

public static void main(String args[]) { // main method of class having no return type and is public . it contains an argument args[] of type String

int n = 10; // a vari able of type int is initialized

do { // do loop that execute its definition atleast 1 time

System.out.println("tick " + n);

Page 114: Manual of JAVA (more than Half)

114

/* 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. This statement of code prints the value of num times 2 i.e 200. Semicolon is used to terminate the statement/line */

n--; // n is decreased by 1

} // end of do loop

while(n > 0); // will continues until n is greater than 0

} // end of main

} //end of class’ def.

Output:

Discussion:In this program a class of name DoWhile is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It demonstrate the functioning of do – while loop.

Page 115: Manual of JAVA (more than Half)

115

Program 47:Write a program that demonstrates the use of for loop.

Solution:// Demonstrate the for loop.

class ForTick { // class having name ForTick

public static void main(String args[]) { /* main method of class having no return type and it is static and public & also contains an argument args[] of type int */

int n; // a variable n of type int

for(n=10; n>0; n--) { /* for loop starts from here. It will start when n = 10 and continues until n is greater than 10 and it contains a decrement operator also */

System.out.println("tick " + n); // prints the value of n

} // end of for loop

} // end of main method

} // end of class’s def.

Page 116: Manual of JAVA (more than Half)

116

Output:

Discussion:In this program a class of name ForTick is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}.

Program 48:Write a program that declare a loop control variable inside the for.

Solution:// Declare a loop control variable inside the for.

class ForStudent { // class with a name ForStudent

public static void main(String args[]) { /* main method of class having no return type and it is static and public & also contains an argument args[] of type int */

for(int n=10; n>0; n--) // here, n is declared inside of the for loop

Page 117: Manual of JAVA (more than Half)

117

System.out.println("Student " + n); // displays the value of n

} // end of main

} // end of class’s def

Output:

Discussion:In this program a class of name ForStudent is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It explains the loop control variable inside the for loop

Page 118: Manual of JAVA (more than Half)

118

Program 49:Write a program that find the primes.

Solution:// Test for primes.

class FindPrime { // class with a name FindPrime

public static void main(String args[]) { /* main method of class with no return type and is public. It contains an argument args[] of type String */

int num; // a variable num of type int

boolean isPrime = true; // a variable isPrime of type Boolean is initialized

num = 14; // num is initalized

for(int i=2; i <= num/i; i++) { /* for loops working starts here. In it i is initialized and this loop will continues until i < = num/I and an increment operator is also used */

if((num % i) == 0) { // an if statement which will execute when num modulus i is equal to 0

isPrime = false; // if the above condition is true then isPrime will be false

break; // break statement will transfer the control to the out of this block

} // end of if’s body

} // end of for loop’s def.

if(isPrime) System.out.println("Prime");// it will print prime if isPrime is true

else System.out.println("Not Prime");

// if then above statement is wrong then this will be displayed

} // end of main method

} // end of class’s def.

Page 119: Manual of JAVA (more than Half)

119

Output:

Discussion:In this program a class of name FindPrime is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. In this code a num equals to 14 is declared using its value the for loop continues to work. Inside the for loop if else statements are used to find the prime’s value.

Program 50:Write a program that demonstrates the use of comma.

Solution://using the comma

class Comma { // class wih name Comma

public static void main(String args[]) { // main method of the class which is public and is of no return type

int a, b; // two variables of type int separated by comma

b = 4; // b is initialized

for(a=1; a<b; a++, b--) { // for loop execute using a variable

System.out.println("a = " + a); // prints value of a

Page 120: Manual of JAVA (more than Half)

120

System.out.println("b = " + b); // prints value of b

// we can use b-- here also, as we use in C++ for decrement

} // end of for

} // end of main

} // end of class

Output:

Discussion:In this program a class of name Comma is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It shows the use of comma. This program initialized 2 variables separated by comma. One is initialized and second is used by the loop and then values of both variables are displayed.

Program 51:Write a program that execute if the parts of the for loop are empty

Solution:// Parts of the for loop can be empty.

Page 121: Manual of JAVA (more than Half)

121

class ForVar { // a class with name ForVar

public static void main(String args[]) { // main method of the class

int i; // variable of type int

boolean done = false; // variable of type boolean

i = 0; // i is initialized

for( ; !done; ) { // for loop can also be used in this way

System.out.println("i is " + i); // prints i

if(i == 10) done = true; // if condition satisfies this wil execute

i++; // increment in i

} // end of for loop’s def.

} // end of main

} // end of class

Page 122: Manual of JAVA (more than Half)

122

Output:

Discussion:In this program a class of name ForVar is declared then its definition starts. Its definition

is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. it shows another representation of for loop

Program 52:Write a program that demonstrates the use nested loops.

Solution:// Loops may be nested.

class Nested { // class with name Nested

public static void main(String args[]) { // mainmethod of class

int i, j; // variables declaration

Page 123: Manual of JAVA (more than Half)

123

for(i=0; i<10; i++) { // outer for loop

for(j=i; j<10; j++) // inner for loop

System.out.print("."); // prints what is in it

System.out.println(); // prints nothing

} // end of for loop

} // end of main method

} // end of class

Output:

Discussion:In this program a class of name Nested is declared then its definition starts. Its definition

is enclosed between the opening and closing of curly braces {}. In it outer loop handles rows and inner handles columns

Page 124: Manual of JAVA (more than Half)

124

Program 53:Write a code using break to exit a loop.

Solution:// Using break to exit a loop.

class BreakLoop { // class with name BreakLoop

public static void main(String args[]) { // main method

for(int i=0; i<100; i++) { // for loop having 100 iterations

if(i == 10) break; // terminate loop if i is 10

System.out.println("i: " + i); // prints i

} // end of for

System.out.println("Loop complete."); // prints double quoted value

} // end of main

} // end of class

Output:

Page 125: Manual of JAVA (more than Half)

125

Discussion:In this program a class of name BreakLoop is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. It shows how to exit using break

Program 54:Write a program using break to exit a while loop.

Solution:// Using break to exit a while loop.

class BreakLoop2 { // class with name BreakLoop2

public static void main(String args[]) { // main method of class

int i = 0; // variable initialization

while(i < 100) { //while loop

if(i == 10) break; // terminate loop if i is 10

Page 126: Manual of JAVA (more than Half)

126

System.out.println("i: " + i); // prints i

i++; // increament operator

} // end of for loop

System.out.println("Loop complete."); // prints double quoted line

} // end of main

} // end of class

Output:

Discussion:In this program a class of name BreakLoop2 is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. It shows how to use break to exit a while loop

Page 127: Manual of JAVA (more than Half)

127

Program 55:Write a program with nested loops using break

Solution:// Using break with nested loops.

class BreakLoop3 { // class with name BreakLoop3

public static void main(String args[]) { // main method

for(int i=0; i<3; i++) { // for loop with 3 iterations

System.out.print("Pass " + i + ": "); // prints double quoted line

for(int j=0; j<100; j++) { // for loop with 100 iterations

if(j == 10) break; // terminate loop if j is 10

System.out.print(j + " "); // prints double quoted line

} // end of for loop

System.out.println(); // prints nothing

} // end of outer loop

System.out.println("Loops complete."); // prints double quoted line

} // end of main

} // end of class

Output:

Page 128: Manual of JAVA (more than Half)

128

Discussion:In this program a class of name BreakLoop3 is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. It shows how to use break as a civilized form of goto statement

Program 56:Write a program using break as a civilized form of goto.

Solution:// Using break as a civilized form of goto.

class Break { // class with name Break

public static void main(String args[]) { // main method of class

boolean t = true; // variable of type boolean

first: { // first label

second: { // second label

third: { // third label

Page 129: Manual of JAVA (more than Half)

129

System.out.println("Before the break."); // prints double quoted line

if(t) break second; // break out of second block

System.out.println("This won't execute");// prints double quoted line

} // end of third block

System.out.println("This won't execute"); // prints double quoted line

} // end of second block

System.out.println("This is after second block."); // // prints double quoted line

} // end of for

} // end of main

} // end of class

Output:

Page 130: Manual of JAVA (more than Half)

130

Discussion:In this program a class of name Break is declared then its definition starts. Its definition

is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. Using break as a civilized form of goto.

Program 57:Write a program using break to exit from nested loop.

Solution:// Using break to exit from nested loops

class BreakLoop4 { // class with name BreakLoop4

public static void main(String args[]) { // main method of class

outer: for(int i=0; i<3; i++) { // outer is a label and for loop having 3 iterations

System.out.print("Pass " + i + ": "); // prints value of i

for(int j=0; j<100; j++) { // for loop having 100 iterations

if(j == 10) break outer; // exit both loops

System.out.print(j + " "); // prints j

} // end of for

System.out.println("This will not print"); // prints double quoted line

} // end of outer loop

System.out.println("Loops complete."); //// prints double quoted line

} // end of main

} // end of class

Page 131: Manual of JAVA (more than Half)

131

Output:

Discussion:In this program a class of name BreakLoop3 is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. it shows how to use break to exit from nested loops

Program 58:Write a program that display the break error

Solution:// This program contains an error.

class BreakErr { // class with the name BreakErr

public static void main(String args[]) { // main method of the class having no return type and is public. It contains a string argument

one: for(int i=0; i<3; i++) {

// one is a label and for loop also execute here on 3 iterations of i

System.out.print("Pass " + i + ": ");

// prints the double quoted statement and the value of i

} // end of for loop

Page 132: Manual of JAVA (more than Half)

132

for(int j=0; j<100; j++) { // another for loop is initializes that initializes j to 100 and the causes an increment

if(j == 10) break one; // WRONG.. because function cannot execute and cannot o back to the label ine

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

// prints out the value of j

} // en dog f main method

} // end of main

} // end of class

Output:

Discussion:In this program a class of name BreakErr is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. it wil show an error

Program 59:Write a program that demonstrates the use of continue statement.

Page 133: Manual of JAVA (more than Half)

133

Solution:// Demonstrate continue.

class Continue { // class with name Continue

public static void main(String args[]) { // public main method having no return type and a string as an argument

for(int i=0; i<10; i++) { // for loop initializes i to zero and performs 10 iterations and incremented the value of i

System.out.print(i + " "); // print the value of i

if (i%2 == 0) continue; // if i modulus 2 is aqual to 0 then it will continue the remaining code until for loop completes its iterations

System.out.println(""); // print double quoted value

} // end of for

} // end of main

} // end of class

Output:

Page 134: Manual of JAVA (more than Half)

134

Discussion:In this program a class of name Continue is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. T demonstrate the working of continue statement if the given condition is satisfied then it will allow the control to continue.

Program 60:Write a program using continue with a lebel

Solution:// Using continue with a label.

class ContinueLabel { // class with a name ContinueLabel

public static void main(String args[]) { /* main method of class having no return type and it is static and public & also contains an argument args[] of type int */

outer: for (int i=0; i<10; i++) {

/* outer is a label. For loop’s execution starts from here in it i is initialized an this loop will continues until i < 10 then an increment operator is used */

for(int j=0; j<10; j++) {

/* For loop’s execution starts from here in it j is initialized an this loop will continues until j < 10 then an increment operator is used */

if(j > i) { // if statement is used if j > i then its body will execute

System.out.println(); // prints nothing

continue outer; // continue is used to go to the label outer written befor for loop

} // end of if

System.out.print(" " + (i * j)); // prints value of i*j

} // end of for loop

} // end of for loop

Page 135: Manual of JAVA (more than Half)

135

System.out.println(); // print snothing

} // end of main

} // end of class’s def.

Output:

Discussion:In this program a class of name ContinueLabel is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the opening and closing curly braces {}. It contains 2 loops 1 for rows and the other for columns. If j > i than it will goes to the outer loop using outer label and displays the value if, if loop is not true.

Program 61:Write a program that demonstrates the use of return.

Page 136: Manual of JAVA (more than Half)

136

Solution:// Demonstrate return.

class Return { // a class with a name Return

public static void main(String args[]) { // main method of class which is public and have no return type, also contains a string type argument

boolean t = true; // a variable t of type bolean is initialized to true

System.out.println("Before the return."); // displays the statement written in double quotes

if(t) return; // if t is true then it return to caller

System.out.println("This won't execute."); // displays the statement written in double quotes

} // end of main

} // end of class’s def.

Output:

Discussion:In this program a class of name Return is declared then its definition starts. Its

definition is enclosed between the opening and closing of curly braces {}. Then main method of no return type is declared. This method is static and public. Its definition is enclosed between the

Page 137: Manual of JAVA (more than Half)

137

opening and closing curly braces {}. It demonstrate the use of return i.e in this code if t is true then return , returns it to caller that is the above statement will execute.

Program 62:

Write a program of interface.

Solution://example of interface

import java.util.Random;

interface SharedConstants { //interface class

int NO = 0;

int YES = 1;

int MAYBE = 2;

int LATER = 3;

int SOON = 4;

int NEVER = 5;

}

class Question implements SharedConstants { //implementation of SharedConstants()

Random rand = new Random();

int ask() {

int prob = (int) (100 * rand.nextDouble());

if (prob < 30)

return NO; // 30%

else if (prob < 60)

Page 138: Manual of JAVA (more than Half)

138

return YES; // 30%

else if (prob < 75)

return LATER; // 15%

else if (prob < 98)

return SOON; // 13%

else

return NEVER; // 2%

}

}

class AskMe implements SharedConstants { //another implementation

static void answer(int result) {

switch(result) { //switch statements

case NO:

System.out.println("No"); // prints

break; // exit

case YES:

System.out.println("Yes");

break;

case MAYBE:

System.out.println("Maybe");

break;

case LATER:

System.out.println("Later");

break;

case SOON:

Page 139: Manual of JAVA (more than Half)

139

System.out.println("Soon");

break;

case NEVER:

System.out.println("Never");

break;

} // end of main

} // end of class

public static void main(String args[]) {

Question q = new Question(); //creating object

answer(q.ask());

answer(q.ask());

answer(q.ask());

answer(q.ask());

}

}

Output:

Page 140: Manual of JAVA (more than Half)

140

Description:This program makes use of one of java’s standard classes Random. this class provides

numbers. It contains several methods which allow you to obtain random numbers in the form required by your program. In this example, the method nextDouble( ) is used. In this sample program, the two classes, Question and AskMe, both implement the SharedConstants interface where NO, YES, MAYBE, SOON, LATER, and NEVER are defined. Inside each class, the code refers to these constants as if each class had defined or inherited them directly.

Program 63:

Write a program in which one interface can extend another.

Solution:interface A{

void meth1();

void meth2();

}

// B now includes meth1() and meth2() -- it adds meth3().

interface B extends A { //B extands A

void meth3(); //initialzing meth3()

}

// This class must implement all of A and B

class MyClass implements B {

public void meth1() {

System.out.println("Implement meth1().");

}

public void meth2() {

System.out.println("Implement meth2().");

Page 141: Manual of JAVA (more than Half)

141

}

public void meth3() {

System.out.println("Implement meth3().");

}

}

class IFExtend{ // class IFExtend

public static void main(String arg[]){

MyClass ob = new MyClass(); //creating object of MyClass

ob.meth1(); //invoking meth1

ob.meth2(); //invoking meth2

ob.meth3(); //invoking meth3

}

}

Output:

Page 142: Manual of JAVA (more than Half)

142

Description:IFExtend is the name of the class. It try to removing the implementation for meth1( ) in

MyClass. This will cause a compile-time error. As stated earlier, any class that implements an interface must implement all methods defined by that interface,including any that are inherited from other interfaces.

Program 64: Write a program that introduces the Exception at run time

Solution:class Exc1 {

static void subroutine() { // a static method

int d = 0;

int a = 10 / d;

// two variables of type in are initialize and declard

}

public static void main(String args[]) { // main method

Exc1.subroutine(); // calling method

} // end of main

} // end of class

Page 143: Manual of JAVA (more than Half)

143

Output:

Discussion:In this program the run time Exception occurs by introducing main in the class. It occurs

in the line 7 that is the call to method, which caused the exception at line 4

Program 65:Write a code that demonstrate the use of try catch

Solution:class Exc2 {

public static void main(String args[]) {

int d, a;

try { // monitor a block of code.

d = 0;

a = 42 / d;

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

}

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

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

Page 144: Manual of JAVA (more than Half)

144

}

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

}

}

Output:

Discussion:In this program the call to println( ) inside the try block is never executed. Once an

exception is thrown, program control transfers out of the try block into the catch block. Put differently,catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.

Program 66:Write a program that Handle an exception and move on.

Solution:// Handle an exception and move on.

import java.util.Random;

class HandleError {

Page 145: Manual of JAVA (more than Half)

145

public static void main(String args[]) {

int a=0, b=0, c=0;

Random r = new Random();

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

try {

b = r.nextInt();

c = r.nextInt();

a = 12345 / (b/c);

}

catch (ArithmeticException e) {

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

a = 0; // set a to zero and continue

}

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

}

}

}

Page 146: Manual of JAVA (more than Half)

146

Output:

Discussion:In this program If either division operation causes a divide-by-zero error, it is caught, the

value of a is set to zero, and the program continues.

Program 67:Write a program that demonstrate multiple catch statemnets

Solution:// Demonstrate multiple catch statements.

class MultiCatch {

public static void main(String args[]) {

try {

int a = args.length;

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

int b = 42 / a;

int c[] = { 1 };

Page 147: Manual of JAVA (more than Half)

147

c[42] = 99;

}

catch(ArithmeticException e) {

System.out.println("Divide by 0: " + e);

}

catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index oob: " + e);

}

System.out.println("After try/catch blocks.");

}

}

Output:

Discussion:This program produces a division-by-zero exception if it is started with no arguments,

since a will equal zero. It will survive the division if you provide an argument and set a to larger than zero value. But it will cause an ArrayIndexOutOfBoundsException

Page 148: Manual of JAVA (more than Half)

148

Program 68:Write a program that contains an error. A subclass must come before its

superclass in a series of catch statements. If not, unreachable code will be created and a compile-time error will result.

Solution:/* This program contains an error. A subclass must come before its superclass in a

series of catch statements. If not, unreachable code will be created and a compile-time error will result. */

Class SuperSubCatch { // class name SuperSubCatch

public static void main(String args[]) { // main method

try { // try block

int a = 0;

int b = 42 / a;

}

catch(Exception e) {

System.out.println("Generic Exception catch.");

}

/* This catch is never reached because

ArithmeticException is a subclass of Exception. */

catch(ArithmeticException e) { // ERROR - unreachable

System.out.println("This is never reached.");

}

}

}

Page 149: Manual of JAVA (more than Half)

149

Output:

Discussion:In this program ArithmeticException is a subclass of Exception, the first catch statement

will handle all Exception-based errors, including ArithmeticException. This means that the second catch statement will never execute.

Program 69: Write a program that demonstrate the nested try statements

Solution:// An example of nested try statements.

class NestTry {

public static void main(String args[]) {

try {

int a = args.length;

/* If no command-line args are present, the following statement will generate a divide-by-zero exception. */

int b = 42 / a;

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

try { // nested try block

Page 150: Manual of JAVA (more than Half)

150

/* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */

if(a==1) a = a/(a-a); // division by zero

/* If two command-line args are used,

then generate an out-of-bounds exception. */

if(a==2) {

int c[] = { 1 };

c[42] = 99; // generate an out-of-bounds exception

}

}

catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out-of-bounds: " + e);

}

}

catch(ArithmeticException e) {

System.out.println("Divide by 0: " + e);

}

}

}

Page 151: Manual of JAVA (more than Half)

151

Output:

Discussion:In this program one argument produces a divide-by-zero exception from within the nested

try block. Since the inner block does not catch this exception, it is passed on to the outer try block, where it is handled.

Program 70: Write a program in which Try statements can be implicitly nested via

calls to methods

Solution:// Try statements can be implicitly nested via calls to methods.

class MethNestTry {

static void nesttry(int a) {

try { // nested try block

/* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */

if(a==1) a = a/(a-a); // division by zero

/* If two command-line args are used, then generate an out-of-bounds exception. */

Page 152: Manual of JAVA (more than Half)

152

if(a==2) {

int c[] = { 1 };

c[42] = 99; // generate an out-of-bounds exception

}

}

catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out-of-bounds: " + e);

}

}

public static void main(String args[]) {

try {

int a = args.length;

/* If no command-line args are present, the following statement will generate a divide-by-zero exception. */

int b = 42 / a;

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

nesttry(a);

}

catch(ArithmeticException e) {

System.out.println("Divide by 0: " + e);

}

}

}

Page 153: Manual of JAVA (more than Half)

153

Output:

Discussion:In this program nested try are used in the method

Program 71:Write a program that demonstrate throw

Solution:// Demonstrate throw.

class ThrowDemo {

static void demoproc() {

try {

throw new NullPointerException("demo");

}

catch(NullPointerException e) {

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

throw e; // rethrow the exception

}

Page 154: Manual of JAVA (more than Half)

154

}

public static void main(String args[]) {

try {

demoproc();

}

catch(NullPointerException e) {

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

}

}

}

Output:

Discussion:In this program new is used to construct an instance of NullPointerException.

Page 155: Manual of JAVA (more than Half)

155

Program 72:Write a program contains an error and will not compile.

Solution:// This program contains an error and will not compile.

class ThrowsDemo {

static void throwOne() {

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

throw new IllegalAccessException("demo");

}

public static void main(String args[]) {

throwOne();

}

}

Output:

Page 156: Manual of JAVA (more than Half)

156

Discussion:This program contains an error because the throwOne() is not declared it must delacre

to throw illegalaccesexceptions. And try/ctach block are also not defined. It also be defined to catch the exceptions.

Program 73:Write a program that demonstrate the method / use of fianally

Solution:// Demonstrate finally.

class FinallyDemo {

// Through an exception out of the method.

static void procA() {

try {

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

throw new RuntimeException("demo");

}

finally {

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

}

}

// Return from within a try block.

static void procB() {

try {

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

return;

}

Page 157: Manual of JAVA (more than Half)

157

finally {

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

}

}

// Execute a try block normally.

static void procC() {

try {

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

}

finally {

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

}

}

public static void main(String args[]) {

try {

procA();

}

catch (Exception e) {

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

}

procB();

procC();

}

}

Page 158: Manual of JAVA (more than Half)

158

Output:

Discussion:In this program procA( ) prematurely breaks out of the try by throwing an exception.

The finally is executed. procB( )’s try statement is exited by a return statement. The finally is executed before procB( ) returns. In procC( ), the try statement executes normally, without error. However, the finally block is still executed

Program 74:Write a program that throws illegal exception and main contains try catch

blocks and handle that exception

Solution:// This is now correct.

class ThrowsDemo1 { // class a key word of showing that is a class and its name is ThrowsDemo1

static void throwOne() throws IllegalAccessException { //

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

throw new IllegalAccessException("demo");

}

Page 159: Manual of JAVA (more than Half)

159

public static void main(String args[]) {

try {

throwOne();

}

catch (IllegalAccessException e) {

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

}

}

}

Output:

Discussion:This program is the correct because its exception is handled by the try catch block coded in the

main method. Here the throwOne() method is declared which throws illegal exceptions and the main also defines the try/catch block that catches the exceptions.