SlideShare a Scribd company logo
Table of Contents
Chapter # 1 (The Genesis of Java)
Q# 1.

Write a java program which show hallow word app!

Chapter # 2 (An Overview Of Java)

4
4
4

Q# 2.

Write a java program to display a simple string.

Q# 3.

Write a simple java program to display a string and perform a simple multiplication. 5

Q# 4.

Write a program which demonstrate the if statement.:

5

Q# 5.

write a program to demonstrate the for loop.

6

Q# 6.

Write a program which contains block of code in ―for‖ loop definition.

7

Chapter # 3: (Data type, Variable and Arays)

4

8

Q# 7.

Write a program to compute distance light travel in 1000 days using long variables. 8

Q# 8.

Write a program that calculates the area of a circle, use data type of double.

9

Q# 9.

Write a program which demonstrate the char data type.

9

Q# 10.

Write a program in which char variables behave like integers.

10

Q# 11.

Write a program which demonstrate dynamic initialization.

11

Q# 12.

Write a program that demonstrates the Boolean type values.

11

Q# 13.

Write a program which show the effect of nested scopes.

12

Q# 14.

Write a program to demonstrates the lifetime of a variable.

13

Q# 15.

Write a program that convert one data type in to another data type

14

Q# 16.

Write a program that multiply and add different data type variable.

15

Chapter # 4 (Operator)

15

Q# 17.

Write a program which demonstrate the arithmetic operator

15

Q# 18.

Write a programme that demonstrate modulus operator

16

Q# 19.

Write a program in which various assignment operator is used.

17

Q# 20.

Write a program which shows the function of increment(++).

18

Q# 21.

Write a programme left shifting the byte value.

18

Q# 22.

Write a programme that demonstrate the Boolean logical operator

19

Q# 23.

Write a program which demonstrates the ? operator.

20

Chapter # 5 (Control Statement)

20

Q# 24.

Write a programme that demonstrate if-else statement

20

Q# 25.

Write a programme that show simple example of switch

21

Q# 26.

Write a programme that show in switch break statements are optional

22
JAVA & OOPS Manual
Q# 27.

Write a programme that show the season when any month is given to it.

23

Q# 28.

Write a programme that demonstrate the while loop

24

Q# 29.

Using while loop write a program which display midpoint of two numbers.

25

Q# 30.

Write a programme that demonstrate dowhile

26

Q# 31.

Write a program using do-while to process a menu selection.

26

Q# 32.

Write a programme that demonstrate loop control veriable inside the for

29

Q# 33.
loop.

Write a program in which for loop is used and find the prime number by using this
29

Q# 34.

Write program in which two variable used to control the iteration of for loop

30

Q# 35.
Write program in which two variable used to control the iteration of for loop using
for comma 31
Q# 36.
for loop.

Write a for loop program in which initialization and iteration is moved out of the
31

Q# 37.

Write a program of nested for loop.

31

Q# 38.

Write a program in using break to exit a loop.

32

Q# 39.

Write a program in which using a break to exit a while loop.

33

Q# 40.

Write a program in which using a break to exit a while loop.

34

Q# 41.

Write a program in which break is used like go to statement.

34

Q# 42.

Write a program that used for a labelled break statement to exit from nested loop.
35

Q# 43.

Write a program that uses continue to cause two number.

36

Q# 44.
Write a program that uses continue to print a triangular multiplication of table for 0
through 9. 36
Q# 45.

Write a program that demonstrates return.

Chapter # 6 (Introducing classes)

37
38

Q# 46.

Write a program that call this file BoxDemo.java.

38

Q# 47.

Write a program that declares two Box object.

38

Q# 48.

Write a program that includes a method inside the box class.

39

Q# 49.

Write a program that volume () returns the volumeof a box

40

Q# 50.

Write a program that use as parameterized method

41

Q# 51.

Write a program that use a constructor to initialize the dimension f a box.

42

Q# 52.

Write a program that uses a parameterized constructor to initialize the dimension.
43

Q# 53.

Write a program that defines an integer stack that can hold 10 values.

Chapter # 7 (A Closer Look at Methods and Classes)
Q# 54.
1|Page

Write a program that demonstrates method overloading.

44
46
46
JAVA & OOPS Manual
Q# 55.
Write a program that use overloaded method and convert a parameter into
corresponding data type when compatible type of constructor is not available.

47

Q# 56.

Write a program that shows the dimension of a box in various way.

48

Q# 57.

Write a program that

49

Q# 58.

Write a program that shows the overloading of constructors.

50

Q# 59.

Write a program that is passed by value.

52

Q# 60.

Write a program that is call by reference.

53

Q# 61.

Write a program that returning an object.

53

Q# 62.
Write a program that that use the concept of recursion and find the factorial of the
numbers. 54
Q# 63.

Write a program that shows recursion.

55

Q# 64.
Write a program that shows the working of access specifies. Like we can access
public methods and variables but not private one.
56
Q# 65.

Write a program that uses variable , method and blocks

Q# 66.

Write a program that inside main() the static method accessed outside of the class.
58

Q# 67.

Write a program that demonstrates an inner class with in for loop.

59

Q# 68.

Write a program that demonstrates Strings.

59

Q# 69.

Write a program that demonstrates some string method.

60

Q# 70.

Write a program that display all command line arguments

61

Q# 71.

Write a program that uses inheritance to extend Box

61

Q# 72.

Write a program that show Super keyword implementation of BoxWeight.

63

Q# 73.

Write a program in which BoxWeight extends to includinf shipping cost.

66

Q# 74.

Write a program that demonstrate when constructor are called.

69

Q# 75.

Write a program that show method overriding.

70

Q# 76.

Write a program that use Dynamic method dispatch.

71

Q# 77.

Write a program that use run time poly-morphisam.

72

Q# 78.

Write a program that use abstract method and classe.

73

Chapter # 10(Exception Handling)

57

75

Q# 79.

Write a program using exceptions in it

75

Q# 80.

Write a program showing multiple catch Clauses.

75

Q# 81.

Write a program that Handle an exception and move on.

76

Q# 82.

write a program of try statements

77

Q# 83.

Write a program that can be implicitly nested via calls to methods. */

78

Chapter#13 (String Handling)
2|Page

79
JAVA & OOPS Manual
Q# 84.

Write a program that use override toString () for Box.

79

Q# 85.

Write a program that demonstrate equals () and equalsIgnoreCase().

80

Q# 86.

Write a program that use == method to give answer.

81

Q# 87.

Write a program that use compareTo() to determine sort ordering for a bubble sort.
81

Q# 88.
string.

Write a program that show how to use various index method t search inside of
82

Q# 89.
Write a program that use substring() method to replace all instance of one substring
with another within string.
83
Q# 90.

Write a program that use trim() to process commands.

84

Q# 91.
Write a program that convert uppercase latter to lowercase and lowercase to
uppercase latters.

85

Q# 92.

Write a program that define StringBuffer length vs. capacity.

85

Q# 93.

Write a program that demonstrate append() method .

86

Q# 94.

Write a program that demonstrate insert() method.

87

Q# 95.

Write a program that demonstratereplace() method.

87

Q# 96.

Write a program that demonstrate IndexOfDemo () method.

87

Chater#09(Package and inter face)

88

Q# 97.

Write a program that that demonstrates package access.

Q# 98.

Write a program that demonstrates class of one package call in second package. 89

Q# 99.

Write a program that demonstrate importing package.

93

Q# 100.

Write a program that demonstrate fixed storage in interface.

94

Q# 101.

Write a program that demonstrate ?

95

Q# 102.

Write a program that ?

96

Q# 103.

Write a program that show interface can be extended.

98

Chapter#12 (I/O,APPLET, AND OTHER TOPIC)

88

100

Q# 104.

Write a program that read the Character.

100

Q# 105.

Write a program that read String.

100

Q# 106.

Write a program that create a tiny Text editor.

102

Q# 107.

Write a program that demonstrate System.out.write( ).

103

Q# 108.

Write a program that demonstrate PrintWriter Class.

104

Q# 109.

Write a program that demonstrate a text file.

106

Q# 110.

Write a program that demonstrate to copy a text file.

107

Q# 111.

Write a program that demonstrate on simple simple Applet method.

109

Q# 112.

Write a program that demonstrate instanceof () Operator.

110

3|Page
JAVA & OOPS Manual
Q# 113.

Write a program that that demonstrate how to use assert.?

Chapter#19(The Applet Classes)
Q# 114.

113
113

Write a program that demonstrates Applet Skelton.

113

Q# 115. Write a program that demonstrate foreground and background ground color of and
out put of String.
115
Q# 116.

Write a program that demonstrate simple Banner Applet.

116

Q# 117.

Write a program that demonstrate showStatus().

118

Q# 118.

Write a program that demonstrate passing parameter to Applet.

119

Q# 119.

Write a program that display code and document bases.

121

Q# 120.

Write a program that get code and display HTML file.

122

Chapter#20(Events Handling)

123

Q# 121.

Write a program that demonstrate mouse event handler.

123

Q# 122.

Write a program that demonstrate key event handler.

125

Q# 123.

Write a program that demonstrate an adapter in event handling.

126

Q# 124.

Write a program that show how to inner classes uses .?

127

Q# 125.

Write a program that demonstrate Anonymous inner class.

128

Chapter # 1 (The Genesis of Java)
Q# 1. Write a java program which show hallow word app!
public class HelloWorldApp { //this line declare a class name and class definition starts from
here
public static void main(String args[]) { // line where program main function starts
System.out.print(" Hello World! "); this line prints HelloWorldApp!
} at this lime program main funcation starts
} program where class end

Chapter # 2 (An Overview Of Java)
Q# 2. Write a java program to display a simple string.
class example { // This line declare a class name & the class definition is start from here .
public static void main(String a[]) {

// This line begins the main() method.

System.out.println(" this is a simple program."); //this print this string followed by newline.

4|Page
JAVA & OOPS Manual
}
}

// end of main program
//end of class

Description : This is a simple java program in which show a string (" this is a simple program.")

OUTPUT:

Q# 3. Write a simple java program to display a string and perform a simple
multiplication.
class Example_2{ // This line daclare a new class & the class defination is start.
public static void main(String a[]){ // This line begins the main() method.
int num; // this declares a variable called num.
num=100 ; // this assign num the value 100.
System.out.println("this is num: " + num);

// this line show output of num

//This line outputs the string and number.
num=num * 2;

// this line show value of num is equals to num multiply by 2

System.out.print("The value of num * 2 is ");
//This line outputs the string "The value of num * 2 is "
System.out.println(num);

// this is a output line which give the value of num

//This line output the value store in variable num followed by a new line.
}
}

// end of main prograam

// end of class

DESCRIPTION:In this program we Ist creat a class with name of example2, after this we initialize num
and give the value and show value of num in form of output,after this we declare ―num = num * 2‖And
than show thevalue of num after multiplying by 2.

OUTPUT:

Q# 4. Write a program which demonstrate the if statement.:
class IfSample{ // This line daclare a class of name ifSample

5|Page
JAVA & OOPS Manual
public static void main(String a[]){ // This line begins the main() method.
int x, y; // this declares a variable called num.
x=10; // this assign x the value 10.
y=20 ; // this assign y the value 20.
if(x<y)

// in this line we give if Statement that ifx is less than y than give
System.out.println("x is less than y"); // This line outputs the string.

x= x*2;

// multiply x by 2.

if(x==y) System.out.println("now x is equal to y");
show a string

// this is a output line which

x= x*2; //multiply again by 2
if(x>y) System.out.println("now x is greater than y");
show a string

// this is a output line which

} //end of main program
}

// end of a class

DESCRIPTION: This java program in which we ist make a class of name after making class we
initialize x and y and give them value , than we give if condition in which we say if value of x is less than
y than show ―x is less than y‖ , Now x multiply by 2 , Now we also give if condition x is equals to

OUTPUT:

Q# 5. write a program to demonstrate the for loop.
class ForTest{ // This line daclare a new class & the class defination is start.
public static void main(String a[]){ // This line begins the main() method.
int x; //daclare a integer x.
for(x=0; x<10; x=x+1) //for loop start
System.out.println("this is x: " + x);
} // end of main program
6|Page

// this line show value of x
JAVA & OOPS Manual
}

// end of a class

DESCRIPTION: In this line I ist initialize x and then give for loop and then show the output
line in which I show output line and after this our main program end.
OUTPUT:

Q# 6. Write a program which contains block of code in “for” loop definition.
class blocktest{

// this line declare class name

public static void main (String arg []){ // this is the main line were program main funcation
starts
int x,y;

// in this line x and y is declaer as as int variable *

y=20;

  in this line we give thie value of y *

for(x=0;x<20;x++) { this is a for loop that code run 20 time*
System.out.println("this is x: " + x);

this line give us value of x 20 time *

System.out.println("this is y :" + y); this line give us value of y 20 time *
y=y-2;}

this line show out put of y is given by this formula *

}

 this is the end of main

}

 this is the end of class

DESCRIPTION: in this we first declare a class as name blocktest, than we initialize x and y,
and than we give value of y; after this we initialize for loop and then it give out put line which
show x and y, and in program we declare value of y
OUTOUT:

7|Page
JAVA & OOPS Manual

Chapter # 3: (Data type, Variable and Arays)
Q# 7. Write a program to compute distance light travel in 1000 days using long
variables.
class Light{ // This line daclare a new class & the class defination is start.
public static void main(String a[]){
int lightspeed;

// This line begins the main() method.

//daclare a integer name lightspeed.

long days; //daclare a variable days of datatype long.
long seconds, distance;
lightspeed=186000; //aproximate speed of light n miles per second.
days=1000; //specify number of days.
seconds=days*24*60*60;

//convert to seconds.

distance=lightspeed * seconds; //compute distance
System.out.print("In " + days);
System.out.print(" days lightwill travel about ");
System.out.println(distance + " miles."); //print distance in miles.
}
}
DESCRIPTION: This program calculate the speed of light in 1000 days. We take long variable
to store the speed of light because inttype is not large enough to hold the desire value. The range
of a long is quite large. This makes it useful whrn big whole numbers are needed.
8|Page
JAVA & OOPS Manual

OUTPUT:

Q# 8. Write a program that calculates the area of a circle, use data type of double.
CODE:
class Area{

// This line daclare a new class & the class defination is start.

public static void main(String a[]){ // This line begins the main() method.
double pi, r, b;

// daclere three variable of type double.

r=12.3993;

//radius of circle.

pi=3.1416;

// value of pi

b=pi*r*r;

// Declare area formula.

System.out.println("Area of the circle is " + b); //This print the area of circle.
}
}
DESCRIPTION: In this program first declare a class name Area and show main program and
than I declare pi r and b and delare value of r and pi after we declare how area found after this in
system.out.println line it gives us the value of area
OUTPUT:

Q# 9. Write a program which demonstrate the char data type.
CODE:
class CharDemo{ // Declare class name as CharDemo.
public static void main(String a[]){ // This line begins the main() method.

9|Page
JAVA & OOPS Manual
char ch1, ch2; // daclere two character variable.
ch1=88;

//Declare value of ch1

ch2='Y'; //Declare ch2 is Y
System.out.print("ch1 and ch2: "); //print the string.
System.out.println(ch1 + " " + ch2); //display both character.
}
}
DESCRIPTION: In this program I take two character variable ch1assigned the value 88 which
is the ASCII (and UNICODE) value that corresponds to the letter X. At the end we display both
character value. The program displays the following output.
OUTPUT:

Q# 10.

Write a program in which char variables behave like integers.

CODE:
class CharDemo2{ // This line daclare a class name and a class start from here .
public static void main(String a[]){ // This line begins the main() method.
char ch1; // daclere a character variable.
ch1='X'; // give a charter to ch1
System.out.println("ch1 contains " + ch1);

//this line print ch1

ch1++; //increment ch1.
System.out.println("ch1 is now " + ch1); //print incremented character.
}
}

//end of main funcation
//end of class

DESCRIPTION:In this program I ist make a class of name Chardemo2. In second line main
funcation of programme start, after this I initiliaze and declare ch1,after this we print ch1 , then
increment in value of ch1 and print value of ch1
OUTPUT:

10 | P a g e
JAVA & OOPS Manual

Q# 11.

Write a program which demonstrate dynamic initialization.

class Square{ // This line daclare a class ‖Square‖& the class is start from here .
public static void main(String a[]){ // This line begins the main() method.
double x=3.0, y=4.0; // Initiallize two double variables.
double z=Math.sqrt(x*x + y*y); //z is initialized and declare calue of z
System.out.println("Hypotenuse is " + c);
}
}

//this line print value of Hypotenus

// end main funcation
end of class name

DESCRIPTION: This program computes the length of the hypotenuse of right triangle given
the length of two opposing sides.
OUTPUT:

Q# 12.

Write a program that demonstrates the Boolean type values.

CODE:
class BoolTest{ // This line daclare a new class & the class defination is start.
public static void main(String a[]){ // This line begins the main() method.
boolean b; // daclere a boolean variable.
b=false; //Initialize b is false.
System.out.println("b is " + b); // display b .
b=true; //now b initialize is true.
11 | P a g e
JAVA & OOPS Manual
System.out.println("b is " + b); // display it.
if(b)
System.out.println("this is executed. ");
// if condition is true then this string is print
b=false; // b again false.
if(b)

// initialize if condition

System.out.println("this is not executed. ");
//this line is not display because b is false.
System.out.println("10 > 9 is " + (10>9)); //out come relational operator Boolean which
is true
}

//end of main function

} // end of a class
DESCRIPTION: I
OUTPUT:

Q# 13.

Write a program which show the effect of nested scopes.

CODE:
class Scope{ // This line daclare a new class & the class defination is start.
public static void main(String a[]){ // This line begins the main() method.
int x; // initialize x
x=10; //Declare value of x.
if(x==10){ //start new scope
int y=20; //this y is known only to this block.
System.out.println("x and y : " + x + " " + y); // This line show the output
x=y*2; // this line show x equals to y*2
12 | P a g e
JAVA & OOPS Manual
} // this line show the finishing of block
//y=100; // error! y not known here.
System.out.println("x is " + x); this line show the output output
}

// this line show the end of program

} this line show the end of class
DESCRIPTION:This program shows the scope of any variable. As the comment indicate we Ist
declare the class and then initialize and delare
OUTPUT:

Q# 14.

Write a program to demonstrates the lifetime of a variable.

class LifeTime{ // This line daclare a class name
public static void main(String a[]){ // This line begins the main() method.
int x; // daclare a variable x.
for(x=0; x<3; x++){

//Declare for loop

int y=-1; //y is initialized each time block is entered.
System.out.println("y is: " + y); this is a output line
y=100; Give value to y
System.out.println("y is now: " + y); // this is the output line
} // end of loop function
}

// this line show the main program

}
DESCRIPTION:In this program we First declare declare a class name oLifetime than main
program start , I declare first x and and than declare for loop ; after this after this I initilaze y and
print value of y; after again give value to y and print again value of y
OUTPUT:

13 | P a g e
JAVA & OOPS Manual

Q# 15.

Write a program that convert one data type in to another data type

class Conversion {

// Declare class name

public static void main(String args[]){
of program start from here
int i = 257;
byte b;

//daclre main line line of program main body

//Initialize and Declare i
//initialize b

double d = 323.42;

//Initialize and Declare d

System.out.println("n Conversion of int tom byte.");
b = (byte) i;

// print string line

// convertion of data type

System.out.println(" i and b is "+ i + " " + b);

// print value of I and b

System.out.println( "n Conversion od double to int " ); //print string line
i = (int) d ; // convertion of data type
System.out.println("d and i " + i + " " + d ); // print value of I and d
System.out.println("n Conversion of double to byte");
b = (byte) d;

// print string line

// convert value of b in to byte

System.out.println("d and b " + d + " " + b); print value of b and d
} // end of main program
}

// end of class

Description:
In this program first make a class and write it main main method after intiliaze I, b, d. after we
conert one data type in to another data type and prind their value
Output:

14 | P a g e
JAVA & OOPS Manual
Q# 16.

Write a program that multiply and add different data type variable.

class Promote { // class name start from here
public static void main (String args [ ] ) { // Main body of program start from here
byte b = 42;

//Initialize and declare b

char c='a';

//Initialize and declare c

short s = 1024;//Initialize and declare s
int i = 50000; //Initialize and declare I
float f = .67f; //Initialize and declare f
double d = .1234;

//Initialize and declare d

double result = (f * b) + (i / c) + (d * s);

//Initialize and declare result

System.out.println((f * b) + " " + (i / c) + " "+ (d * s));
System.out.println("result = " + result);
}
}

// print line

// print result

// end of main programme
// end of a class

Description:
In this program I first make class and write its main method after this I declare and initialize b, c,
s, I, f, d. after this initialize result and give a value after we print our result
Output:

Chapter # 4 (Operator)
Q# 17.

Write a program which demonstrate the arithmetic operator

class BasicMath{ // This line daclare a new class & the class defination is start.
public static void main(String a[]){ // This line begins the main() method.
System.out.println("Integer Arithmetic"); //arthmetic using integers
int x=1+1; //store 2 in variable x
int b=x * 3; //x multiply a by 3 and store in b.
int c=b/4; //b divide b by 4 and store in c.
int d=c - x; // c minus x and store in d
int e=-d; // minus of d is
System.out.println("a = " + x); // print value of a
System.out.println("b = " + b); // print value of b
15 | P a g e
JAVA & OOPS Manual
System.out.println("c = " + c); // print value of c
System.out.println("d = " + d); // print value of d
System.out.println("e = " + e); // print value of e
System.out.println("nFloating Point Arithmetic"); // Arthmetic using doubles
double da=1+1; //store 2 in variable da
double db=da * 3; //multiply da by 3 and store in db.
double dc=db/4; //divide db by 4 and store in dc.
double dd=dc - da; // value of dc minus da store in dd
double de=-dd; // value of dd store in de
System.out.println("da = " + da); // print value of da
System.out.println("db = " + db); // print value of db
System.out.println("dc = " + dc); // print value of dc
System.out.println("dd = " + dd); // print value of dd
System.out.println("de = " + de); // print value of de
} // end of main method
}
// end of class
DESCRIPTION: in this programme first make a class and write its main method, after intilize
and declare a, b, c, d, e. and da, db, dc, dd, and print their value .
OUTPUT:

Q# 18.

Write a programme that demonstrate modulus operator

class modulas{

// class name

public static void main(String arg []){
int x=67;
double y=67.25;

//initialize and declare x
//initialize and declare y

System.out.println("x mod 10 = " + x%10 );
System.out.println("y mod 10 = " + y%10 );
} // end main method
16 | P a g e

// main method

//print modulus of x
//print modulus of y
JAVA & OOPS Manual
} end class
Description:in this programme first make a class and write its main method than initialize and
declare c and y and print them.
Output:

Q# 19.

Write a program in which various assignment operator is used.

//Demonstrate several assignment operator
class OpEquals{ // class name
public static void main(String a[]){ // This line begins the main() method.
int i=1; // declare i
int b=2; // Declare b
int c=3; // Declare 3
i+=5; // increment 5 in i.
b*=4; //multiply b by 4 than again store in b.
c+=i*b; //I multiply with b and add in c
c%=6; // modulus of c.
System.out.println("i = " + i);

// print value of i

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

// print value of b

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

// print value of c

}
}

end main method
// end the class

Description: in this programme first make a class and write its main method initialize and
declare a, b , c and again declare a, b, c and print their value
Output:

17 | P a g e
JAVA & OOPS Manual

Q# 20.

Write a program which shows the function of increment(++).

class InDec{
// Class name and class start from here.
public static void main(String a[]){
// main method of program line.
int a=1;
// Initialize1 in variable a.
int b=2;
// Initialize 2 in variable b.
int c, d;
// daclare two variables c & d.
c=++b;
// increment in b than store in c.
d=a++;
// store value of a in d. than increment in i.
System.out.println("a = " + i);
//this print the value i.
System.out.println("b = " + b);
//this print the value b.
System.out.println("c = " + c);
//this print the value c.
System.out.println("d = " + d);
//this print the value d.
}
}
DESCRIPTION: In this program two variable initialized and other two variables are initialized
by increment in values of pervious two variables.
OUTPUT:

Q# 21.

Write a programme left shifting the byte value.

class ByteShift {

// class name

public static void main (String args [ ] ) {
from here
byte a = 64, b;
int i;

//Declare a
// declare i

i = a<<2;
b = (byte) (a << 2);
18 | P a g e

//Decare i is lessthan 2
// convert data type

// main body of programme start
JAVA & OOPS Manual
System.out.println("orignal value of a: " +a); //print value of a
System.out.println("i and b:" + i + " " + b);
}

// print value of i and b

// main of main programme

} //end of class
Description:
Output:

Q# 22.

Write a programme that demonstrate the Boolean logical operator

class BoolLogic { // calss name
public static void main (String args[]) { // main method of programme
boolean a=true;

// Declare a

boolean b=false;

//Declare b

boolean c=a | b;

//Declare c

boolean d=a & b;

//Declare d

boolean e=a ^ b;

//Declare e

boolean f=(!a & b) | (a & !b);
boolean g= !a;

//Declare f
//Declare g

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

//Print value of a

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

//Print value of b

System.out.println(" a|b = " + c);

//Print value of c

System.out.println(" a&b = " + d);

//Print value of d

System.out.println(" a^b = " + e);

//Print value of e

System.out.println(" (!a & b) | (a & !b) = " + f);
System.out.println(" !a = " + g);
}
}

//Print value of g

//main body of programme ended
// class ended

Description:
Output:

19 | P a g e

//Print value of f
JAVA & OOPS Manual

Q# 23.

Write a program which demonstrates the ? operator.

class Ternary{ // Declare class name
public static void main(String a[]){ // Main body of programme start from here.
int i, k; // daclare two variables i & k.
i=10; // Initialize i
k= i<0 ? -i : i; //get absolute value of i.
System.out.print("Absolute value of "); // print string line
System.out.println(i +" is "+ k); //this print the value of i and k.
i=-10; // Initialize
k= i<0 ? -i: i; // get absolute value of i.
System.out.print("Absolute value of "); // print string line
System.out.println(i +" is "+ k); //this show the value of i and k.
}

// Main body of programme ended

}

// class ended

DESCRIPTION:This program shows the functionality of ? operator. In this programme ist
declare two variable and initialize them than print their value after this again initialize both
variable and print their value.
OUTPUT:

Chapter # 5 (Control Statement)
Q# 24.

Write a programme that demonstrate if-else statement

class IfElse{ // This line daclare a new class & the class defination is start.
public static void main(String a[]){ // This line begins the main() method.
20 | P a g e
JAVA & OOPS Manual
int month=4; //April
String season; //daclare a string name season.
if(month==12 || month==1 || month==2)
season= "winter";

//if above condition is true than print winter.

else if(month==3 || month==4 || month==5)
season= "Spring";

//if above condition is true than print Spring.

else if(month==6 || month==7 || month==8)
season= "Summer";

//if above condition is true than print Summer.

else if(month==9 || month==10 || month==11)
season= "Auntumn"; //if above condition is true than print Auntumn.
else
season="Bogus Month"; //
System.out.println("April is in the " + season + ".");
// this print the season of month.
}
}

// end of main programme

// end of class

DESCRIPTION: This java program demonstrates if-else-if statements. The if statements are
executed from the top down. In above if one of the condition is true the statement associated with
that if is executed and rest of the ladder is bypassed. If none of the condition is true then final
else statements is executed.
OUTPUT:

Q# 25.

Write a programme that show simple example of switch

class SwitchSample{ // class definition start from here.
public static void main(String a[]){ // Main body of programme start from here
for(int i=0; i<6; i++) // for loop start.
switch(i) { //start body of switch statment
case 0: //if i=0 than this case is executed.
System.out.println("i is zero.");
21 | P a g e
JAVA & OOPS Manual
break; // this stop the execution and end the program
case 1: //if i=1 than this case is executed.
System.out.println("i is one.");
break;

// this stop the execution and end the program

case 2: //if i=2 than this case is executed.
System.out.println("i is two.");
break;
case 3:

// this stop the execution and end the program

//if i=3 than this case is executed.
System.out.println("i is three.");
break;

default:

// this stop the execution and end the program.

//if i is greater than t than default statment executed.

System.out.println("i is greater than 3.");
}
}
}
DESCRIPTION: This java program demonstrates the switch statement. In above program as
you can see each time through the loop the statements associated with the case constant that
matches i are executed. All others are bypassed. After i is greater than 3 no case statements
match so the default statement is executed.
OUTPUT:

Q# 26.

Write a programme that show in switch break statements are optional

class MissingBreak{ // class name .
public static void main(String a[]){ // Main body of programme start from here.
for(int i=0; i<8; i++) // for loop start.
switch(i){

//start body of switch statment

case 0:
case 1:
case 2:
22 | P a g e
JAVA & OOPS Manual
System.out.println("i is less than 3");
break;

// print the string

// this line break the loop

case 3:
case 4:
System.out.println("i is less than 5");
break;
default:

// this line break the loop
//if no condition is true then this is executed.

System.out.println("i is 6 or more");
}
}
}

// print the string

// print the string

// for loop ended
// main body of programme ended

// class ended

Description: In this program we see that if break statements are not used then the program will
not stop and it print the statements following by true case. In above case 0,1 and 2 a single
statement is executed 3 then break statement is executed and control is bypassed. At the end if no
condition is true then the default statement is executed.
Output:

Q# 27.
it.

Write a programme that show the season when any month is given to

class Switch {

// class name declare

public static void main(String args[]) { // public main method declared
int month = 4;

// variable (month) is declared of int type, value is 4

String season;

// another variable (season) is declared

switch (month) {

//body of switch satement start

case 12:
case 1:
case 2:
season = "Winter";
break;
23 | P a g e

// break statement use to jump from the switch
JAVA & OOPS Manual
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}

//end of switch statement

System.out.println("April is in the " + season + "."); // here show the final output of
program
}
}

//main body of programme ended
// class ended

Description:In this programme first declare a class name than write its main method than
declare month and season after this declare switch statement and then write the cases .after this
print the season of April.
Output:

Q# 28.

Write a programme that demonstrate the while loop

//Demonstrate the while loop
24 | P a g e
JAVA & OOPS Manual
class While {

// Declare class name

public static void main (String args [ ] ) { // main body of class start from here
int n = 10;

// declare n

while(n > 0) {

// start while loop

System.out.println(―tick‖ + n) ;
n--;
}
}
}

//print value of n

// Decrement n
// loop body ended

// main body ended
//class ended

Description:
In this programme first make class and then main body of programme start and then declare
while loop after this print the value of n after decrement the n.
Output:

Q# 29.
Using while loop write a program which display midpoint of two
numbers.
class NoBody {

// class name is declared as Nobody

public static void main(String args[]) { // public main method declared
int i, j;

// two variables i & j are declared

i = 100; j = 200;

// intialize i and j.

// find midpoint between i and j
while(++i < --j) ; // Declare while loop
System.out.println("Midpoint is " + i); // show output
}
}

// main body of programme start from here
// class ended

Description:

25 | P a g e
JAVA & OOPS Manual
In this programme first declare a class name as NoBody then main body of programme start than
declare I and j after this giv value to I and j and declare while loop after this print value of I.
Output:

Q# 30.

Write a programme that demonstrate dowhile

class DoWhile {

// Class name is as DoWhile

public static void main(String args[]) { // public main method is start.
int n = 10;

// variable (n) is declared of int type, value is 10.

do {

// do whilel loop is started here.
System.out.println("tick " + n);
n--;

// print value of n

// decrement in n.

}
while(n > 0); // this loop is stop when n is equal to or less than zero.
} // main body programme ended
}

//class ended

Description:
In this programme first make a class and then write its main method after this declare n equals to
ten than apply do and print line after write while condition , In this programme do while loop is
used .

Q# 31.

Write a program using do-while to process a menu selection.

class Menu {
public static void main(String args[])
throws java.io.IOException {
input errors
char choice;
do {
26 | P a g e

// This line is used for for handling exception and

//Declare char as a choice
//
JAVA & OOPS Manual
System.out.println("Help on:");

// print Help on:

System.out.println(" 1. if"); // print 1.if
System.out.println(" 2. switch"); // print 2.Switch
System.out.println(" 3. while");

//print 3.While

System.out.println(" 4. do-while"); // print 4. DO while
System.out.println(" 5. forn");

//print 5 for n

System.out.println("Choose one:"); // print choose one
choice = (char)
System.in.read();

// char are read from this method

} while( choice < '1' || choice > '5');

// Apply while loop

System.out.println("n");
switch(choice) {

// Switch statement start

case '1': // this is condition one
System.out.println("The if:n");

// print the if:n

System.out.println("if(condition) statement;"); // print if condition
statement
System.out.println("else statement;"); //print else statement
break; // This line break the switch statement
case '2':

//This is condition 2

System.out.println("The switch:n"); // print the switch
System.out.println("switch(expression) {");

// print switch

System.out.println(" case constant:");

// print case constant

expression

System.out.println(" statement sequence"); // print statement sequence
System.out.println(" break;");
System.out.println(" //

// print break

..."); // print dotted line

System.out.println("}"); print ending braes
break; // This line break the switch statement
case '3':

// This is condition three

System.out.println("The while:n");

//print the while

System.out.println("while(condition) statement;"); // print while
condition statement
27 | P a g e
JAVA & OOPS Manual
Break;

//This line break the switch statement

case '4': // this is condition four
System.out.println("The do-while:n"); // this print the which in inverted
commas
System.out.println("do {"); // this print the which in inverted commas

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

// this will print Staement

System.out.println("} while (condition);");

// this line print} while

(condition);
break; // this ill break the switch statement
case '5': // this is choice 5
System.out.println("The for:n"); //print the for
System.out.print("for(init; condition; iteration)"); print for(init;
condition; iteration)
System.out.println(" statement;"); break; // print Statement
}
}
}

// switch statement ended
// main body of programme ended

// class ended

DESCRIPTION: In this program we first make a class and then write main body of programme
in which we print some condition than call System.in.read()ask input from user at run time after
this we give detail of our choice which is given by user.
Output:

28 | P a g e
JAVA & OOPS Manual
Q# 32.
for

Write a programme that demonstrate loop control veriable inside the

class ForTick {

// class start from here

public static void main (String args [] ) {

// main body of programme

// here n is declared inside the loop
For(inr n =10; n>0;n--)

{ // Define for loop

System.out.println(―tick ‖ + n);
}
}
}

// this brace show end of loop body
// this brace show end of main body of programme
// this brace show end of class

Description: In this programme first make a class and then start main body of programme than
declare for loop and print out put

Q# 33.
Write a program in which for loop is used and find the prime number
by using this loop.
class FindPrime { //class name start .
public static void main(String args[]) { // This line begins the main() method.
int num; //daclare a variable of type int.
boolean isPrime = true; //initialize a boolean variable.
num = 30; // give value to num
for(int i=2; i <= num/2; i++) { //for loop body is started.
if((num % i) == 0) { //this find prime number.
isPrime = false; // declare isPrime is equals to false
break;

// if condition stop

} // if condition ended
} loopbody ended
if(isPrime)
29 | P a g e
JAVA & OOPS Manual
System.out.println("Prime");

// print prime

else //else is uses
System.out.println("Not Prime"); // print Not Prime
}
}

// main body of programme ended
// this brace show end of class

DESCRIPTION: In this program for loop is used. Take an integer 30 and take modulus with 2
if it is equal to zero it is prime otherwise it display not prime. As we know 30 is not aprime
number it display not prime. It display the following output.
Output:

Q# 34.
Write program in which two variable used to control the iteration of
for loop
class Sample {
// class name start
public static void main(String args[]) { // This line begins the main() method.
Int x, y; //declare two integer variables.
Y = 4;
// give value to 4
for(x=1; x<y; x++) {
// for initialize declare
System.out.println(―x = ― + x); //this print the value of x.
System.out.println(―y = ― + y); //this print the value of y.
y--;
// Decrement y
}
// for loop ended
}
//main body of programme ended
}
// class ended
DESCRIPTION: In this program make class than start main method after this x and y after this
for loop is started and then print the value of x and y and decrement y.
Output:

30 | P a g e
JAVA & OOPS Manual
Q# 35.
Write program in which two variable used to control the iteration of
for loop using for comma
class comma {

// class body start from here

public static void main (String args []) {
Int a , b;

// main body of programme start from here

// Declare a aand b

For(a=1, b=4; a<b; a++, b--) {

// use for loop

System.out.println(―a= ‖ = + a) ;

// print value of a

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

// print value of b

}
}
}

loop body ended
main body ended

class ended

Description: In this programme first declare a class than write main method and initiliaze a and
b and declare for loop after this print value
Output:

Q# 36.
Write a for loop program in which initialization and iteration is moved
out of the for loop.
class ForVar{ // class name start from here
public static void main(String args[]) { // This line begins the main() method.
int n;
// declare n
boolean done= false; //initialize a boolean variable.
n=0;
// put n equals to zero
for(; !done;){ ///this is infinte loop .no condition & iteration
System.out.println("n is " + n);
// print value of n
if(n==5) done=true;
// declare if statement
n++; //if above condition is true than increment in n.
}
// end of loop
}
// end of main body
}
// end of class
DESCRIPTION: In this program the for loop is empty e.g no condition and iteration.

Q# 37.

Write a program of nested for loop.

class Nested { // This line daclare a class name
public static void main(String args[]) { // This line begins the main() method.
31 | P a g e
JAVA & OOPS Manual
int i, j; //daclare two integer variable.
for(i=0; i<10; i++) { //first loop
for(j=i; j<10; j++) //2nd loop
System.out.print(".");
// this line print dotted line
System.out.println();
}
// loop body ended
}
// main body of program ended
}
// class ended
DESCRIPTION: This is the program in which nested for loop is used.
Output:

Q# 38.

Write a program in using break to exit a loop.

class BreakLoop { // This line daclare a new class & the class defination is start.
public static void main(String args[]) { // This line begins the main() method.
for(int i=0; i<100; i++) { //loop body start.
if(i == 10) break; // terminate loop if i is 5
System.out.println("i: " + i); ///print value of i.
}
System.out.println("Loop complete."); //Print this string.
}
}
DESCRIPTION: In this program for loop is designed to run from 0 to 99 the break statement
causesit to terminates when i equals 10.
Output:

32 | P a g e
JAVA & OOPS Manual

Q# 39.

Write a program in which using a break to exit a while loop.

class BreakLoop2 {

// This line daclare class name

public static void main(String args[]) { // This line begins the main() method.
int i = 0;

// declare I =0

while(i < 100) { //while loop body start.
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i); //print value of i.
i++;
}
System.out.println("Loop complete.");
}
}
DESCRIPTION: the break statement can be used in any of java’loop. In above while loop is
used and loop is designed to run from 0 to 99, the break statement causes it to terminates early
when i equal 10.
OUTPUT:

33 | P a g e
JAVA & OOPS Manual
Q# 40.

Write a program in which using a break to exit a while loop.

class BreakLoop3 { // This line daclare a new class & the class defination is start.
public static void main(String args[]) { // This line begins the main() method.
for(int i=0; i<3; i++) { //first for loop start.
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) { //2nd loop start.
if(j == 10) break; // terminate loop if j is 10
System.out.print(j + " "); //print value of j.
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
DESCRIPTION: In this program first loop run 3 times and internal loop is designed to run 0 to
99 but it stop due to break statement when j equals 10. This program shows the following output.
OUTPUT:

Q# 41.

Write a program in which break is used like go to statement.

class Break { // This line daclare a new class & the class defination is start.
public static void main(String args[]) { // This line begins the main() method.
boolean t = true; //initialize a boolean variable.
first: { //body of first block start
second: { //body of 2nd block start
third: { //body of third block start
System.out.println("Before the break.");
34 | P a g e
JAVA & OOPS Manual
if(t) break second;

//break out of second block.

System.out.println("This won't be execute.");
}
System.out.println("This won't be execute.");
}
System.out.println("This is after second block.");
}
}
}
DESCRIPTION: This is the program in which break statement work like a goto. In this
statement of third block print after this second block is break and statement of first block is
executed.
OUTPUT:

Q# 42.
Write a program that used for a labelled break statement to exit from
nested loop.
class BreakLoop4 {

// class definition starts

public static void main (String args []) {
outer: for(int i = 0; i<3 ; i++)

{

// main body of program start from here
// for loop declared

System.out.print("Pass" + i + ": ");

// print value of

for(int j=0; j<100;j++)

{

if (j == 10)
break outer;

// declared if condition j equals to 10
// exit both loops

System.out.print(j + " "); // print j
} //second loop body ended
System.out.println("This will not print");
35 | P a g e

// Again for loop declared
JAVA & OOPS Manual
} // first loop body ended
System.out.println("Loops Complete."); // print loop completed
}
}

// main body ended

// class ended

Q# 43.

Write a program that uses continue to cause two number.

class Continue {

// clss defination start

public static void main (String args [ ] ) {
for (int i = 0; i < 10; i++ ) {

// main body of program start

// for loop started

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

// print value of i

if(i%2 == 0) continue;

// print modulas of 2

System.out.println(" ");

// print nothing

}
}
}

//loop body ended
// main body of program ended

// class ended

Description:
In this program first make a class than make main method than initialize for loop than print I
after get modulas and print
Output:

Q# 44.

Write a program that uses continue to print a triangular
multiplication of table for 0 through 9.

class ContinueLable {

// class definition start

public static void main (String args [] ) {
outer: for(int i=o; i<10; i++)
for(int j=0; j<10; j++)
if (j > i) {

//main body of program start from here

{ for loop declare
{

again for loop declare

// if j is greater than i

System.out.println();
continue outer;
}
36 | P a g e

// print nothing
// print

// if condition finished
JAVA & OOPS Manual
System.out.print(" " + (i * j));
}
}

// print value of i*j

// first for loop declared

// second for declared
System.out.println();

} // main body of program ended
}

// class ended

Description:
In this program
Output:

Q# 45.

Write a program that demonstrates return.

class Return {

// class name declared

public static void main (String args []) {
boolean t = true;

t declared as a boolean type

System.out.println("Before the return. ");
if(t) return;

// main body of program start
// print before the return

// return to caller

System.out.println("This Won't execute. "); // print this won’t execute
}
}

// main body of program ended

class ended

Description:
In this program first make a class name than write main method after declare t as Boolean type
after this print string after this if condition apply after print this won’t execute.
Output:

37 | P a g e
JAVA & OOPS Manual
Chapter # 6 (Introducing classes)
Q# 46.

Write a program that call this file BoxDemo.java.

class Box {
double width;
double height ;
double depth;
}
class BoxDemo{
public static void main (String args [ ] ){
Box mybox=new Box ();
double vol;
mybox.width=10;
mybox.height=15;
mybox.depth=18;
vol=mybox.width*mybox.height*mybox.depth;
System.out.println("Volume of Box is " + vol );
}
}
Description: In this program
Output:

Q# 47.

Write a program that declares two Box object.

class Box {
double width;
double height;
double depth ;
}
class BoxDemo2{
public static void main (String args [] ) {
38 | P a g e
JAVA & OOPS Manual
Box mybox = new Box ();
Box mybox2 =new Box ();
double vol;
mybox.width=10;
mybox.height=20;
mybox.depth=15;
mybox2.width=10;
mybox2.height=15;
mybox2.depth=18;
vol=mybox.width*mybox.height*mybox.depth;
System.out.println(" Volume of Box is " + vol );
vol=mybox2.width*mybox2.height*mybox2.depth;
System.out.println(" Volume of Box is " + vol );
}
}
Description:
Output:

Q# 48.

Write a program that includes a method inside the box class.

class Box {

//declare class name

double width;

// initialize width

double height;

// initialize height

double depth;

// initialize depth

void volume ( ) {

// declared volume method

System.out.println("Volume of Box is :");

//print string

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

print volume

}

// end of volume method

}

// end of class

class BoxDemo3{

// declare class name

public static void main (String args [ ]) {
Box mybox=new Box ();
39 | P a g e

// main body of program start

// declare a memory of for new box mybox
JAVA & OOPS Manual
Box mybox2=new Box ();

// declare a memory of for new box mybox

//assign value to mybox’s instance variable
mybox.width=15;

// give value of heightof second box

mybox.height=18;

// give value of heightof second box

mybox.depth=23;

//give value of depthof second box

//assign different value to mybox2’s instance variable
mybox2.width=10;

// give value of width of second box

mybox2.height=13;

// give value of heightof second box

mybox2.depth=15;

//give value of depthof second box

mybox.volume();

//display the volume of first box

mybox2.volume();

//display the volume of Second box

}
}
Description:
Output:

Q# 49.

Write a program that volume () returns the volumeof a box

class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
}
class BoxDemo4{
public static void main (String args [ ]) {
Box mybox1=new Box ();
Box mybox2=new Box ();
double vol;
40 | P a g e
JAVA & OOPS Manual
mybox1.width=15;
mybox1.height=18;
mybox1.depth=23;
mybox2.width=10;
mybox2.height=13;
mybox2.depth=15;
vol=mybox1.volume();

// declare vol

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

// print volume of myBox1

// declare vol

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

// print volume

// ending brace of main body

}

// ending brace of main class

Description:
In this program first make a super a class class and in which declare widthheight and depth after
this make a volume method after this make main class in which our main method is call after this
declare mybox1 and mybox2, after this declare vol after this assign values different values to
mybox1 and mybox2, after this print volume of box 1 and 2.
Output:

Q# 50.

Write a program that use as parameterized method

class Box {

// declare class name

double width;

// declare width

double height; // declare height
double depth;

// declare depth

double volume() {

// declare volume function

return width * height * depth;

// this line return value of volume

}
void setdim(double w, double h, double d ) {
width=w;
41 | P a g e

//declare width

// setdim method initialize
JAVA & OOPS Manual
height=h;

// declare h

depth=d;

// declare depth

}
}

// ending brace of stdim
// ending brace of class

class BoxDemo5{

//Declare class name

public static void main (String args [ ]) {

// main body of program

Box mybox1=new Box ();

// Declare myBox1

Box mybox2=new Box ();

// Declare mybox2

double vol;

// Declare vol

mybox1.setdim(10, 16, 19 );

// declare value of mybox1

mybox2.setdim(9, 10,15);

// declare value of mybox2

vol=mybox1.volume();

// Initialize vol

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

// Initialize vol

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

// print volume of mybox1
// print volume of mybox2

// ending brace of main body

}

// ending brace of class

Description:
Output:

Q# 51.
box.

Write a program that use a constructor to initialize the dimension f a

class Box {
double width;
double height;
double depth;
Box( ) {
System.out.println("costructing box is ");
width=17;
height=19;
depth=15;
42 | P a g e
JAVA & OOPS Manual
}
double volume() {
return width * height * depth;
}
}
class BoxDemo6{
public static void main (String args [ ] ){
Box mybox1=new Box();
Box mybox2=new Box();
double vol;
vol=mybox1.volume();
System.out.println("volume is " + vol);
vol=mybox2.volume();
System.out.println("volume is " + vol);
}
}
Description:
Output:

Q# 52.
Write a program that uses a parameterized constructor to initialize the
dimension.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d ) {
width=w;
height=h;
depth=d;
}
43 | P a g e
JAVA & OOPS Manual
double volume() {
return width * height * depth;
}
}
class BoxDemo7{
public static void main (String args [ ] ){
Box mybox1=new Box(17,19, 23);
Box mybox2=new Box(24, 27, 30);
double vol;
vol=mybox1.volume();
System.out.println("volume is " + vol);
vol=mybox2.volume();
System.out.println("volume is " + vol);
}
}
Description:
Output:

Q# 53.

Write a program that defines an integer stack that can hold 10 values.

class Stack {
int stack [] = new int [10];
int tos;
Stack ( ) { // Initialize top-of-stack
tos = -1;
}
void push (int item) {

// push an item on to stack

if (tos == 9)
System.out.println("Stack is full.");
else
44 | P a g e
JAVA & OOPS Manual
stack[++tos] = item;
}
int pop ( ) {

// pop an item from stack

if (tos < 0) {
System.out.println("Stack underflow");
return 0;
}
else
return stack[tos--];
}
}
class TestStack {
public static void main (String args [ ]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
for(int i =0 ; i < 10; i++)

mystack1.push(i);

// push some number on to

stack
for (int i = 10; i<20; i++)

mystack2.push(i);

// push some number on to stack

System.out.println("Stack my skack1 :");
for (int i = 0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack my skack2 :");
for (int i = 0; i<10; i++)
System.out.println(mystack2.pop());
}
}
Description:
In this program first make a class name as stack after this declare Stack and tos . after this I make
a constructor in which I initialize top-of-stack than make push method in which define if tos
equals to 9 than show shack is ful otherwise push another number. After this declare pop method
in which define if tos lessthan 0 than show stack underflow and ant return 0 otherwise decrease
number. After this make a main class and in main class declare two Object mystack1 and
mystack2 after this declare for loop than print output.
Output:
45 | P a g e
JAVA & OOPS Manual

Chapter # 7 (A Closer Look at Methods and Classes)
Q# 54.

Write a program that demonstrates method overloading.

class OverloadDemo{
void test() {

// declare class name
// declare test method

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

// print no parameter

// ending brace of test method

void test (int a ) {

// declare test method again

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

// print value of a

// ending brace of test method

void test (int a, int b) {

// declare test method again

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

// print value of a and b

// ending brace of test method

double test(double a) {

// declare test method again

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

// print value of a

// return value of a*a

// ending brace of test method

}

// ending brace of class

class Overload{

// declare class name

public static void main (String args [ ] ){
OverloadDemo ob = new OverloadDemo ();
46 | P a g e

// main method call
// declare new object as ob
JAVA & OOPS Manual
ob.test(); // class test method
ob.test(10);

// class test method

ob.test(10 , 20 );

// class test method

double result = ob.test(123.456);

// declare result

System.out.println ("Reslult of ob.test(123.456) is :" + result );
value of result
}
}

// print

// ending brace of main body
// ending brace of main class

Description:
In this program first declare class name than test name method define again and again . after this
make a main class and after this make a new object ob after this call method function with
object ob than initialize result after this print value of result.
Output:

Q# 55.
Write a program that use overloaded method and convert a parameter
into corresponding data type when compatible type of constructor is not
available.
class OverloadDemo{
void test() {
System.out.println("No parameters");
}
void test (int a, int b) {
System.out.println("a and b is " + a +" " + b);
}
void test(double a) {
System.out.println("Inside test (double) a : " + a);
}
}
class Overload2{
public static void main (String args [ ] ){
OverloadDemo ob = new OverloadDemo ();
int i = 88;
47 | P a g e
JAVA & OOPS Manual
ob.test();
ob.test(10, 20);
ob.test(i);
ob.test(123.456);
}
}
DESCRIPTION: In this program as you can see that this program is same as previous one. But
the difference is that we are calling a constructor which has one parameter of integer type but in
the constructor overloading we has no one like this. At this time java automatically converts data
type into most corresponding data type as here integer into double. Keep in mind that both have
same number of parameters.
OUTPUT:

Q# 56.

Write a program that shows the dimension of a box in various way.

class Box {
double width;
double height;
double depth;
Box(double w, double h, double d ) {
width=w;
height=h;
depth=d;
}
Box () {
width=-1;
height=-1;
depth=-1;
}
Box(double len) {
width=height=depth=len;
}
48 | P a g e
JAVA & OOPS Manual
double volume () {
return width*height*depth;
}
}
class OverloadCons {
public static void main (String args [ ] ) {
Box mybox1=new Box(17,19, 23);
Box mybox2=new Box();
Box mybox3=new Box();
double vol;
vol=mybox1.volume();
System.out.println("Volume of box1 is :" + vol);
vol=mybox2.volume();
System.out.println("Volume of box2 is :" + vol);
vol=mybox3.volume();
System.out.println("Volume of box3 is :" + vol);
}
}
Description:
Output:

Q# 57.

Write a program that

class Test{

// declare

int a, b;
Test(int i, int j ) {
a=i;
b=j;
}
boolean equals(Test o) {
if
49 | P a g e
JAVA & OOPS Manual
(o.a == a && o.b == b )
return true;
else
return false;
}
}
class PassOb {
public static void main (String args [ ] ) {
Test Ob1 = new Test( 100, 22 );
Test Ob2 = new Test( 100, 22 );
Test Ob3 = new Test( -1, -1);
System.out.println("ob1 == ob2 " + Ob1.equals(Ob2));
System.out.println("ob1 == ob3 " + Ob1.equals(Ob3));
}
}
Description:
Output:

Q# 58.

Write a program that shows the overloading of constructors.

class Box {

// declare class name

double width;

// declare width

double height;

// declare height

double depth;

// declare depth

Box(Box ob ) {

// make constructor

width=ob.width;
height=ob.height;
depth=ob.depth;
}

// ending brace of constructor

Box(double w, double h, double d ) {
width=w;
50 | P a g e
JAVA & OOPS Manual
height=h;
depth=d;
}
Box () {
width=-1;
height=-1;
depth=-1;
}
Box(double len) {
width=height=depth=len;
}
double volume () {
return width*height*depth;
}
}
class OverloadCons2 {
public static void main (String args [ ] ) {
Box mybox1=new Box(10,120, 15);
Box mybox2=new Box();
Box mycube=new Box(7);
Box myclone=new Box(mybox1);
double vol;
vol=mybox1.volume();
System.out.println("Volume of mybox1 is " + vol );
vol=mybox2.volume();
System.out.println("Volume of mybox2 is " + vol );
vol=mycube.volume();
System.out.println("Volume of mybox3 is " + vol );
vol=myclone.volume();
System.out.println("Volume of clone is " + vol );
}
}
51 | P a g e
JAVA & OOPS Manual
Description:
Output:

Q# 59.

Write a program that is passed by value.

class Test {
void meth (int i, int j ) {
i *=2;
j /=2;
}
}
class CallByValue {
public static void main (String args [ ] ) {
Test ob = new Test ( );
int a = 15;
int b = 20;
System.out.println("a and b before call :" + a + " " + b );
ob.meth(a, b);
System.out.println("a and b after call :" + a

+ " " + b );

}
}
Description:
In this program we settle a method in a class named as test and then perform some operations on
the variables in the method then call that method in the main function and display them using
System.out.println() method. We can see that when we call parameters by value our operations
will not perform on them. It just prints them as it is.
Output:

52 | P a g e
JAVA & OOPS Manual
Q# 60.

Write a program that is call by reference.

class Test {
int a, b;
Test (int i, int j ) {
a = i;
b = j;
}
void meth(Test o ) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main (String args [ ] ) {
Test ob = new Test (15, 20 );
System.out.println("a and b before call :" + ob.a

+ " " + ob.b );

ob.meth(ob);
System.out.println("a and b after call :" + ob.a

+ " " + ob.b );

}
}
Description:
: In this program we settle a method in a class named as test and then perform some operations
on the variables in the method then call that method in the main function and display them using
System.out.println() method. We can see that when we call parameters by reference our
operations will perform on them. It prints them after operating on them according to the
operators
Output:

Q# 61.

Write a program that returning an object.

class Test{
int a;
Test(int i) {
53 | P a g e
JAVA & OOPS Manual
a=i;
}
Test incByTen () {
Test temp = new Test (a+ 10 );
return temp;
}
}
class Retob{
public static void main (String args [ ] ) {
Test ob1 = new Test (2);
Test ob2;
ob2=ob1.incByTen();
System.out.println("ob1.a:" + ob1.a );
System.out.println("ob2.a:" + ob2.a );
ob2=ob2.incByTen();
System.out.println("ob2.a after Second increase :" + ob2.a );
}
}
DESCRIPTION: In this program we create a class and set a method in that class. In the method
we add 10 in the object as required from the statement. Then in the main function we create a
object of that class and then invoke that method and print them using System.out.println(). Then
for second increment we again invoke method that increments the object by 10.
OUTPUT:

Q# 62.
Write a program that that use the concept of recursion and find the
factorial of the numbers.
class Factorial{
int fact (int n ) {
int result;
if (n==1) return 1;
result = fact(n-1)*n;
54 | P a g e
JAVA & OOPS Manual
return result;
}
}
class Recursion{
public static void main (String args []) {
Factorial f= new Factorial ();
System.out.println("Factorial of 5 is " + f.fact(5));
System.out.println("Factorial of 7 is " + f.fact(7));
System.out.println("Factorial of 9 is " + f.fact(9));
}
}
DESCRIPTION: In this program we find the factorial of numbers. This is a recursive program
in which we create a function of name fact(). When it will call with an argument of 1, the
function returns 1, otherwise it will return the product of fact(n-1)*n . To evaluate this
expression fact () is called with (n-1) .This process repeats until n =1.
OUTPUT:

Q# 63.

Write a program that shows recursion.

CODE:
class Rectest{
int values[];
Rectest (int i){
values = new int[ i ];
}
//display array-- recursively
void printArray( int i){
if ( i == 0 ) return;
else

printArray(i - 1);

System.out.println(" [" + (i-1) + "] " + values [ i -1 ] );
}
55 | P a g e
JAVA & OOPS Manual
}
class Recursion2{
public static void main(String args[]){
Rectest ob = new Rectest(10);
int i;
for(i=0 ; i<10 ; i++)
ob.values[i] = i;
ob.printArray(10);
}
}
Description:
In this program first make a class after and intiliaze value after this make a constructor with
single value , after this make void print array method than make another class which is main
class in this class declare new object ob than initialize I after this declare for loop than call
printarray() function.
OUTPUT:

Q# 64.
Write a program that shows the working of access specifies. Like we
can access public methods and variables but not private one.
class test{
int a; //default access
public int b; //public access
private int c; //private access
void setc(int z){
c = z;
}
int getc(){
return c;
}
}
56 | P a g e
JAVA & OOPS Manual
class AccessTest{
public static void main(String args[]){
test ob = new test();
ob.a =10;

//correct

ob.b = 20;

//

//ob.c = 100;
ob.setc(100);

//this is not Ok(Error)
//

System.out.println("The values of a , b and c are : " + ob.a+" " + ob.b +" "+ ob.getc() );
}
}
DESCRIPTION:In this program we simply shows the working of access specifier. This
program shows that in java or any other language we can access public methods and public
variables from outside the class but we can’t access a private method or private variable form
outside the class. There is one type also called protected whose methods and variables can access
only by the child classes but not from outside the class.
OUTPUT:

Q# 65.

Write a program that uses variable , method and blocks

class UseStatic {
static int a=3;
static int b;
static void meth(int x)

{

System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("static block initialize. ");
b = a*4;
}
public static void main(String args []) {
57 | P a g e
JAVA & OOPS Manual
meth(42);
}
}
Description:
In this program first make a class than initialize static member a and b, after this make a method
name as static void meth in this function print value of x , a, and b , after this write main method
and call meth.
Output:

Q# 66.
Write a program that inside main() the static method accessed outside
of the class.
Class StaticDemo {
Static int a = 42;
Static int b = 99;
Static void callme( ) {
System.out.println(―a = ―+ a);
}
}
Class StaticByName {
Public static void main (String args []) {
StaticDemo.callme();
}
}
Description:
in this program first make a class after this make a class as name StaticDemo after this initialize
static data member, than print value of a , after this make a main class and print the value of b.
Output:

58 | P a g e
JAVA & OOPS Manual
Q# 67.

Write a program that demonstrates an inner class with in for loop.

class Outer {
int outer_x = 100;
void test () {
for (int i = 0; i<10; i++ ); {

// declare for loop

class Inner {
void display ( ) {
System.out.println("display : outer_x = " + outer_x); // prit value
outer_x
}
}
Inner inner = new Inner();
inner . display( );

// display method call

}
}
}
class InnerClassDemo {
public static void main (String args [ ]) {

// main body of program start from

here
Outer outer = new Outer ();
outer.test ();

// declare objrct

// call test method

}
}
Description:In this program first make class outer and initialize outer_x after this make method
test, and for loop declare after this make class inner than declare display method, and call with
inner object , than make main class and make new object outer and call test method.
Output:

Q# 68.

Write a program that demonstrates Strings.

class StringDemo {

//declare class

public static void main (String args []) {
59 | P a g e

// main body of program start
JAVA & OOPS Manual
String strOb1 = "First String ";

//Declare strOb1

String strOb2 = "Second String ";

//Declare strOb2

String strOb3 = strOb1 + " and " + strOb2;
System.out.println(" strOb1 ");

// print strOb1

System.out.println(" strOb2 ");

// print strOb2

System.out.println(" strOb3 ");

//Declare strOb3

// print strOb3

}
}
Description: this is a simple program in which first declare object then print them.
Output:

Q# 69.

Write a program that demonstrates some string method.

class StringDemo2 {
public static void main (String args []) {
String strOb1 = "First String ";
String strOb2 = "Second String ";
String strOb3 = strOb1;
System.out.println(" Length of strOb1 :" + strOb1.length());
System.out.println(" Char at index 3 in strOb1:" + strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2 ");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.print("strOb1 == strOb3 ");
else
System.out.println("strOb1 != strOb3");
}
}
60 | P a g e
JAVA & OOPS Manual
Description:
Output:

Q# 70.

Write a program that display all command line arguments

class CommandLine {

// class name declare

public static void main (String args [ ]) {

//main body of program start from

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

// declare for loop

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

// print arguments

}
}
Description:in this program first make a class than main method of body start from here than for
loop declare after this print value.
Output:

Q# 71.

Write a program that uses inheritance to extend Box

class Box{
double width;
double height;
double depth;
//Construct Clone Of An Object
Box(Box ob){
//Pass Object To Constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d){//Constructor Used When All Dimensions Specified
61 | P a g e
JAVA & OOPS Manual
width = w;
height = h;
depth = d;
}
Box(){//Constructor Used When No Dimensions Specified
width = -1;
height = -1;
depth = -1;
}
Box(double len){//Constructor Used When Cube Is Created
width = height = depth = len;
}
double volume(){

//Compute And Return Volume

return width * height * depth;
}
}
class BoxWeight extends Box{//Here, Box Is Extended To Include Weight.
double weight; //Weight Of Box
BoxWeight(double w, double h, double d, double m){
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight{
public static void main(String args[]){
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
62 | P a g e

//Constructor For BoxWeight
JAVA & OOPS Manual
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
Description:
Output:

Q# 72.
Write a program that show Super keyword implementation of
BoxWeight.
class Box{

//class name

private double width;

//declare width

private double height;

//declare height

private double depth;

//declare depth

Box(Box ob){
width = ob.width;

// define constructor
//give value to ob

height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d){
width = w;

//declare w

height = h;

//declare h

depth = d;
}
Box() {
width = -1;
height = -1;
depth = -1;
63 | P a g e

//declare d

//define Box constructor
JAVA & OOPS Manual

}
Box(double len) {

// again constructor define which define len

width = height = depth = len;
}
double volume() {

//volume funcation

return width * height * depth;

// return value of volume

}
}
class BoxWeight extends Box {
double weight;

//BoxWeight inherited from Box

//declare weight

BoxWeight(BoxWeight ob) {
super(ob);
weight = ob.weight;

//constructor define

//call super to ob
//initiliaze weight

}
BoxWeight(double w, double h, double d, double m) {
with 3 arguments

//define constructor

super(w, h, d);
weight = m;
}
BoxWeight() {
super();
weight = -1;
}
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);

64 | P a g e

//initialize myBox1
JAVA & OOPS Manual
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
myBox2

//initialize

BoxWeight mybox3 = new BoxWeight(); // by default
BoxWeight mycube = new BoxWeight(3, 2);

// initialize mycube

BoxWeight myclone = new BoxWeight(mybox1);

// declare my clone

double vol;
vol = mybox1.volume();

//declare vol

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

//print volume of myBox1

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

// print weight

System.out.println(); //print nothing
vol = mybox2.volume();

//declare vol

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

//print volume of myBox2

System.out.println("Weight of mybox2 is " + mybox2.weight);
of myBox
System.out.println();
vol = mybox3.volume();

// print weight

//print nothing
// declare vol

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

//print volume of mybox3

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

// print weigh

System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
Description:
In this program first a class name Box in this class I define weight, height, and depth, after this
make constructor with one argument ob and declare ob in it. After this make constructor with
65 | P a g e
JAVA & OOPS Manual
three arguments than define bydefault constructor. After this volume method define. Than make
another class which extends Box, in this class define new object weight , than make theor
constructor in BoxWeight() method super method call, after this main class define , and define
new object print their values which are define in above class .
Output:

Q# 73.
cost.

Write a program in which BoxWeight extends to includinf shipping

class Box {

// class na,e declare

private double width;

//declare width

private double height;

//declare height

private double depth;

//declare depth

Box(Box ob) { // make constructor
width = ob.width;

// pass object to constructor

height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d) {
dimensions specified

// constructor used when all

width = w;
height = h;
depth = d;
}
Box() {

// constructor used when no dimensions specified

width = -1;
height = -1;
depth = -1;
}
Box(double len) {
width = height = depth = len;
}
66 | P a g e

// constructor used when cube is created
JAVA & OOPS Manual
double volume() {

// compute and return volume

return width * height * depth;
}
}
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(BoxWeight ob) {
super(ob);

// construct clone of an object
// pass object to constructor

weight = ob.weight;
}
BoxWeight(double w, double h, double d, double m) {
parameters are specified
super(w, h, d);

// constructor when all

// call superclass constructor

weight = m;
}
BoxWeight() {

// default constructor

super();
weight = -1;
}
BoxWeight(double len, double m) {

// constructor used when cube is created

super(len);
weight = m;
}
}
class Shipment extends BoxWeight {

// Add shipping costs.

double cost;
Shipment(Shipment ob) {
super(ob);

// construct clone of an object

// pass object to constructor

cost = ob.cost;
}
Shipment(double w, double h, double d, double m, double c) {
when all parameters are specified
67 | P a g e

// constructor
JAVA & OOPS Manual
super(w, h, d, m);
cost = c;

// call superclass constructor

}
Shipment() {

// default constructor

super();
cost = -1;
}
Shipment(double len, double m, double c) {// constructor used when cube is created
super(len, m);

// call Super

cost = c;

//declare cost

}
}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 =new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 =new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();

//decare vol
// initiliaze volume

System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();

//decare vol
// initiliaze volume

System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
Description:
In this program first a class name Box in this class I define weight, height, and depth, after this
make constructor with one argument ob and declare ob in it. After this make constructor with
three arguments than define bydefault constructor. After this volume method define. Than make
68 | P a g e
JAVA & OOPS Manual
another class which extends Box, in this class define new object weight , than make another
constructor in BoxWeight() method super method call,after this make class Shipment which
extends Boxweightin this class cost shipment is defined in constructor of shipment class. after
this main class define , and define new object print their values which are define in above class
Output:

Q# 74.

Write a program that demonstrate when constructor are called.

class A {

//class name declare

A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {

// Create a subclass by extending class A.

B() {
System.out.println("Inside B's constructor.");
}
}
class C extends B {

// Create another subclass by extending B.

C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {

// class name definition

public static void main(String args[]) {

// main body of program start

C c = new C();
}
}
Description: In this program first define a class A and its constructor , after this make another
class B which is inherited from A, make the constructor and print value , after this make another
class c which is inherited from class B, than make main class and make new object cand print .
Output:
69 | P a g e
JAVA & OOPS Manual

Q# 75.

Write a program that show method overriding.

class A{
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {

// display i and j

System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {

// display k – this overrides show() in A

System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show();
}
}
Description:
70 | P a g e

// this calls show() in B
JAVA & OOPS Manual
Output:

Q# 76.

Write a program that use Dynamic method dispatch.

class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
void callme() {

// override callme()

System.out.println("Inside B's callme method");
}
}
class C extends A {
void callme() {

// override callme()

System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A();

// object of type A

B b = new B();

// object of type B

C c = new C();

// object of type C

A r;

// obtain a reference of type A

r = a;

// r refers to an A object

r.callme();
r = b;
r.callme();
r = c;
r.callme();
71 | P a g e

// calls A's version of callme
// r refers to a B object
// calls B's version of callme
// r refers to a C object
// calls C's version of callme
JAVA & OOPS Manual
}
}
Description:
Output;

Q# 77.

Write a program that use run time poly-morphisam.

class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
double area() {// override area for rectangle
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
double area() {
// override area for right triangle
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
72 | P a g e
JAVA & OOPS Manual
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
Description:
Through the dual mechanisms of inheritance and run-time polymorphism, it is possible to
define one consistent interface that is used by several different, yet related, types of objects. In
this case, if an object is derived from Figure, then its area can be obtained by calling area( ).
Output:

Q# 78.

Write a program that use abstract method and classe.

abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
73 | P a g e
JAVA & OOPS Manual
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
// this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
System.out.println("Area is " + figref.area());
}
}
Description:
As the comment inside main( ) indicates, it is no longer possible to declare objects of
type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To
prove this to yourself, try creating a subclass that does not override area( ). You will receive a
compile-time error
Output:

74 | P a g e
JAVA & OOPS Manual
Chapter # 10(Exception Handling)
Q# 79.

Write a program using exceptions in it

class Exc2{
public static void main(String args[]){
int d,a;
try{
d=0;
a=42/d;
System.out.println("This will not be printed");
}
catch(ArithmeticException e){
System.out.println("Division by zero");
}
System.out.println("After catch statement");
}
}
Description:
Notice that 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.
Output:

Q# 80.

Write a program showing multiple catch Clauses.

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};
c[42]=99;
}
catch(ArithmeticException e){
System.out.println("Divide by 0:"+e);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index oob: "+e);
75 | P a g e
JAVA & OOPS Manual
}
System.out.println("After try/catch blocks.");
}
}
Description:
This program will cause a division-by-zero exception if it is started with no command
line arguments, since a will equal zero. It will survive the division if you provide a command line
argument, setting a to something larger than zero. But it will cause an.
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program
attempts to assign a value to c[42].
Output:

Q# 81.

Write a program that Handle an exception and move on.

import java.util.Random;
class HandleError {
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);
}
}
}
Output:

76 | P a g e
JAVA & OOPS Manual

Q# 82.

write a program of 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
//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

77 | P a g e
JAVA & OOPS Manual
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Description:
As you can see, this program nests one try block within another. The program works as
follows. When you execute the program with no command-line arguments, a divide-by-zero
exception is generated by the outer try block. Execution of the program with one command-line
argument generates 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. If
you execute the program with two command-line arguments, an array boundary exception is
generated from within the inner try block. Here are sample runs that illustrate each case.
Output:

Q# 83.

Write a program that 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
if(a==2) {
int c[] = { 1 };
c[42] = 99;
}
}
78 | P a g e

// generate an out-of-bounds exception
JAVA & OOPS Manual
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);
}
}
}
Description:
As you can see, this program nests one try block within another. The program works as
follows. When you execute the program with no command-line arguments, a divide-by-zero
exception is generated by the outer try block. Execution of the program with one command-line
argument generates 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. If
you execute the program with two command-line arguments, an array boundary exception is
generated from within the inner
Output:

Chapter#13 (String Handling)
Q# 84.

Write a program that use override toString () for Box.

class Box {
double width;
double height;
double depth;
79 | P a g e
JAVA & OOPS Manual
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString () {
return "Dimension are " + width + " By " + depth + " By " + height + " . ";
}
}
class toStringDemo {
public static void main (String args []) {
Box b = new Box (10, 12, 14) ;
String s =( "Box b :" + b);

//Concatinate box object

System.out.println(b);

//Convert Box to String

System.out.println(s);

//print value of s.

}

//ending brace of main program

} //ending brace of class
Description:
In this program first make a class than write its main body after this declares s and print value of
b and s.
Output:

Q# 85.

Write a program that demonstrate equals () and equalsIgnoreCase().

//Demonstrate equals() and equalIgnoreCase().
public class EqualsDemo {
public static void main (String[] args) {
String s1 = "Hellow";

// Declare and initialize s1

String s2 = "Hellow";

// Declare and initialize s2

String s3 = "Good-By";

// Declare and initialize s3

String s4 = "HELLOW";

// Declare and initialize s4

80 | P a g e
JAVA & OOPS Manual
System.out.println(s1 + " equals " + s2 + "->" + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + "->" + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + "->" + s1.equals(s4));
System.out.println(s1 + " equals " + s2 + "->" + s1.equalsIgnoreCase(s2));
}
}
Description:
In this program first make class than write its main method after this initialize String s1 to s4
than print values by equals method.
Output:

Q# 86.

Write a program that use == method to give answer.

public class EqualsNotEqualsTo {
public static void main (String[] args) {
String s1 = "Helow";
String s2 = new String (s1);
System.out.println(s1 + " equals " + s2 + "->" + s1.equals(s2));
System.out.println(s1 + "==" + s2 + "->" + (s1==s2));
}
}
Description:
Output:

Q# 87.
Write a program that use compareTo() to determine sort ordering
for a bubble sort.
//A bubble sort for string
public class SortString {
static String arr[] = {
81 | P a g e
JAVA & OOPS Manual
"my","Name","is","khan","i","am","the","student","of","BSCS.","i","am","studing","in","
NFC","IEFR","Faisalabad"
};
public static void main (String[] args) {
for(int j = 0; j <arr.length; j++){
for(int i =j+1; i<arr.length;i++){
if(arr[i].compareTo(arr[j])< 0){
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
Description:
Output:

Q# 88.
Write a program that show how to use various index method t search
inside of string.
public class IndexOfDemo {
public static void main(String[] args) {
String s = " my name is hussain ahmad khan , i am the student of BSCS " +
"gradugate doing from Nfc IEFR Faisalabad Punjab Pakistan.";
System.out.println(s);
System.out.println("Last Index of (t) = " + s.indexOf('t'));
System.out.println("Last Index of (t) = " + s.lastIndexOf('t'));
82 | P a g e
JAVA & OOPS Manual
System.out.println("Last Index of (the) = " + s.indexOf("the"));
System.out.println("Last Index of (the) = " + s.lastIndexOf("the"));
System.out.println("Last Index of (t,10) = " + s.indexOf('t',10));
System.out.println("Last Index of (t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("Last Index of (the,10) = " + s.indexOf("the",10));
System.out.println("Last Index of (the, 60) = " + s.lastIndexOf("the", 60));
}
}
Description:
Output:

Q# 89.
Write a program that use substring() method to replace all instance of
one substring with another within string.
class StringReplace {
public static void main (String[] args) {
String org = "This is a Test. This is , too.";
String search = "is";
String sub = "was";
String result = " ";
int i;
do {

//replase all matching substring

System.out.println(org);
i = org.indexOf(search);
if(i != -1){
result = org.substring(0, i);
result = result + sub ;
result = result + org.substring(i + search.length());
org = result;
}
83 | P a g e
JAVA & OOPS Manual
}
while (i != -1);
}
}
Description:
Output:

Q# 90.

Write a program that use trim() to process commands.

import java.io.*;

//this is for taking input and output

public class UseTrim {

//class name declare

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

// main body of programme

//

BufferedReader br = new BufferedReader (new InputStreamReader(System.in)) ;// creat
bufferedReader using System.in
String str;

//declare str

System.out.println("Enter 'Stop' to quite. ");
System.out.println("Enter State: ");
do {

//print line

// do while declare

str = br.readLine();
str = str.trim();

// print the line

//Call readLine() method to str
//remove whitespace

if (str.equals("Illionois"))

//define if statement

System.out.println("Capital spring feild.");
else if (str.equals("Missouri"))

//print the line

//else statement difine

System.out.println("Capital is Jefferson city");

// print capital is Jefferson

city
else if(str.equals("California"))
statement

// otherwise equals method call using if

System.out.println("Capital is Scramemento");
else if (str.equals("Washhington"))
statement

// print value

//again equls method call using else if

System.out.println("Capital is Olampia."); // print capital is olampia.
84 | P a g e
JAVA & OOPS Manual
}
while(!str.equals("stop"));

//while condition define

}
}
Description:
First declare class name
Output:

Q# 91.
Write a program that convert uppercase latter to lowercase and
lowercase to uppercase latters.
public class ChangeCase {

//class name declare

public static void main(String[] args) {
String s = "This is a test.";

//main body of program start from here
//declare and initialize s

System.out.println("Orignal sentence:" + s);

// print value of s

String upper = s.toUpperCase();

//call toUpperCase() method

String lower = s.toLowerCase ();

//call toLowerCase() method

System.out.println("Upper: " + upper);

// print string line in upper case

System.out.println("Lower case: " + lower);
}

// print string line in lower case

// ending brace of main body

}

//ending brace of class

Description:
In this code first make a class than start main body of program. Than declare s and then call
toLoweCase() method and toUpperCase() method. Than print their their value.
Output:

Q# 92.

Write a program that define StringBuffer length vs. capacity.

class StringBufferDemo {
public static void main (String[] args) {
85 | P a g e
JAVA & OOPS Manual
StringBuffer sb = new StringBuffer ("Hellow");
System.out.println("Buffer before = " + sb);
System.out.println("Char at (1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("CharAt(1) after = " + sb.charAt(1));
}
}
Description:
In this program first make class and write main method, after this call StringBuffer() method
and declare sb after this print value of sb.
Output:

Q# 93.

Write a program that demonstrate append() method .

class AppendDemo {

//class name declare

public static void main (String[] args) {
String s ;

// print main body of program start

//declare s

int a = 42;

declare and initialize a

StringBuffer sb = new StringBuffer (40);

// call stringBuffer() method.

s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s); //print value of s
}
}

// ending brace of main body
//ending brace of class

Description:
In this program make class and main body of program start. Than initialize and declare a and s,
after this call StringBuffer() method. Than print value of s.
Output:

86 | P a g e
JAVA & OOPS Manual
Q# 94.

Write a program that demonstrate insert() method.

lass InsertDemo{
public static void main (String[] args) {
StringBuffer sb = new StringBuffer ("I java");
sb.insert(2, "like ");

//insert like on 2 number.

System.out.println(sb);

// print value of sb

}
}

//ending brace of main body
//ending brace of class

Description:
Output:

Q# 95.

Write a program that demonstratereplace() method.

class ReplaceDemo {

// class name start

public static void main (String[] args) {

//main body of program start

StringBuffer sb = new StringBuffer ("This is a test.");
System.out.println("Before replace: " + sb);
sb.replace(5, 7, "was");

//Call StringBuffer() method
//print value of sb

//Call replace method

System.out.println("After replace : " + sb);
method.

//print value of sb after replacing

}
}
Description:
In this code first make a class than write main body of program , after this call StringBuffer()
method. Than print sb after this call replace() method and replace the words.
Output:

Q# 96.

Write a program that demonstrate IndexOfDemo () method.

public class IndexOfDemo {
public static void main(String[] args) {

//main body of program start

String s = " my name is hussain ahmad khan , i am the student of BSCS " +
87 | P a g e
JAVA & OOPS Manual
"gradugate doing from Nfc IEFR Faisalabad Punjab Pakistan.";
System.out.println(s);

// print value of s

System.out.println("Last Index of (t) = " + s.indexOf('t'));

//print value

System.out.println("Last Index of (t) = " + s.lastIndexOf('t'));

//print value

System.out.println("Last Index of (the) = " + s.indexOf("the"));

//print value

System.out.println("Last Index of (the) = " + s.lastIndexOf("the")); //print value
System.out.println("Last Index of (t,10) = " + s.indexOf('t',10));

//print value

System.out.println("Last Index of (t, 60) = " + s.lastIndexOf('t', 60));

//print value

System.out.println("Last Index of (the,10) = " + s.indexOf("the",10));

//print value

System.out.println("Last Index of (the, 60) = " + s.lastIndexOf("the", 60));

//print

value
}
}

//ending brace of main bpdy
//ending brace of class

Description:
In this program first make a class than main body of program start. After this call StringBuffer()
than declare I after this call indexOf() method than print value of I , after this call lastIndecOf()
method than print value of i.
Output:

Chater#09(Package and inter face)
Q# 97.

Write a program that that demonstrates package access.

package mypack;
class Balance {
String name;
doublebal;
Balance(String n, double b){
name = n;
bal = b;
}
void show (){

88 | P a g e
JAVA & OOPS Manual
if(bal<0)
System.out.print("-->");
System.out.print(name + " : $" + bal);
}
}
publicclass AccountBalance {
publicstaticvoid main (String args [] ){
Balance current [] = new Balance [3];
current [0] = new Balance ("K.J.Fielding", 123.23);
current [1] = new Balance ("Will Tell", 157.02);
current [2] = new Balance ("Tom Jackson", -12.33);
for (int i=0; i<3; i++)
current [i].show();
}
}

Description:
Ist I make a project in java eclipse, than I make a package name as mypack , after this I make a
class in this package. After this I make a class name Balance,, after this declare name as tring
and bal as double , than make constructor, after this make show method , than make main class ,
which is abstract from Balance, and show output.
Output:

Q# 98.
Write a program that demonstrates class of one package call in second
package.
package p1;
publicclass Protection {
intn = 1;
privateintn_pri = 2;
protectedintn_pro = 3;
publicintn_pub = 4;
public Protection (){
System.out.println("base constructer");
System.out.println("n = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pro = " + n_pub);
}
}
package p1;
class Derived extends Protection {
Derived() {
System.out.println("derived
System.out.println("n = " +
//System.out.println("n_pri
System.out.println("n_pro =
System.out.println("n_pub =
}

89 | P a g e

constructor");
n);
= " + n_pri);
" + n_pro);
" + n_pub);
JAVA & OOPS Manual
}

This is class SamePackage.java
package p1;
class SamePackage {
SamePackage(){
Protection p = new Protection ();
System.out.println("Same package constructor");
System.out.println("n = " + p.n);
//System.out.println("n_pri = " + p.npri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}

This is file class Protectionism.java
/**
*
*/
package p2;
/**
* @author hussain
*
*/
class Protection2 extends p1.Protection{
/**
* body
*/
public Protection2() {
System.out.println("Derived other package constructor");
// class or package only
// System.out.println("n = " + n);
//class only
//System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
90 | P a g e
JAVA & OOPS Manual
}
}
This is class file OtherPackage.java
/**
*
*/
package p2;
/**
* @author hussain
*
*/
public class OtherPackage {
/**
*
*/
public OtherPackage() {
p1.Protection p = new p1.Protection ();
System.out.println("Other Package Constructor");
// class or package only
//System.out.println("n = " +p. n);
//class only
//System.out.println("n_pri" + p.n_pri);
//class subclass or package only
//System.out.println("n_pro = " p.n_pro);
System.out.println("n_pub = " + p.n_pub);
// TODO Auto-generated constructor stub
}
}
Now Package p1.java
package p2;

91 | P a g e
JAVA & OOPS Manual
publicclass Demo {
/**
* @param args
*/
publicstaticvoid main(String[] args) {
Protection2 ob1 = new Protection2 ();
OtherPackage ob2 = new OtherPackage();
}
}

The test file for P2 is shown next
package p1;
publicclass Demo {
/**
* @param args
*/
publicstaticvoid main(String[] args) {
Protection ob1 = new Protection ();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage ();
}
}

Description:
The two classes defined in
p2 cover the other two conditions which are affected by access control. The first class,
Protection2, is a subclass of p1.Protection. This grants access to all of p1.Protection’s
variables except for n_pri (because it is private) and n, the variable declared with the
default protection. Remember, the default only allows access from within the class or
the package, not extra-package subclasses. Finally, the class OtherPackage has access
to only one variable, n_pub, which was declared public.
Output:

92 | P a g e
JAVA & OOPS Manual

Q# 99.

Write a program that demonstrate importing package.

/**
*
*/
package mypack;
/**
* @authorhussain
*
*/
publicclass Balance {
String name;
doublebal;
/**
*
*/
public Balance(String n, double b){
name = n;
bal = b;
}
publicvoid show (){
if(bal<0)
System.out.print("-->");
System.out.print(name + " : $" + bal);
}
}

This class is in another class and import package , member of other class
//import java.util.*;
import mypack.*;
publicclass TestBalance {
publicstaticvoid main (String args []){
Balance test = new Balance ("J . J . Jasper", 99.98);
test.show();
}
}

93 | P a g e
JAVA & OOPS Manual
Description:
Balance class is now public. Also, its constructor and its
show( ) method are public, too. This means that they can be accessed by any type of
code outside the MyPack package. For example, here TestBalance imports MyPack
and is then able to make use of the Balance class.
Output:

Q# 100.

Write a program that demonstrate fixed storage in interface.

package interface9;
class FixedStack implements IntStack {
privateintstck[];
privateinttos;
// allocate and initialize stack
FixedStack(int size) {
stck = newint[size];
tos = -1;
}
// Push an item onto the stack
publicvoid push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
publicint pop() {
if(tos< 0) {
System.out.println("Stack underflow.");
return 0;
}
else
returnstck[tos--];
}
}
publicclass IFTest {
/**
* @param args
*/
publicstaticvoid main(String[] args) {
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++) mystack1.push(i);
for(int i=0; i<8; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());

94 | P a g e
JAVA & OOPS Manual
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}

Description:
IntStack that creates a dynamic stack by
use of the same interface definition. In this implementation, each stack is constructed
with an initial length. If this initial length is exceeded, then the stack is increased in
size. Each time more room is needed, the size of the stack is doubled.

Q# 101.

Write a program that demonstrate ?

package interface9;
//Implement a "growable" stack.
class DynStack implements IntStack {
privateintstck[];
privateinttos;
// allocate and initialize stack
DynStack(int size) {
stck = newint[size];
tos = -1;
}
// Push an item onto the stack
publicvoid push(int item) {
// if stack is full, allocate a larger stack
if(tos==stck.length-1) {
int temp[] = newint[stck.length * 2]; // double size
for(int i=0; i<stck.length; i++) temp[i] = stck[i];
stck = temp;
stck[++tos] = item;
}
else
stck[++tos] = item;
}
// Pop an item from the stack
publicint pop() {
if(tos< 0) {
System.out.println("Stack underflow.");
return 0;
}
else
returnstck[tos--];
}
}
class IFTest2 {
publicstaticvoid main(String args[]) {
DynStack mystack1 = new DynStack(5);
DynStack mystack2 = new DynStack(8);
// these loops cause each stack to grow
for(int i=0; i<12; i++) mystack1.push(i);
for(int i=0; i<20; i++) mystack2.push(i);

95 | P a g e
JAVA & OOPS Manual
System.out.println("Stack in mystack1:");
for(int i=0; i<12; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<20; i++)
System.out.println(mystack2.pop());
}
}

Description:
mystack is a reference to the IntStack interface. Thus, when it refers to
ds, it uses the versions of push( ) and pop( ) defined by the DynStack implementation.
When it refers to fs, it uses the versions of push( ) and pop( ) defined by FixedStack.
As explained, these determinations are made at run time. Accessing multiple
implementations of an interface through an interface reference variable is the most
powerful way that Java achieves run-time polymorphism.
Output:

Q# 102.

Write a program that ?

package interface9;
import java.util.Random;
interface SharedConstants {
intNO = 0;
intYES = 1;
intMAYBE = 2;
intLATER = 3;
intSOON = 4;

96 | P a g e
JAVA & OOPS Manual
intNEVER = 5;
}
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 30)
returnNO; // 30%
elseif (prob < 60)
returnYES; // 30%
elseif (prob < 75)
returnLATER; // 15%
elseif (prob < 98)
returnSOON; // 13%
else
returnNEVER; // 2%
}
}
class AskMe implements SharedConstants {
staticvoid answer(int result) {
switch(result) {
caseNO:
System.out.println("No");
break;
caseYES:
System.out.println("Yes");
break;
caseMAYBE:
System.out.println("Maybe");
break;
caseLATER:
System.out.println("Later");
break;
caseSOON:
System.out.println("Soon");
break;
caseNEVER:
System.out.println("Never");
break;
}
}
publicstaticvoid main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}

Description:
This
class provides pseudorandom numbers. It contains several methods which allow you
to obtain random numbers in the form required by your program. In this example, the
97 | P a g e
JAVA & OOPS Manual
method nextDouble( ) is used. It returns random numbers in the range 0.0 to 1.0.
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. Here is the output of a sample run of this program.
Output:

Q# 103.

Write a program that show interface can be extended.

/**
*
*/
package interface9;
/**
* @author hussain
*
*/
//One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
98 | P a g e
JAVA & OOPS Manual
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Description:
you might want to try 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
Output:

99 | P a g e
JAVA & OOPS Manual
Chapter#12 (I/O,APPLET, AND OTHER TOPIC)
Q# 104.

Write a program that read the Character.

package readingCharacter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BRRead {
public static void main(String args [])
throws IOException {
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter character, 'q' to quit.");
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Description:
This output may look a little different from what you expected, because System.in is
line buffered, by default. This means that no input is actually passed to the program
until you press ENTER. As you can guess, this does not make read( ) particularly
valuable for interactive, console input.
Output:

Q# 105.
/**
*
100 | P a g e

Write a program that read String.
JAVA & OOPS Manual
*/
package readingString;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author hussain
*
*/
public class BRReadLine {
/**
* @param args
*/
public static void main(String[] args)
throws IOException {
// TODO Auto-generated method stub
// creat a bfferedreader line using system.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Ener lines of text.");
System.out.println("Ener 'stop' of quit.");
do{
str = br.readLine();
System.out.println(str);
} while (!str.equals("stop"));
}
}
Description:
101 | P a g e
JAVA & OOPS Manual
To read a string from the keyboard, use the version of readLine( ) that is a member of
the BufferedReader class.following program demonstrates BufferedReader and the
readLine( ) method;
the program reads and displays lines of text until you enter the word ―stop‖:
Output:

Q# 106.

Write a program that create a tiny Text editor.

/**
*
*/
package readingString;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author hussain
*
*/
public class TinyEdit {
/**
* @param args
*/
public static void main(String[] args)
throws IOException {

102 | P a g e
JAVA & OOPS Manual
// creat a bfferedreader line using system.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str [] = new String[100];
System.out.println("Ener lines of text.");
System.out.println("Ener 'stop' of quit.");
for(int i = 0; i<00; i++){
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.print("n Here is your file:");
// display the line
for(int i = 0; i<00; i++){
if (str[i].equals("stop")) break;
System.out.print(str[i]);
}
}
}
Description:
To read a string from the keyboard, use the version of readLine( ) that is a member of
the BufferedReader class.following program demonstrates BufferedReader and the
readLine( ) method;
the program reads and displays lines of text until you enter the word ―stop‖:
Output:

Q# 107.
/**
*
*/
103 | P a g e

Write a program that demonstrate System.out.write().
JAVA & OOPS Manual
package writingconsoeoutput;
/**
* @author hussain
*
*/
public class WriteDemo {
/**
* @param args
*/
public static void main(String[] args) {
int b;
b = 'c';
System.out.print(b);
System.out.write('n');
}
}
Description:
There is nothing wrong with using System.out to write simple text
output to the console when you are learning Java or debugging your programs.
However, using a PrintWriter will make your real-world applications easier to
internationalize. Because no advantage is gained by using a PrintWriter in the
sample programs shown in this book, we will continue to use System.out to write
to the console.
Output:

Q# 108.

Write a program that demonstrate PrintWriter Class.

/**
*
*/
package printwriter;
104 | P a g e
JAVA & OOPS Manual

import java.io.PrintWriter;
/**
* @author hussain
*
*/
public class PrintwriterDemo {
/**
* @param args
*/
public static void main(String[] args) {
PrintWriter pw = new PrintWriter (System.out, true);
pw.println("This is a String");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
Description:
The following program uses read( ) to input and display the contents of a text file,
the name of which is specified as a command-line argument. Note the try/catch blocks
that handle the two errors that might occur when this program is used—the specified
file not being found or the user forgetting to include the name of the file. You can use
this same approach whenever you use command-line arguments.
Output:

105 | P a g e
JAVA & OOPS Manual
Q# 109.

Write a program that demonstrate a text file.

/**
*
*/
package readandwrite;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author hussain
*
*/
public class ShowFile {
/**
* @param args
*/
public static void main(String[] args)
throws IOException {
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
}

catch(FileNotFoundException e){
System.out.println("File Not Found");
return;

}

catch (ArrayIndexOutOfBoundsException e){
System.out.println("Ener lines of text.");
System.out.println("Usage : ShowFile File");
return;

}
106 | P a g e
JAVA & OOPS Manual
do {
i = fin.read();
if (i != -1) System.out.print((char)i);
} while (i != -1);
fin.close();
}
}
Description:
To write to a file, you will use the write( ) method defined by FileOutputStream.
Its simplest form is shown here:
void write(int byteval) throws IOException
This method writes the byte specified by byteval to the file. Although byteval is declared
as an integer, only the low-order eight bits are written to the file. If an error occurs
during writing, an IOException is thrown
Output:

Q# 110.

Write a program that demonstrate to copy a text file.

/**
*
*/
package readandwrite;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author hussain
*
107 | P a g e
JAVA & OOPS Manual
*/
public class CopyFile {
/**
* @param args
*/
public static void main(String[] args)
throws IOException{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch (FileNotFoundException e){
System.out.print("Input File Not Foud");
return;
}
// open output file
try {
fout = new FileOutputStream(args[1]);
} catch (FileNotFoundException e){
System.out.print("Error oprning output file");
return;
}
} catch(ArrayIndexOutOfBoundsException e){
System.out.print("Usage : CopyFile From To");
return;
}
// copy file
try {
108 | P a g e
JAVA & OOPS Manual
do {
i = fin.read();
if(i != -1) fout.write(i);
} while (i != -1);
}catch (IOException e){
System.out.print("File Error");
}
fin.close();
fout.close();
}
}
Description:
Output:

Q# 111.

Write a program that demonstrate on simple simple Applet method.

package AppletFundamental;
import java.applet.Applet;
import java.awt.Graphics;
publicclassSimpleAppletextends Applet {
publicvoid paint (Graphics g){
g.drawString("A simple Applet", 20, 20);
}
}

Description:
This applet begins with two import statements. The first imports the Abstract Window
Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the
console-based I/O classes. The AWT contains support for a window-based, graphical
interface. As you might expect, the AWT is quite large and sophisticated
Output:

109 | P a g e
JAVA & OOPS Manual

Q# 112.

Write a program that demonstrate instanceof () Operator.

/**
*
*/
package instanceoof;
/**
* @author hussain
*
*/
class A{
int i,j;
}
class B{
int i,j;
}
class C extends A {
int k;
}
110 | P a g e
JAVA & OOPS Manual
class D extends A {
int k;
}
class Instanceof {
/**
* @param args
*/
public static void main(String[] args) {
A a = new A ();
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
System.out.println("a is instanceof of A");
if (b instanceof B)
System.out.println("b is instanceof of B");
if (c instanceof C)
System.out.println("c is instanceof of C");
if (d instanceof D)
System.out.println("d is instanceof of D");
if (a instanceof C)
System.out.println("a can b cast to C");
System.out.println();
// compare type of derived type
A ob;
ob = d; // a refrence to d
System.out.println("ob now refrence to d");
if (ob instanceof D)
System.out.println("ib is instanceof of D");
System.out.println();
111 | P a g e
JAVA & OOPS Manual
ob = c;
System.out.println("ob now refer to c");
if (ob instanceof D)
System.out.println("ob can b cast to D");
else
System.out.print("ob cannot b cast to D");
if (ob instanceof A)
System.out.print("ob can b cast to A");
System.out.println();
// all object can be cast cast to object
if (a instanceof Object)
System.out.print("a must b cast to Object.");
if (b instanceof Object)
System.out.print("b must b cast to Object.");
if (c instanceof Object)
System.out.print("c must b cast to Object.");
if (d instanceof Object)
System.out.print("d must b cast to Object.");
}
}
Description:
The instanceof operator isn’t needed by most programs, because, generally, you know
the type of object with which you are working. However, it can be very useful when you’re
writing generalized routines that operate on objects of a complex class hierarchy.
Output:

112 | P a g e
JAVA & OOPS Manual

Q# 113.

Write a program that that demonstrate how to use assert.?

package assert1;
publicclass AssertDemo {
staticintval= 3;
// val declare and initialize
staticint getnum(){
// getnum() method start
returnval--;
// return decrement of val value
}
// ending brace of getnum() method
publicstaticvoid main (String args []){ // main body of program start
from here
int n;
// declare n
for(int i = 0; i <10; i++){
// for loop
n = getnum();
// call getnum () method
assert n > 0 ; // will fail when n is zero
System.out.println("n is" + n);
// print value of
n
}
}
}

Description:
Thisvalue is converted to its string format and displayed if an assertion fails. Typically, you
will specify a string for expr, but any non-void expression is allowed as long as it
defines a reasonable string conversion.
Output:

Chapter#19(The Applet Classes)
Q# 114.

Write a program that demonstrates Applet Skelton.

/**
*
*/
package appletskelton1;

113 | P a g e
JAVA & OOPS Manual
import java.applet.Applet;
import java.awt.Graphics;
/**
* @author hussain
*
*/
public class AppletSkel extends Applet {
//called first
public void init(){
//initlization
}
public void start (){
// start or resume executation
}
public void stop(){
// suspends executation
}
public void destory (){
// perform shut down activity
}
public void paint (Graphics g){
//redisplay content of window
}
}
Description:
Output:

114 | P a g e
JAVA & OOPS Manual

Q# 115.
Write a program that demonstrate foreground and background
ground color of and out put of String.
package displaymethod;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Sample extends Applet {
//private static final long serialVersionUID = 1L;
String msg;
// set forgroung and background color
public void init (){
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inide init( ) --";
}
// initiliaze the string to displaymethod
public void start (){
msg += "Inside start ( ) --";
}
115 | P a g e
JAVA & OOPS Manual
// display msg in applet window
public void paint (Graphics g){
msg += "Inside start ( ).";
g.drawString(msg, 10, 30);
}
}
Description:
The methods stop( ) and destroy( ) are not overridden, because they are not needed
by this simple applet.
Output:

Q# 116.

Write a program that demonstrate simple Banner Applet.

package bannerapplet3;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class SimpleBanner extends Applet implements Runnable{
String msg = "A simple Moving. ";
Thread t = null;
int state;
boolean stopFlag;
116 | P a g e
JAVA & OOPS Manual
public void init (){
setBackground(Color.CYAN);
setForeground(Color.red);
}
public void start (){
t = new Thread (this);
stopFlag = false;
t.start();
}
public void run (){
char ch;
for(;;){
try{
repaint();
Thread.sleep(250);
ch = msg .charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if(stopFlag)
break;
} catch (InterruptedException e) {
}
}
}
public void stop (){
stopFlag = true;
t = null;
}
public void paint (Graphics g){
g.drawString(msg, 50, 30);
}
117 | P a g e
JAVA & OOPS Manual
}
Description:
Let’s take a close look at how this applet operates. First, notice that SimpleBanner
extends Applet, as expected, but it also implements Runnable. This is necessary, since
the applet will be creating a second thread of execution that will be used to scroll the
banner. Inside init( ), the foreground and background colors of the applet are set.
Output:

Q# 117.

Write a program that demonstrate showStatus().

package statuswindow4;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class StatusWindow extends Applet{
public void init (){
setBackground(Color.CYAN);
}
public void paint (Graphics g){
g.drawString("This is an Applet Window.", 10, 20);
showStatus("This is shown in the status window.");
118 | P a g e
JAVA & OOPS Manual
}
}
Description:
The status window
is a good place to give the user feedback about what is occurring in the applet, suggest
options, or possibly report some types of errors. The status window also makes an
excellent debugging aid, because it gives you an easy way to output information about
your applet.
Output:

Q# 118.

Write a program that demonstrate passing parameter to Applet.

package passingparameter5;
import java.applet.Applet;
import java.awt.Graphics;
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
public void start (){
String Param;
119 | P a g e
JAVA & OOPS Manual
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
Param = getParameter("fontSize");
try{
if(Param != null)
fontSize = Integer.parseInt(Param);
else
fontSize = 0;
}
catch(NumberFormatException e){
fontSize = -1;
}
Param = getParameter("leading");
try{
if (Param != null)
leading = Float.valueOf(Param).floatValue();
else
leading = 0;
}catch(NumberFormatException e){
leading = -1;
}
Param = getParameter("Account Enabled");
if(Param != null)
active = Boolean.valueOf(Param).booleanValue();
}
public void Paint (Graphics g){
g.drawString("Font Name", 0, 10);
g.drawString("Font Soze" + fontSize, 0, 26);
g.drawString("Leading" + leading , 0, 42);
g.drawString("Account Active" + active
}
120 | P a g e

,0 , 58);
JAVA & OOPS Manual
}
Description:
It return values from getParameter( ). If a
parameter isn’t available, getParameter( ) will return null. Also, conversions to numeric
types must be attempted in a try statement that catches NumberFormatException.
Uncaught exceptions should never occur within an applet
Output:

Q# 119.

Write a program that display code and document bases.

package getDocument;
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="Bases" width=300 height=50>
</applet>
*/
publicclassBasesextends Applet{
// Display code and document bases.
publicvoid paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}

Description:

Output:

121 | P a g e
JAVA & OOPS Manual

Q# 120.

Write a program that get code and display HTML file.

package showDocument8;
importjava.awt.*;
import java.applet.*;
import java.net.*;
publicclassACDemoextends Applet{
publicvoid start() {
AppletContext ac = getAppletContext();
URL url = getCodeBase(); // get url of this applet
try {
ac.showDocument(new URL(url+"Test.html"));
} catch(MalformedURLException e) {
showStatus("URL not found");
}
}
}

Description:
AppletContext and showDocument( ).
Upon execution, it obtains the current applet context and uses that context to
transfer control to a file called Test.html. This file must be in the same directory
as the applet. Test.html can contain any valid hypertext that you like.
Output:

122 | P a g e
JAVA & OOPS Manual

Chapter#20(Events Handling)
Q# 121.

Write a program that demonstrate mouse event handler.

package handlingmouse1;
//Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
publicclassMouseEventsextends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
intmouseX = 0, mouseY = 0; // coordinates of mouse
publicvoid init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
publicvoid mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
publicvoid mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

123 | P a g e
JAVA & OOPS Manual
// Handle mouse exited.
publicvoid mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
publicvoid mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
publicvoid mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
publicvoid mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
publicvoid mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
publicvoid paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

Description:
The MouseEvents class extends Applet and
implements both the MouseListener and MouseMotionListener interfaces. These
two interfaces contain methods that receive and process the various types of mouse
events. Notice that the applet is both the source and the listener for these events.
This works because Component, which supplies the addMouseListener( ) and
addMouseMotionListener( ) methods, is a superclass of Applet. Being both the
source and the listener for events is a common situation for applets.
124 | P a g e
JAVA & OOPS Manual
Inside init( ), the applet registers itself as a listener for mouse events. This is done
by using addMouseListener( ) and addMouseMotionListener( ), which, as mentioned,
are members of Component.
Output:

Q# 122.

Write a program that demonstrate key event handler.

package handlingkeybord;
//Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
publicclassSimpleKeyextends Applet
implements KeyListener {
String msg = "";
intX = 10, Y = 20; // output coordinates
publicvoid init() {
addKeyListener(this);
requestFocus(); // request input focus
}
publicvoid keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
publicvoid keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
publicvoid keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
publicvoid paint(Graphics g) {
g.drawString(msg, X, Y);

125 | P a g e
JAVA & OOPS Manual
}
}

Description:
If you want to handle the special keys, such as the arrow or function keys, you need
to respond to them within the keyPressed( ) handler. They are not available through
keyTyped( ).
Output:

program
adapter in

Q# 123.
Write a
that demonstrate an
event handling.

package

adapter;

//Demonstrate
importjava.awt.*;
import java.awt.event.*;
import java.applet.*;
publicclassAdapterDemoextends Applet {
publicvoid init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
publicvoid mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {

an adapter.

126 | P a g e
JAVA & OOPS Manual
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
publicvoid mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}

Description:
As you can see by looking at the program, not having to implement all of the
methods defined by the MouseMotionListener and MouseListener interfaces saves
you a considerable amount of effort and prevents your code from becoming cluttered
with empty methods. As an exercise, you might want to try rewriting one of the
keyboard input examples shown earlier so that it uses a KeyAdapter.

Output:

Q# 124.
Write a
to inner classes
package inner;

program that show how
uses .?

//This applet does NOT use an inner class.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MousePressedDemo" width=200 height=100>
</applet>
*/
publicclassMousePressextends Applet {
publicvoid init() {
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
MousePress mousePress;
public MyMouseAdapter(MousePress mousePressedDemo) {
this.mousePress = mousePressedDemo;
}
publicvoid mousePressed(MouseEvent me) {
mousePress.showStatus("Mouse Pressed.");

127 | P a g e
JAVA & OOPS Manual
}
}

Description:
The following listing shows how the preceding program can be improved
by using an inner class. Here, InnerClassDemo is a top-level class that extends
Applet. MyMouseAdapter is an inner class that extends MouseAdapter. Because
MyMouseAdapter is defined within the scope of InnerClassDemo, it has access to all of
the variables and methods within the scope of that class. Therefore, the mousePressed( )
method can call the showStatus( ) method directly. It no longer needs to do this via a
stored reference to the applet. Thus, it is no longer necessary to pass MyMouseAdapter( )
a reference to the invoking object.
Output:

Q# 125.

Write a program that demonstrate Anonymous inner class.

package anonymousinner;
//Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
publicclassAnonymousInnerClassDemoextends Applet {
publicvoid init() {
addMouseListener(new MouseAdapter() {
publicvoid mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}

Description:
There is one top-level class in this program: AnonymousInnerClassDemo. The init( )
method calls the addMouseListener( ) method. Its argument is an expression that defines
and instantiates an anonymous inner class. Let’s analyze this expression carefully.
128 | P a g e
JAVA & OOPS Manual
Output:

129 | P a g e

More Related Content

PPTX
Java package
PPSX
Seminar on java
PDF
Java threads
PPTX
INHERITANCE IN JAVA.pptx
PPTX
Inner classes in java
PPT
Java operators
PPTX
Multithreading in java
PPTX
Javascript conditional statements
Java package
Seminar on java
Java threads
INHERITANCE IN JAVA.pptx
Inner classes in java
Java operators
Multithreading in java
Javascript conditional statements

What's hot (20)

PPTX
Control flow statements in java
PDF
Java Multithreading Using Executors Framework
PPTX
This keyword in java
PDF
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
PPS
Introduction to class in java
PPTX
Dynamic method dispatch
PPTX
Methods in java
PPT
Final keyword in java
PPTX
Classes and objects
PPTX
Constructor in java
PPTX
Access Modifier.pptx
PDF
Basic Java Programming
PDF
P code
PPTX
Local variables Instance variables Class/static variables
PPTX
Encapsulation C++ Piller of OOP it is the important piller
PPSX
Data Types & Variables in JAVA
PDF
CONST-- once initialised, no one can change it
PPTX
Access modifier and inheritance
PPTX
I/O Streams
PPT
Java And Multithreading
Control flow statements in java
Java Multithreading Using Executors Framework
This keyword in java
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Introduction to class in java
Dynamic method dispatch
Methods in java
Final keyword in java
Classes and objects
Constructor in java
Access Modifier.pptx
Basic Java Programming
P code
Local variables Instance variables Class/static variables
Encapsulation C++ Piller of OOP it is the important piller
Data Types & Variables in JAVA
CONST-- once initialised, no one can change it
Access modifier and inheritance
I/O Streams
Java And Multithreading
Ad

Viewers also liked (20)

PDF
Java programming-examples
DOCX
Basic java important interview questions and answers to secure a job
PDF
Advanced Java Practical File
PPT
Most Asked Java Interview Question and Answer
DOCX
Java questions for viva
DOCX
Java PRACTICAL file
DOC
Ad java prac sol set
DOCX
Java Code for Sample Projects Inheritance
PDF
Advanced java practical semester 6_computer science
DOC
Advanced Java - Praticals
PPT
Simple Java Programs
PDF
Top 10 Java Interview Questions and Answers 2014
PDF
Java Simple Programs
DOC
Final JAVA Practical of BCA SEM-5.
PPT
Ch01 basic-java-programs
PPS
Advance Java
PPT
Introduction to-programming
DOCX
Java practical
PPT
Java tutorial PPT
DOC
Hospital management system
Java programming-examples
Basic java important interview questions and answers to secure a job
Advanced Java Practical File
Most Asked Java Interview Question and Answer
Java questions for viva
Java PRACTICAL file
Ad java prac sol set
Java Code for Sample Projects Inheritance
Advanced java practical semester 6_computer science
Advanced Java - Praticals
Simple Java Programs
Top 10 Java Interview Questions and Answers 2014
Java Simple Programs
Final JAVA Practical of BCA SEM-5.
Ch01 basic-java-programs
Advance Java
Introduction to-programming
Java practical
Java tutorial PPT
Hospital management system
Ad

Similar to Java codes (20)

PDF
Object oriented programming -QuestionBank
PDF
Lab exam question_paper
DOC
Java programming lab assignments
DOC
Practical java
PDF
(eTextbook PDF) for Starting Out with Java: From Control Structures through O...
PDF
Week 1
PDF
Test Bank for Java Programming, 7th Edition
DOCX
Lab exam question_paper
PPT
Basic elements of java
PPT
00_Introduction to Java.ppt
PPTX
Java Android Programming for MAD lab Fundamentals
PPTX
Advanced Computer Programming..pptx
PDF
(eBook PDF) Starting Out with Java: From Control Structures through Objects, ...
PDF
Test Bank for Java Programming, 7th Edition
PDF
Test Bank for Java Programming, 7th Edition
PDF
Get Test Bank for Java Programming, 7th Edition free all chapters
DOCX
703497334-ICSE-Class-9-Computer-Applications-Sample-Question-Papers.docx
PDF
Chapter 00 revision
PPT
Introduction to Java Programming Part 2
Object oriented programming -QuestionBank
Lab exam question_paper
Java programming lab assignments
Practical java
(eTextbook PDF) for Starting Out with Java: From Control Structures through O...
Week 1
Test Bank for Java Programming, 7th Edition
Lab exam question_paper
Basic elements of java
00_Introduction to Java.ppt
Java Android Programming for MAD lab Fundamentals
Advanced Computer Programming..pptx
(eBook PDF) Starting Out with Java: From Control Structures through Objects, ...
Test Bank for Java Programming, 7th Edition
Test Bank for Java Programming, 7th Edition
Get Test Bank for Java Programming, 7th Edition free all chapters
703497334-ICSE-Class-9-Computer-Applications-Sample-Question-Papers.docx
Chapter 00 revision
Introduction to Java Programming Part 2

Recently uploaded (20)

PPTX
Pharma ospi slides which help in ospi learning
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Computing-Curriculum for Schools in Ghana
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
master seminar digital applications in india
PPTX
Cell Types and Its function , kingdom of life
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Pre independence Education in Inndia.pdf
PPTX
Lesson notes of climatology university.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
RMMM.pdf make it easy to upload and study
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Final Presentation General Medicine 03-08-2024.pptx
Pharma ospi slides which help in ospi learning
O7-L3 Supply Chain Operations - ICLT Program
Computing-Curriculum for Schools in Ghana
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
master seminar digital applications in india
Cell Types and Its function , kingdom of life
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Basic Mud Logging Guide for educational purpose
Pre independence Education in Inndia.pdf
Lesson notes of climatology university.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Renaissance Architecture: A Journey from Faith to Humanism
Module 4: Burden of Disease Tutorial Slides S2 2025
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
RMMM.pdf make it easy to upload and study
Microbial disease of the cardiovascular and lymphatic systems
Final Presentation General Medicine 03-08-2024.pptx

Java codes

  • 1. Table of Contents Chapter # 1 (The Genesis of Java) Q# 1. Write a java program which show hallow word app! Chapter # 2 (An Overview Of Java) 4 4 4 Q# 2. Write a java program to display a simple string. Q# 3. Write a simple java program to display a string and perform a simple multiplication. 5 Q# 4. Write a program which demonstrate the if statement.: 5 Q# 5. write a program to demonstrate the for loop. 6 Q# 6. Write a program which contains block of code in ―for‖ loop definition. 7 Chapter # 3: (Data type, Variable and Arays) 4 8 Q# 7. Write a program to compute distance light travel in 1000 days using long variables. 8 Q# 8. Write a program that calculates the area of a circle, use data type of double. 9 Q# 9. Write a program which demonstrate the char data type. 9 Q# 10. Write a program in which char variables behave like integers. 10 Q# 11. Write a program which demonstrate dynamic initialization. 11 Q# 12. Write a program that demonstrates the Boolean type values. 11 Q# 13. Write a program which show the effect of nested scopes. 12 Q# 14. Write a program to demonstrates the lifetime of a variable. 13 Q# 15. Write a program that convert one data type in to another data type 14 Q# 16. Write a program that multiply and add different data type variable. 15 Chapter # 4 (Operator) 15 Q# 17. Write a program which demonstrate the arithmetic operator 15 Q# 18. Write a programme that demonstrate modulus operator 16 Q# 19. Write a program in which various assignment operator is used. 17 Q# 20. Write a program which shows the function of increment(++). 18 Q# 21. Write a programme left shifting the byte value. 18 Q# 22. Write a programme that demonstrate the Boolean logical operator 19 Q# 23. Write a program which demonstrates the ? operator. 20 Chapter # 5 (Control Statement) 20 Q# 24. Write a programme that demonstrate if-else statement 20 Q# 25. Write a programme that show simple example of switch 21 Q# 26. Write a programme that show in switch break statements are optional 22
  • 2. JAVA & OOPS Manual Q# 27. Write a programme that show the season when any month is given to it. 23 Q# 28. Write a programme that demonstrate the while loop 24 Q# 29. Using while loop write a program which display midpoint of two numbers. 25 Q# 30. Write a programme that demonstrate dowhile 26 Q# 31. Write a program using do-while to process a menu selection. 26 Q# 32. Write a programme that demonstrate loop control veriable inside the for 29 Q# 33. loop. Write a program in which for loop is used and find the prime number by using this 29 Q# 34. Write program in which two variable used to control the iteration of for loop 30 Q# 35. Write program in which two variable used to control the iteration of for loop using for comma 31 Q# 36. for loop. Write a for loop program in which initialization and iteration is moved out of the 31 Q# 37. Write a program of nested for loop. 31 Q# 38. Write a program in using break to exit a loop. 32 Q# 39. Write a program in which using a break to exit a while loop. 33 Q# 40. Write a program in which using a break to exit a while loop. 34 Q# 41. Write a program in which break is used like go to statement. 34 Q# 42. Write a program that used for a labelled break statement to exit from nested loop. 35 Q# 43. Write a program that uses continue to cause two number. 36 Q# 44. Write a program that uses continue to print a triangular multiplication of table for 0 through 9. 36 Q# 45. Write a program that demonstrates return. Chapter # 6 (Introducing classes) 37 38 Q# 46. Write a program that call this file BoxDemo.java. 38 Q# 47. Write a program that declares two Box object. 38 Q# 48. Write a program that includes a method inside the box class. 39 Q# 49. Write a program that volume () returns the volumeof a box 40 Q# 50. Write a program that use as parameterized method 41 Q# 51. Write a program that use a constructor to initialize the dimension f a box. 42 Q# 52. Write a program that uses a parameterized constructor to initialize the dimension. 43 Q# 53. Write a program that defines an integer stack that can hold 10 values. Chapter # 7 (A Closer Look at Methods and Classes) Q# 54. 1|Page Write a program that demonstrates method overloading. 44 46 46
  • 3. JAVA & OOPS Manual Q# 55. Write a program that use overloaded method and convert a parameter into corresponding data type when compatible type of constructor is not available. 47 Q# 56. Write a program that shows the dimension of a box in various way. 48 Q# 57. Write a program that 49 Q# 58. Write a program that shows the overloading of constructors. 50 Q# 59. Write a program that is passed by value. 52 Q# 60. Write a program that is call by reference. 53 Q# 61. Write a program that returning an object. 53 Q# 62. Write a program that that use the concept of recursion and find the factorial of the numbers. 54 Q# 63. Write a program that shows recursion. 55 Q# 64. Write a program that shows the working of access specifies. Like we can access public methods and variables but not private one. 56 Q# 65. Write a program that uses variable , method and blocks Q# 66. Write a program that inside main() the static method accessed outside of the class. 58 Q# 67. Write a program that demonstrates an inner class with in for loop. 59 Q# 68. Write a program that demonstrates Strings. 59 Q# 69. Write a program that demonstrates some string method. 60 Q# 70. Write a program that display all command line arguments 61 Q# 71. Write a program that uses inheritance to extend Box 61 Q# 72. Write a program that show Super keyword implementation of BoxWeight. 63 Q# 73. Write a program in which BoxWeight extends to includinf shipping cost. 66 Q# 74. Write a program that demonstrate when constructor are called. 69 Q# 75. Write a program that show method overriding. 70 Q# 76. Write a program that use Dynamic method dispatch. 71 Q# 77. Write a program that use run time poly-morphisam. 72 Q# 78. Write a program that use abstract method and classe. 73 Chapter # 10(Exception Handling) 57 75 Q# 79. Write a program using exceptions in it 75 Q# 80. Write a program showing multiple catch Clauses. 75 Q# 81. Write a program that Handle an exception and move on. 76 Q# 82. write a program of try statements 77 Q# 83. Write a program that can be implicitly nested via calls to methods. */ 78 Chapter#13 (String Handling) 2|Page 79
  • 4. JAVA & OOPS Manual Q# 84. Write a program that use override toString () for Box. 79 Q# 85. Write a program that demonstrate equals () and equalsIgnoreCase(). 80 Q# 86. Write a program that use == method to give answer. 81 Q# 87. Write a program that use compareTo() to determine sort ordering for a bubble sort. 81 Q# 88. string. Write a program that show how to use various index method t search inside of 82 Q# 89. Write a program that use substring() method to replace all instance of one substring with another within string. 83 Q# 90. Write a program that use trim() to process commands. 84 Q# 91. Write a program that convert uppercase latter to lowercase and lowercase to uppercase latters. 85 Q# 92. Write a program that define StringBuffer length vs. capacity. 85 Q# 93. Write a program that demonstrate append() method . 86 Q# 94. Write a program that demonstrate insert() method. 87 Q# 95. Write a program that demonstratereplace() method. 87 Q# 96. Write a program that demonstrate IndexOfDemo () method. 87 Chater#09(Package and inter face) 88 Q# 97. Write a program that that demonstrates package access. Q# 98. Write a program that demonstrates class of one package call in second package. 89 Q# 99. Write a program that demonstrate importing package. 93 Q# 100. Write a program that demonstrate fixed storage in interface. 94 Q# 101. Write a program that demonstrate ? 95 Q# 102. Write a program that ? 96 Q# 103. Write a program that show interface can be extended. 98 Chapter#12 (I/O,APPLET, AND OTHER TOPIC) 88 100 Q# 104. Write a program that read the Character. 100 Q# 105. Write a program that read String. 100 Q# 106. Write a program that create a tiny Text editor. 102 Q# 107. Write a program that demonstrate System.out.write( ). 103 Q# 108. Write a program that demonstrate PrintWriter Class. 104 Q# 109. Write a program that demonstrate a text file. 106 Q# 110. Write a program that demonstrate to copy a text file. 107 Q# 111. Write a program that demonstrate on simple simple Applet method. 109 Q# 112. Write a program that demonstrate instanceof () Operator. 110 3|Page
  • 5. JAVA & OOPS Manual Q# 113. Write a program that that demonstrate how to use assert.? Chapter#19(The Applet Classes) Q# 114. 113 113 Write a program that demonstrates Applet Skelton. 113 Q# 115. Write a program that demonstrate foreground and background ground color of and out put of String. 115 Q# 116. Write a program that demonstrate simple Banner Applet. 116 Q# 117. Write a program that demonstrate showStatus(). 118 Q# 118. Write a program that demonstrate passing parameter to Applet. 119 Q# 119. Write a program that display code and document bases. 121 Q# 120. Write a program that get code and display HTML file. 122 Chapter#20(Events Handling) 123 Q# 121. Write a program that demonstrate mouse event handler. 123 Q# 122. Write a program that demonstrate key event handler. 125 Q# 123. Write a program that demonstrate an adapter in event handling. 126 Q# 124. Write a program that show how to inner classes uses .? 127 Q# 125. Write a program that demonstrate Anonymous inner class. 128 Chapter # 1 (The Genesis of Java) Q# 1. Write a java program which show hallow word app! public class HelloWorldApp { //this line declare a class name and class definition starts from here public static void main(String args[]) { // line where program main function starts System.out.print(" Hello World! "); this line prints HelloWorldApp! } at this lime program main funcation starts } program where class end Chapter # 2 (An Overview Of Java) Q# 2. Write a java program to display a simple string. class example { // This line declare a class name & the class definition is start from here . public static void main(String a[]) { // This line begins the main() method. System.out.println(" this is a simple program."); //this print this string followed by newline. 4|Page
  • 6. JAVA & OOPS Manual } } // end of main program //end of class Description : This is a simple java program in which show a string (" this is a simple program.") OUTPUT: Q# 3. Write a simple java program to display a string and perform a simple multiplication. class Example_2{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ // This line begins the main() method. int num; // this declares a variable called num. num=100 ; // this assign num the value 100. System.out.println("this is num: " + num); // this line show output of num //This line outputs the string and number. num=num * 2; // this line show value of num is equals to num multiply by 2 System.out.print("The value of num * 2 is "); //This line outputs the string "The value of num * 2 is " System.out.println(num); // this is a output line which give the value of num //This line output the value store in variable num followed by a new line. } } // end of main prograam // end of class DESCRIPTION:In this program we Ist creat a class with name of example2, after this we initialize num and give the value and show value of num in form of output,after this we declare ―num = num * 2‖And than show thevalue of num after multiplying by 2. OUTPUT: Q# 4. Write a program which demonstrate the if statement.: class IfSample{ // This line daclare a class of name ifSample 5|Page
  • 7. JAVA & OOPS Manual public static void main(String a[]){ // This line begins the main() method. int x, y; // this declares a variable called num. x=10; // this assign x the value 10. y=20 ; // this assign y the value 20. if(x<y) // in this line we give if Statement that ifx is less than y than give System.out.println("x is less than y"); // This line outputs the string. x= x*2; // multiply x by 2. if(x==y) System.out.println("now x is equal to y"); show a string // this is a output line which x= x*2; //multiply again by 2 if(x>y) System.out.println("now x is greater than y"); show a string // this is a output line which } //end of main program } // end of a class DESCRIPTION: This java program in which we ist make a class of name after making class we initialize x and y and give them value , than we give if condition in which we say if value of x is less than y than show ―x is less than y‖ , Now x multiply by 2 , Now we also give if condition x is equals to OUTPUT: Q# 5. write a program to demonstrate the for loop. class ForTest{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ // This line begins the main() method. int x; //daclare a integer x. for(x=0; x<10; x=x+1) //for loop start System.out.println("this is x: " + x); } // end of main program 6|Page // this line show value of x
  • 8. JAVA & OOPS Manual } // end of a class DESCRIPTION: In this line I ist initialize x and then give for loop and then show the output line in which I show output line and after this our main program end. OUTPUT: Q# 6. Write a program which contains block of code in “for” loop definition. class blocktest{ // this line declare class name public static void main (String arg []){ // this is the main line were program main funcation starts int x,y; // in this line x and y is declaer as as int variable * y=20; in this line we give thie value of y * for(x=0;x<20;x++) { this is a for loop that code run 20 time* System.out.println("this is x: " + x); this line give us value of x 20 time * System.out.println("this is y :" + y); this line give us value of y 20 time * y=y-2;} this line show out put of y is given by this formula * } this is the end of main } this is the end of class DESCRIPTION: in this we first declare a class as name blocktest, than we initialize x and y, and than we give value of y; after this we initialize for loop and then it give out put line which show x and y, and in program we declare value of y OUTOUT: 7|Page
  • 9. JAVA & OOPS Manual Chapter # 3: (Data type, Variable and Arays) Q# 7. Write a program to compute distance light travel in 1000 days using long variables. class Light{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ int lightspeed; // This line begins the main() method. //daclare a integer name lightspeed. long days; //daclare a variable days of datatype long. long seconds, distance; lightspeed=186000; //aproximate speed of light n miles per second. days=1000; //specify number of days. seconds=days*24*60*60; //convert to seconds. distance=lightspeed * seconds; //compute distance System.out.print("In " + days); System.out.print(" days lightwill travel about "); System.out.println(distance + " miles."); //print distance in miles. } } DESCRIPTION: This program calculate the speed of light in 1000 days. We take long variable to store the speed of light because inttype is not large enough to hold the desire value. The range of a long is quite large. This makes it useful whrn big whole numbers are needed. 8|Page
  • 10. JAVA & OOPS Manual OUTPUT: Q# 8. Write a program that calculates the area of a circle, use data type of double. CODE: class Area{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ // This line begins the main() method. double pi, r, b; // daclere three variable of type double. r=12.3993; //radius of circle. pi=3.1416; // value of pi b=pi*r*r; // Declare area formula. System.out.println("Area of the circle is " + b); //This print the area of circle. } } DESCRIPTION: In this program first declare a class name Area and show main program and than I declare pi r and b and delare value of r and pi after we declare how area found after this in system.out.println line it gives us the value of area OUTPUT: Q# 9. Write a program which demonstrate the char data type. CODE: class CharDemo{ // Declare class name as CharDemo. public static void main(String a[]){ // This line begins the main() method. 9|Page
  • 11. JAVA & OOPS Manual char ch1, ch2; // daclere two character variable. ch1=88; //Declare value of ch1 ch2='Y'; //Declare ch2 is Y System.out.print("ch1 and ch2: "); //print the string. System.out.println(ch1 + " " + ch2); //display both character. } } DESCRIPTION: In this program I take two character variable ch1assigned the value 88 which is the ASCII (and UNICODE) value that corresponds to the letter X. At the end we display both character value. The program displays the following output. OUTPUT: Q# 10. Write a program in which char variables behave like integers. CODE: class CharDemo2{ // This line daclare a class name and a class start from here . public static void main(String a[]){ // This line begins the main() method. char ch1; // daclere a character variable. ch1='X'; // give a charter to ch1 System.out.println("ch1 contains " + ch1); //this line print ch1 ch1++; //increment ch1. System.out.println("ch1 is now " + ch1); //print incremented character. } } //end of main funcation //end of class DESCRIPTION:In this program I ist make a class of name Chardemo2. In second line main funcation of programme start, after this I initiliaze and declare ch1,after this we print ch1 , then increment in value of ch1 and print value of ch1 OUTPUT: 10 | P a g e
  • 12. JAVA & OOPS Manual Q# 11. Write a program which demonstrate dynamic initialization. class Square{ // This line daclare a class ‖Square‖& the class is start from here . public static void main(String a[]){ // This line begins the main() method. double x=3.0, y=4.0; // Initiallize two double variables. double z=Math.sqrt(x*x + y*y); //z is initialized and declare calue of z System.out.println("Hypotenuse is " + c); } } //this line print value of Hypotenus // end main funcation end of class name DESCRIPTION: This program computes the length of the hypotenuse of right triangle given the length of two opposing sides. OUTPUT: Q# 12. Write a program that demonstrates the Boolean type values. CODE: class BoolTest{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ // This line begins the main() method. boolean b; // daclere a boolean variable. b=false; //Initialize b is false. System.out.println("b is " + b); // display b . b=true; //now b initialize is true. 11 | P a g e
  • 13. JAVA & OOPS Manual System.out.println("b is " + b); // display it. if(b) System.out.println("this is executed. "); // if condition is true then this string is print b=false; // b again false. if(b) // initialize if condition System.out.println("this is not executed. "); //this line is not display because b is false. System.out.println("10 > 9 is " + (10>9)); //out come relational operator Boolean which is true } //end of main function } // end of a class DESCRIPTION: I OUTPUT: Q# 13. Write a program which show the effect of nested scopes. CODE: class Scope{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ // This line begins the main() method. int x; // initialize x x=10; //Declare value of x. if(x==10){ //start new scope int y=20; //this y is known only to this block. System.out.println("x and y : " + x + " " + y); // This line show the output x=y*2; // this line show x equals to y*2 12 | P a g e
  • 14. JAVA & OOPS Manual } // this line show the finishing of block //y=100; // error! y not known here. System.out.println("x is " + x); this line show the output output } // this line show the end of program } this line show the end of class DESCRIPTION:This program shows the scope of any variable. As the comment indicate we Ist declare the class and then initialize and delare OUTPUT: Q# 14. Write a program to demonstrates the lifetime of a variable. class LifeTime{ // This line daclare a class name public static void main(String a[]){ // This line begins the main() method. int x; // daclare a variable x. for(x=0; x<3; x++){ //Declare for loop int y=-1; //y is initialized each time block is entered. System.out.println("y is: " + y); this is a output line y=100; Give value to y System.out.println("y is now: " + y); // this is the output line } // end of loop function } // this line show the main program } DESCRIPTION:In this program we First declare declare a class name oLifetime than main program start , I declare first x and and than declare for loop ; after this after this I initilaze y and print value of y; after again give value to y and print again value of y OUTPUT: 13 | P a g e
  • 15. JAVA & OOPS Manual Q# 15. Write a program that convert one data type in to another data type class Conversion { // Declare class name public static void main(String args[]){ of program start from here int i = 257; byte b; //daclre main line line of program main body //Initialize and Declare i //initialize b double d = 323.42; //Initialize and Declare d System.out.println("n Conversion of int tom byte."); b = (byte) i; // print string line // convertion of data type System.out.println(" i and b is "+ i + " " + b); // print value of I and b System.out.println( "n Conversion od double to int " ); //print string line i = (int) d ; // convertion of data type System.out.println("d and i " + i + " " + d ); // print value of I and d System.out.println("n Conversion of double to byte"); b = (byte) d; // print string line // convert value of b in to byte System.out.println("d and b " + d + " " + b); print value of b and d } // end of main program } // end of class Description: In this program first make a class and write it main main method after intiliaze I, b, d. after we conert one data type in to another data type and prind their value Output: 14 | P a g e
  • 16. JAVA & OOPS Manual Q# 16. Write a program that multiply and add different data type variable. class Promote { // class name start from here public static void main (String args [ ] ) { // Main body of program start from here byte b = 42; //Initialize and declare b char c='a'; //Initialize and declare c short s = 1024;//Initialize and declare s int i = 50000; //Initialize and declare I float f = .67f; //Initialize and declare f double d = .1234; //Initialize and declare d double result = (f * b) + (i / c) + (d * s); //Initialize and declare result System.out.println((f * b) + " " + (i / c) + " "+ (d * s)); System.out.println("result = " + result); } } // print line // print result // end of main programme // end of a class Description: In this program I first make class and write its main method after this I declare and initialize b, c, s, I, f, d. after this initialize result and give a value after we print our result Output: Chapter # 4 (Operator) Q# 17. Write a program which demonstrate the arithmetic operator class BasicMath{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ // This line begins the main() method. System.out.println("Integer Arithmetic"); //arthmetic using integers int x=1+1; //store 2 in variable x int b=x * 3; //x multiply a by 3 and store in b. int c=b/4; //b divide b by 4 and store in c. int d=c - x; // c minus x and store in d int e=-d; // minus of d is System.out.println("a = " + x); // print value of a System.out.println("b = " + b); // print value of b 15 | P a g e
  • 17. JAVA & OOPS Manual System.out.println("c = " + c); // print value of c System.out.println("d = " + d); // print value of d System.out.println("e = " + e); // print value of e System.out.println("nFloating Point Arithmetic"); // Arthmetic using doubles double da=1+1; //store 2 in variable da double db=da * 3; //multiply da by 3 and store in db. double dc=db/4; //divide db by 4 and store in dc. double dd=dc - da; // value of dc minus da store in dd double de=-dd; // value of dd store in de System.out.println("da = " + da); // print value of da System.out.println("db = " + db); // print value of db System.out.println("dc = " + dc); // print value of dc System.out.println("dd = " + dd); // print value of dd System.out.println("de = " + de); // print value of de } // end of main method } // end of class DESCRIPTION: in this programme first make a class and write its main method, after intilize and declare a, b, c, d, e. and da, db, dc, dd, and print their value . OUTPUT: Q# 18. Write a programme that demonstrate modulus operator class modulas{ // class name public static void main(String arg []){ int x=67; double y=67.25; //initialize and declare x //initialize and declare y System.out.println("x mod 10 = " + x%10 ); System.out.println("y mod 10 = " + y%10 ); } // end main method 16 | P a g e // main method //print modulus of x //print modulus of y
  • 18. JAVA & OOPS Manual } end class Description:in this programme first make a class and write its main method than initialize and declare c and y and print them. Output: Q# 19. Write a program in which various assignment operator is used. //Demonstrate several assignment operator class OpEquals{ // class name public static void main(String a[]){ // This line begins the main() method. int i=1; // declare i int b=2; // Declare b int c=3; // Declare 3 i+=5; // increment 5 in i. b*=4; //multiply b by 4 than again store in b. c+=i*b; //I multiply with b and add in c c%=6; // modulus of c. System.out.println("i = " + i); // print value of i System.out.println("b = " + b); // print value of b System.out.println("c = " + c); // print value of c } } end main method // end the class Description: in this programme first make a class and write its main method initialize and declare a, b , c and again declare a, b, c and print their value Output: 17 | P a g e
  • 19. JAVA & OOPS Manual Q# 20. Write a program which shows the function of increment(++). class InDec{ // Class name and class start from here. public static void main(String a[]){ // main method of program line. int a=1; // Initialize1 in variable a. int b=2; // Initialize 2 in variable b. int c, d; // daclare two variables c & d. c=++b; // increment in b than store in c. d=a++; // store value of a in d. than increment in i. System.out.println("a = " + i); //this print the value i. System.out.println("b = " + b); //this print the value b. System.out.println("c = " + c); //this print the value c. System.out.println("d = " + d); //this print the value d. } } DESCRIPTION: In this program two variable initialized and other two variables are initialized by increment in values of pervious two variables. OUTPUT: Q# 21. Write a programme left shifting the byte value. class ByteShift { // class name public static void main (String args [ ] ) { from here byte a = 64, b; int i; //Declare a // declare i i = a<<2; b = (byte) (a << 2); 18 | P a g e //Decare i is lessthan 2 // convert data type // main body of programme start
  • 20. JAVA & OOPS Manual System.out.println("orignal value of a: " +a); //print value of a System.out.println("i and b:" + i + " " + b); } // print value of i and b // main of main programme } //end of class Description: Output: Q# 22. Write a programme that demonstrate the Boolean logical operator class BoolLogic { // calss name public static void main (String args[]) { // main method of programme boolean a=true; // Declare a boolean b=false; //Declare b boolean c=a | b; //Declare c boolean d=a & b; //Declare d boolean e=a ^ b; //Declare e boolean f=(!a & b) | (a & !b); boolean g= !a; //Declare f //Declare g System.out.println(" a = " + a); //Print value of a System.out.println(" b = " + b); //Print value of b System.out.println(" a|b = " + c); //Print value of c System.out.println(" a&b = " + d); //Print value of d System.out.println(" a^b = " + e); //Print value of e System.out.println(" (!a & b) | (a & !b) = " + f); System.out.println(" !a = " + g); } } //Print value of g //main body of programme ended // class ended Description: Output: 19 | P a g e //Print value of f
  • 21. JAVA & OOPS Manual Q# 23. Write a program which demonstrates the ? operator. class Ternary{ // Declare class name public static void main(String a[]){ // Main body of programme start from here. int i, k; // daclare two variables i & k. i=10; // Initialize i k= i<0 ? -i : i; //get absolute value of i. System.out.print("Absolute value of "); // print string line System.out.println(i +" is "+ k); //this print the value of i and k. i=-10; // Initialize k= i<0 ? -i: i; // get absolute value of i. System.out.print("Absolute value of "); // print string line System.out.println(i +" is "+ k); //this show the value of i and k. } // Main body of programme ended } // class ended DESCRIPTION:This program shows the functionality of ? operator. In this programme ist declare two variable and initialize them than print their value after this again initialize both variable and print their value. OUTPUT: Chapter # 5 (Control Statement) Q# 24. Write a programme that demonstrate if-else statement class IfElse{ // This line daclare a new class & the class defination is start. public static void main(String a[]){ // This line begins the main() method. 20 | P a g e
  • 22. JAVA & OOPS Manual int month=4; //April String season; //daclare a string name season. if(month==12 || month==1 || month==2) season= "winter"; //if above condition is true than print winter. else if(month==3 || month==4 || month==5) season= "Spring"; //if above condition is true than print Spring. else if(month==6 || month==7 || month==8) season= "Summer"; //if above condition is true than print Summer. else if(month==9 || month==10 || month==11) season= "Auntumn"; //if above condition is true than print Auntumn. else season="Bogus Month"; // System.out.println("April is in the " + season + "."); // this print the season of month. } } // end of main programme // end of class DESCRIPTION: This java program demonstrates if-else-if statements. The if statements are executed from the top down. In above if one of the condition is true the statement associated with that if is executed and rest of the ladder is bypassed. If none of the condition is true then final else statements is executed. OUTPUT: Q# 25. Write a programme that show simple example of switch class SwitchSample{ // class definition start from here. public static void main(String a[]){ // Main body of programme start from here for(int i=0; i<6; i++) // for loop start. switch(i) { //start body of switch statment case 0: //if i=0 than this case is executed. System.out.println("i is zero."); 21 | P a g e
  • 23. JAVA & OOPS Manual break; // this stop the execution and end the program case 1: //if i=1 than this case is executed. System.out.println("i is one."); break; // this stop the execution and end the program case 2: //if i=2 than this case is executed. System.out.println("i is two."); break; case 3: // this stop the execution and end the program //if i=3 than this case is executed. System.out.println("i is three."); break; default: // this stop the execution and end the program. //if i is greater than t than default statment executed. System.out.println("i is greater than 3."); } } } DESCRIPTION: This java program demonstrates the switch statement. In above program as you can see each time through the loop the statements associated with the case constant that matches i are executed. All others are bypassed. After i is greater than 3 no case statements match so the default statement is executed. OUTPUT: Q# 26. Write a programme that show in switch break statements are optional class MissingBreak{ // class name . public static void main(String a[]){ // Main body of programme start from here. for(int i=0; i<8; i++) // for loop start. switch(i){ //start body of switch statment case 0: case 1: case 2: 22 | P a g e
  • 24. JAVA & OOPS Manual System.out.println("i is less than 3"); break; // print the string // this line break the loop case 3: case 4: System.out.println("i is less than 5"); break; default: // this line break the loop //if no condition is true then this is executed. System.out.println("i is 6 or more"); } } } // print the string // print the string // for loop ended // main body of programme ended // class ended Description: In this program we see that if break statements are not used then the program will not stop and it print the statements following by true case. In above case 0,1 and 2 a single statement is executed 3 then break statement is executed and control is bypassed. At the end if no condition is true then the default statement is executed. Output: Q# 27. it. Write a programme that show the season when any month is given to class Switch { // class name declare public static void main(String args[]) { // public main method declared int month = 4; // variable (month) is declared of int type, value is 4 String season; // another variable (season) is declared switch (month) { //body of switch satement start case 12: case 1: case 2: season = "Winter"; break; 23 | P a g e // break statement use to jump from the switch
  • 25. JAVA & OOPS Manual case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; default: season = "Bogus Month"; } //end of switch statement System.out.println("April is in the " + season + "."); // here show the final output of program } } //main body of programme ended // class ended Description:In this programme first declare a class name than write its main method than declare month and season after this declare switch statement and then write the cases .after this print the season of April. Output: Q# 28. Write a programme that demonstrate the while loop //Demonstrate the while loop 24 | P a g e
  • 26. JAVA & OOPS Manual class While { // Declare class name public static void main (String args [ ] ) { // main body of class start from here int n = 10; // declare n while(n > 0) { // start while loop System.out.println(―tick‖ + n) ; n--; } } } //print value of n // Decrement n // loop body ended // main body ended //class ended Description: In this programme first make class and then main body of programme start and then declare while loop after this print the value of n after decrement the n. Output: Q# 29. Using while loop write a program which display midpoint of two numbers. class NoBody { // class name is declared as Nobody public static void main(String args[]) { // public main method declared int i, j; // two variables i & j are declared i = 100; j = 200; // intialize i and j. // find midpoint between i and j while(++i < --j) ; // Declare while loop System.out.println("Midpoint is " + i); // show output } } // main body of programme start from here // class ended Description: 25 | P a g e
  • 27. JAVA & OOPS Manual In this programme first declare a class name as NoBody then main body of programme start than declare I and j after this giv value to I and j and declare while loop after this print value of I. Output: Q# 30. Write a programme that demonstrate dowhile class DoWhile { // Class name is as DoWhile public static void main(String args[]) { // public main method is start. int n = 10; // variable (n) is declared of int type, value is 10. do { // do whilel loop is started here. System.out.println("tick " + n); n--; // print value of n // decrement in n. } while(n > 0); // this loop is stop when n is equal to or less than zero. } // main body programme ended } //class ended Description: In this programme first make a class and then write its main method after this declare n equals to ten than apply do and print line after write while condition , In this programme do while loop is used . Q# 31. Write a program using do-while to process a menu selection. class Menu { public static void main(String args[]) throws java.io.IOException { input errors char choice; do { 26 | P a g e // This line is used for for handling exception and //Declare char as a choice //
  • 28. JAVA & OOPS Manual System.out.println("Help on:"); // print Help on: System.out.println(" 1. if"); // print 1.if System.out.println(" 2. switch"); // print 2.Switch System.out.println(" 3. while"); //print 3.While System.out.println(" 4. do-while"); // print 4. DO while System.out.println(" 5. forn"); //print 5 for n System.out.println("Choose one:"); // print choose one choice = (char) System.in.read(); // char are read from this method } while( choice < '1' || choice > '5'); // Apply while loop System.out.println("n"); switch(choice) { // Switch statement start case '1': // this is condition one System.out.println("The if:n"); // print the if:n System.out.println("if(condition) statement;"); // print if condition statement System.out.println("else statement;"); //print else statement break; // This line break the switch statement case '2': //This is condition 2 System.out.println("The switch:n"); // print the switch System.out.println("switch(expression) {"); // print switch System.out.println(" case constant:"); // print case constant expression System.out.println(" statement sequence"); // print statement sequence System.out.println(" break;"); System.out.println(" // // print break ..."); // print dotted line System.out.println("}"); print ending braes break; // This line break the switch statement case '3': // This is condition three System.out.println("The while:n"); //print the while System.out.println("while(condition) statement;"); // print while condition statement 27 | P a g e
  • 29. JAVA & OOPS Manual Break; //This line break the switch statement case '4': // this is condition four System.out.println("The do-while:n"); // this print the which in inverted commas System.out.println("do {"); // this print the which in inverted commas System.out.println(" statement;"); // this will print Staement System.out.println("} while (condition);"); // this line print} while (condition); break; // this ill break the switch statement case '5': // this is choice 5 System.out.println("The for:n"); //print the for System.out.print("for(init; condition; iteration)"); print for(init; condition; iteration) System.out.println(" statement;"); break; // print Statement } } } // switch statement ended // main body of programme ended // class ended DESCRIPTION: In this program we first make a class and then write main body of programme in which we print some condition than call System.in.read()ask input from user at run time after this we give detail of our choice which is given by user. Output: 28 | P a g e
  • 30. JAVA & OOPS Manual Q# 32. for Write a programme that demonstrate loop control veriable inside the class ForTick { // class start from here public static void main (String args [] ) { // main body of programme // here n is declared inside the loop For(inr n =10; n>0;n--) { // Define for loop System.out.println(―tick ‖ + n); } } } // this brace show end of loop body // this brace show end of main body of programme // this brace show end of class Description: In this programme first make a class and then start main body of programme than declare for loop and print out put Q# 33. Write a program in which for loop is used and find the prime number by using this loop. class FindPrime { //class name start . public static void main(String args[]) { // This line begins the main() method. int num; //daclare a variable of type int. boolean isPrime = true; //initialize a boolean variable. num = 30; // give value to num for(int i=2; i <= num/2; i++) { //for loop body is started. if((num % i) == 0) { //this find prime number. isPrime = false; // declare isPrime is equals to false break; // if condition stop } // if condition ended } loopbody ended if(isPrime) 29 | P a g e
  • 31. JAVA & OOPS Manual System.out.println("Prime"); // print prime else //else is uses System.out.println("Not Prime"); // print Not Prime } } // main body of programme ended // this brace show end of class DESCRIPTION: In this program for loop is used. Take an integer 30 and take modulus with 2 if it is equal to zero it is prime otherwise it display not prime. As we know 30 is not aprime number it display not prime. It display the following output. Output: Q# 34. Write program in which two variable used to control the iteration of for loop class Sample { // class name start public static void main(String args[]) { // This line begins the main() method. Int x, y; //declare two integer variables. Y = 4; // give value to 4 for(x=1; x<y; x++) { // for initialize declare System.out.println(―x = ― + x); //this print the value of x. System.out.println(―y = ― + y); //this print the value of y. y--; // Decrement y } // for loop ended } //main body of programme ended } // class ended DESCRIPTION: In this program make class than start main method after this x and y after this for loop is started and then print the value of x and y and decrement y. Output: 30 | P a g e
  • 32. JAVA & OOPS Manual Q# 35. Write program in which two variable used to control the iteration of for loop using for comma class comma { // class body start from here public static void main (String args []) { Int a , b; // main body of programme start from here // Declare a aand b For(a=1, b=4; a<b; a++, b--) { // use for loop System.out.println(―a= ‖ = + a) ; // print value of a System.out.println(―b= ― + b); // print value of b } } } loop body ended main body ended class ended Description: In this programme first declare a class than write main method and initiliaze a and b and declare for loop after this print value Output: Q# 36. Write a for loop program in which initialization and iteration is moved out of the for loop. class ForVar{ // class name start from here public static void main(String args[]) { // This line begins the main() method. int n; // declare n boolean done= false; //initialize a boolean variable. n=0; // put n equals to zero for(; !done;){ ///this is infinte loop .no condition & iteration System.out.println("n is " + n); // print value of n if(n==5) done=true; // declare if statement n++; //if above condition is true than increment in n. } // end of loop } // end of main body } // end of class DESCRIPTION: In this program the for loop is empty e.g no condition and iteration. Q# 37. Write a program of nested for loop. class Nested { // This line daclare a class name public static void main(String args[]) { // This line begins the main() method. 31 | P a g e
  • 33. JAVA & OOPS Manual int i, j; //daclare two integer variable. for(i=0; i<10; i++) { //first loop for(j=i; j<10; j++) //2nd loop System.out.print("."); // this line print dotted line System.out.println(); } // loop body ended } // main body of program ended } // class ended DESCRIPTION: This is the program in which nested for loop is used. Output: Q# 38. Write a program in using break to exit a loop. class BreakLoop { // This line daclare a new class & the class defination is start. public static void main(String args[]) { // This line begins the main() method. for(int i=0; i<100; i++) { //loop body start. if(i == 10) break; // terminate loop if i is 5 System.out.println("i: " + i); ///print value of i. } System.out.println("Loop complete."); //Print this string. } } DESCRIPTION: In this program for loop is designed to run from 0 to 99 the break statement causesit to terminates when i equals 10. Output: 32 | P a g e
  • 34. JAVA & OOPS Manual Q# 39. Write a program in which using a break to exit a while loop. class BreakLoop2 { // This line daclare class name public static void main(String args[]) { // This line begins the main() method. int i = 0; // declare I =0 while(i < 100) { //while loop body start. if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); //print value of i. i++; } System.out.println("Loop complete."); } } DESCRIPTION: the break statement can be used in any of java’loop. In above while loop is used and loop is designed to run from 0 to 99, the break statement causes it to terminates early when i equal 10. OUTPUT: 33 | P a g e
  • 35. JAVA & OOPS Manual Q# 40. Write a program in which using a break to exit a while loop. class BreakLoop3 { // This line daclare a new class & the class defination is start. public static void main(String args[]) { // This line begins the main() method. for(int i=0; i<3; i++) { //first for loop start. System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) { //2nd loop start. if(j == 10) break; // terminate loop if j is 10 System.out.print(j + " "); //print value of j. } System.out.println(); } System.out.println("Loops complete."); } } DESCRIPTION: In this program first loop run 3 times and internal loop is designed to run 0 to 99 but it stop due to break statement when j equals 10. This program shows the following output. OUTPUT: Q# 41. Write a program in which break is used like go to statement. class Break { // This line daclare a new class & the class defination is start. public static void main(String args[]) { // This line begins the main() method. boolean t = true; //initialize a boolean variable. first: { //body of first block start second: { //body of 2nd block start third: { //body of third block start System.out.println("Before the break."); 34 | P a g e
  • 36. JAVA & OOPS Manual if(t) break second; //break out of second block. System.out.println("This won't be execute."); } System.out.println("This won't be execute."); } System.out.println("This is after second block."); } } } DESCRIPTION: This is the program in which break statement work like a goto. In this statement of third block print after this second block is break and statement of first block is executed. OUTPUT: Q# 42. Write a program that used for a labelled break statement to exit from nested loop. class BreakLoop4 { // class definition starts public static void main (String args []) { outer: for(int i = 0; i<3 ; i++) { // main body of program start from here // for loop declared System.out.print("Pass" + i + ": "); // print value of for(int j=0; j<100;j++) { if (j == 10) break outer; // declared if condition j equals to 10 // exit both loops System.out.print(j + " "); // print j } //second loop body ended System.out.println("This will not print"); 35 | P a g e // Again for loop declared
  • 37. JAVA & OOPS Manual } // first loop body ended System.out.println("Loops Complete."); // print loop completed } } // main body ended // class ended Q# 43. Write a program that uses continue to cause two number. class Continue { // clss defination start public static void main (String args [ ] ) { for (int i = 0; i < 10; i++ ) { // main body of program start // for loop started System.out.print(i + " "); // print value of i if(i%2 == 0) continue; // print modulas of 2 System.out.println(" "); // print nothing } } } //loop body ended // main body of program ended // class ended Description: In this program first make a class than make main method than initialize for loop than print I after get modulas and print Output: Q# 44. Write a program that uses continue to print a triangular multiplication of table for 0 through 9. class ContinueLable { // class definition start public static void main (String args [] ) { outer: for(int i=o; i<10; i++) for(int j=0; j<10; j++) if (j > i) { //main body of program start from here { for loop declare { again for loop declare // if j is greater than i System.out.println(); continue outer; } 36 | P a g e // print nothing // print // if condition finished
  • 38. JAVA & OOPS Manual System.out.print(" " + (i * j)); } } // print value of i*j // first for loop declared // second for declared System.out.println(); } // main body of program ended } // class ended Description: In this program Output: Q# 45. Write a program that demonstrates return. class Return { // class name declared public static void main (String args []) { boolean t = true; t declared as a boolean type System.out.println("Before the return. "); if(t) return; // main body of program start // print before the return // return to caller System.out.println("This Won't execute. "); // print this won’t execute } } // main body of program ended class ended Description: In this program first make a class name than write main method after declare t as Boolean type after this print string after this if condition apply after print this won’t execute. Output: 37 | P a g e
  • 39. JAVA & OOPS Manual Chapter # 6 (Introducing classes) Q# 46. Write a program that call this file BoxDemo.java. class Box { double width; double height ; double depth; } class BoxDemo{ public static void main (String args [ ] ){ Box mybox=new Box (); double vol; mybox.width=10; mybox.height=15; mybox.depth=18; vol=mybox.width*mybox.height*mybox.depth; System.out.println("Volume of Box is " + vol ); } } Description: In this program Output: Q# 47. Write a program that declares two Box object. class Box { double width; double height; double depth ; } class BoxDemo2{ public static void main (String args [] ) { 38 | P a g e
  • 40. JAVA & OOPS Manual Box mybox = new Box (); Box mybox2 =new Box (); double vol; mybox.width=10; mybox.height=20; mybox.depth=15; mybox2.width=10; mybox2.height=15; mybox2.depth=18; vol=mybox.width*mybox.height*mybox.depth; System.out.println(" Volume of Box is " + vol ); vol=mybox2.width*mybox2.height*mybox2.depth; System.out.println(" Volume of Box is " + vol ); } } Description: Output: Q# 48. Write a program that includes a method inside the box class. class Box { //declare class name double width; // initialize width double height; // initialize height double depth; // initialize depth void volume ( ) { // declared volume method System.out.println("Volume of Box is :"); //print string System.out.println(width*height*depth); print volume } // end of volume method } // end of class class BoxDemo3{ // declare class name public static void main (String args [ ]) { Box mybox=new Box (); 39 | P a g e // main body of program start // declare a memory of for new box mybox
  • 41. JAVA & OOPS Manual Box mybox2=new Box (); // declare a memory of for new box mybox //assign value to mybox’s instance variable mybox.width=15; // give value of heightof second box mybox.height=18; // give value of heightof second box mybox.depth=23; //give value of depthof second box //assign different value to mybox2’s instance variable mybox2.width=10; // give value of width of second box mybox2.height=13; // give value of heightof second box mybox2.depth=15; //give value of depthof second box mybox.volume(); //display the volume of first box mybox2.volume(); //display the volume of Second box } } Description: Output: Q# 49. Write a program that volume () returns the volumeof a box class Box { double width; double height; double depth; double volume() { return width * height * depth; } } class BoxDemo4{ public static void main (String args [ ]) { Box mybox1=new Box (); Box mybox2=new Box (); double vol; 40 | P a g e
  • 42. JAVA & OOPS Manual mybox1.width=15; mybox1.height=18; mybox1.depth=23; mybox2.width=10; mybox2.height=13; mybox2.depth=15; vol=mybox1.volume(); // declare vol System.out.println("Volume of mybox1 is:" + vol); vol=mybox2.volume(); // print volume of myBox1 // declare vol System.out.println("Volume of mybox2 is: " + vol); mybox2 } // print volume // ending brace of main body } // ending brace of main class Description: In this program first make a super a class class and in which declare widthheight and depth after this make a volume method after this make main class in which our main method is call after this declare mybox1 and mybox2, after this declare vol after this assign values different values to mybox1 and mybox2, after this print volume of box 1 and 2. Output: Q# 50. Write a program that use as parameterized method class Box { // declare class name double width; // declare width double height; // declare height double depth; // declare depth double volume() { // declare volume function return width * height * depth; // this line return value of volume } void setdim(double w, double h, double d ) { width=w; 41 | P a g e //declare width // setdim method initialize
  • 43. JAVA & OOPS Manual height=h; // declare h depth=d; // declare depth } } // ending brace of stdim // ending brace of class class BoxDemo5{ //Declare class name public static void main (String args [ ]) { // main body of program Box mybox1=new Box (); // Declare myBox1 Box mybox2=new Box (); // Declare mybox2 double vol; // Declare vol mybox1.setdim(10, 16, 19 ); // declare value of mybox1 mybox2.setdim(9, 10,15); // declare value of mybox2 vol=mybox1.volume(); // Initialize vol System.out.println("Volume of mybox1 is " + vol); vol=mybox2.volume(); // Initialize vol System.out.println("Volume of mybox2 is " + vol); } // print volume of mybox1 // print volume of mybox2 // ending brace of main body } // ending brace of class Description: Output: Q# 51. box. Write a program that use a constructor to initialize the dimension f a class Box { double width; double height; double depth; Box( ) { System.out.println("costructing box is "); width=17; height=19; depth=15; 42 | P a g e
  • 44. JAVA & OOPS Manual } double volume() { return width * height * depth; } } class BoxDemo6{ public static void main (String args [ ] ){ Box mybox1=new Box(); Box mybox2=new Box(); double vol; vol=mybox1.volume(); System.out.println("volume is " + vol); vol=mybox2.volume(); System.out.println("volume is " + vol); } } Description: Output: Q# 52. Write a program that uses a parameterized constructor to initialize the dimension. class Box { double width; double height; double depth; Box(double w, double h, double d ) { width=w; height=h; depth=d; } 43 | P a g e
  • 45. JAVA & OOPS Manual double volume() { return width * height * depth; } } class BoxDemo7{ public static void main (String args [ ] ){ Box mybox1=new Box(17,19, 23); Box mybox2=new Box(24, 27, 30); double vol; vol=mybox1.volume(); System.out.println("volume is " + vol); vol=mybox2.volume(); System.out.println("volume is " + vol); } } Description: Output: Q# 53. Write a program that defines an integer stack that can hold 10 values. class Stack { int stack [] = new int [10]; int tos; Stack ( ) { // Initialize top-of-stack tos = -1; } void push (int item) { // push an item on to stack if (tos == 9) System.out.println("Stack is full."); else 44 | P a g e
  • 46. JAVA & OOPS Manual stack[++tos] = item; } int pop ( ) { // pop an item from stack if (tos < 0) { System.out.println("Stack underflow"); return 0; } else return stack[tos--]; } } class TestStack { public static void main (String args [ ]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); for(int i =0 ; i < 10; i++) mystack1.push(i); // push some number on to stack for (int i = 10; i<20; i++) mystack2.push(i); // push some number on to stack System.out.println("Stack my skack1 :"); for (int i = 0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack my skack2 :"); for (int i = 0; i<10; i++) System.out.println(mystack2.pop()); } } Description: In this program first make a class name as stack after this declare Stack and tos . after this I make a constructor in which I initialize top-of-stack than make push method in which define if tos equals to 9 than show shack is ful otherwise push another number. After this declare pop method in which define if tos lessthan 0 than show stack underflow and ant return 0 otherwise decrease number. After this make a main class and in main class declare two Object mystack1 and mystack2 after this declare for loop than print output. Output: 45 | P a g e
  • 47. JAVA & OOPS Manual Chapter # 7 (A Closer Look at Methods and Classes) Q# 54. Write a program that demonstrates method overloading. class OverloadDemo{ void test() { // declare class name // declare test method System.out.println("No parameters"); } // print no parameter // ending brace of test method void test (int a ) { // declare test method again System.out.println("a is : " + a ); } // print value of a // ending brace of test method void test (int a, int b) { // declare test method again System.out.println("a and b is " + a +" " + b); } // print value of a and b // ending brace of test method double test(double a) { // declare test method again System.out.println("double a : " + a); return a*a; } // print value of a // return value of a*a // ending brace of test method } // ending brace of class class Overload{ // declare class name public static void main (String args [ ] ){ OverloadDemo ob = new OverloadDemo (); 46 | P a g e // main method call // declare new object as ob
  • 48. JAVA & OOPS Manual ob.test(); // class test method ob.test(10); // class test method ob.test(10 , 20 ); // class test method double result = ob.test(123.456); // declare result System.out.println ("Reslult of ob.test(123.456) is :" + result ); value of result } } // print // ending brace of main body // ending brace of main class Description: In this program first declare class name than test name method define again and again . after this make a main class and after this make a new object ob after this call method function with object ob than initialize result after this print value of result. Output: Q# 55. Write a program that use overloaded method and convert a parameter into corresponding data type when compatible type of constructor is not available. class OverloadDemo{ void test() { System.out.println("No parameters"); } void test (int a, int b) { System.out.println("a and b is " + a +" " + b); } void test(double a) { System.out.println("Inside test (double) a : " + a); } } class Overload2{ public static void main (String args [ ] ){ OverloadDemo ob = new OverloadDemo (); int i = 88; 47 | P a g e
  • 49. JAVA & OOPS Manual ob.test(); ob.test(10, 20); ob.test(i); ob.test(123.456); } } DESCRIPTION: In this program as you can see that this program is same as previous one. But the difference is that we are calling a constructor which has one parameter of integer type but in the constructor overloading we has no one like this. At this time java automatically converts data type into most corresponding data type as here integer into double. Keep in mind that both have same number of parameters. OUTPUT: Q# 56. Write a program that shows the dimension of a box in various way. class Box { double width; double height; double depth; Box(double w, double h, double d ) { width=w; height=h; depth=d; } Box () { width=-1; height=-1; depth=-1; } Box(double len) { width=height=depth=len; } 48 | P a g e
  • 50. JAVA & OOPS Manual double volume () { return width*height*depth; } } class OverloadCons { public static void main (String args [ ] ) { Box mybox1=new Box(17,19, 23); Box mybox2=new Box(); Box mybox3=new Box(); double vol; vol=mybox1.volume(); System.out.println("Volume of box1 is :" + vol); vol=mybox2.volume(); System.out.println("Volume of box2 is :" + vol); vol=mybox3.volume(); System.out.println("Volume of box3 is :" + vol); } } Description: Output: Q# 57. Write a program that class Test{ // declare int a, b; Test(int i, int j ) { a=i; b=j; } boolean equals(Test o) { if 49 | P a g e
  • 51. JAVA & OOPS Manual (o.a == a && o.b == b ) return true; else return false; } } class PassOb { public static void main (String args [ ] ) { Test Ob1 = new Test( 100, 22 ); Test Ob2 = new Test( 100, 22 ); Test Ob3 = new Test( -1, -1); System.out.println("ob1 == ob2 " + Ob1.equals(Ob2)); System.out.println("ob1 == ob3 " + Ob1.equals(Ob3)); } } Description: Output: Q# 58. Write a program that shows the overloading of constructors. class Box { // declare class name double width; // declare width double height; // declare height double depth; // declare depth Box(Box ob ) { // make constructor width=ob.width; height=ob.height; depth=ob.depth; } // ending brace of constructor Box(double w, double h, double d ) { width=w; 50 | P a g e
  • 52. JAVA & OOPS Manual height=h; depth=d; } Box () { width=-1; height=-1; depth=-1; } Box(double len) { width=height=depth=len; } double volume () { return width*height*depth; } } class OverloadCons2 { public static void main (String args [ ] ) { Box mybox1=new Box(10,120, 15); Box mybox2=new Box(); Box mycube=new Box(7); Box myclone=new Box(mybox1); double vol; vol=mybox1.volume(); System.out.println("Volume of mybox1 is " + vol ); vol=mybox2.volume(); System.out.println("Volume of mybox2 is " + vol ); vol=mycube.volume(); System.out.println("Volume of mybox3 is " + vol ); vol=myclone.volume(); System.out.println("Volume of clone is " + vol ); } } 51 | P a g e
  • 53. JAVA & OOPS Manual Description: Output: Q# 59. Write a program that is passed by value. class Test { void meth (int i, int j ) { i *=2; j /=2; } } class CallByValue { public static void main (String args [ ] ) { Test ob = new Test ( ); int a = 15; int b = 20; System.out.println("a and b before call :" + a + " " + b ); ob.meth(a, b); System.out.println("a and b after call :" + a + " " + b ); } } Description: In this program we settle a method in a class named as test and then perform some operations on the variables in the method then call that method in the main function and display them using System.out.println() method. We can see that when we call parameters by value our operations will not perform on them. It just prints them as it is. Output: 52 | P a g e
  • 54. JAVA & OOPS Manual Q# 60. Write a program that is call by reference. class Test { int a, b; Test (int i, int j ) { a = i; b = j; } void meth(Test o ) { o.a *= 2; o.b /= 2; } } class CallByRef { public static void main (String args [ ] ) { Test ob = new Test (15, 20 ); System.out.println("a and b before call :" + ob.a + " " + ob.b ); ob.meth(ob); System.out.println("a and b after call :" + ob.a + " " + ob.b ); } } Description: : In this program we settle a method in a class named as test and then perform some operations on the variables in the method then call that method in the main function and display them using System.out.println() method. We can see that when we call parameters by reference our operations will perform on them. It prints them after operating on them according to the operators Output: Q# 61. Write a program that returning an object. class Test{ int a; Test(int i) { 53 | P a g e
  • 55. JAVA & OOPS Manual a=i; } Test incByTen () { Test temp = new Test (a+ 10 ); return temp; } } class Retob{ public static void main (String args [ ] ) { Test ob1 = new Test (2); Test ob2; ob2=ob1.incByTen(); System.out.println("ob1.a:" + ob1.a ); System.out.println("ob2.a:" + ob2.a ); ob2=ob2.incByTen(); System.out.println("ob2.a after Second increase :" + ob2.a ); } } DESCRIPTION: In this program we create a class and set a method in that class. In the method we add 10 in the object as required from the statement. Then in the main function we create a object of that class and then invoke that method and print them using System.out.println(). Then for second increment we again invoke method that increments the object by 10. OUTPUT: Q# 62. Write a program that that use the concept of recursion and find the factorial of the numbers. class Factorial{ int fact (int n ) { int result; if (n==1) return 1; result = fact(n-1)*n; 54 | P a g e
  • 56. JAVA & OOPS Manual return result; } } class Recursion{ public static void main (String args []) { Factorial f= new Factorial (); System.out.println("Factorial of 5 is " + f.fact(5)); System.out.println("Factorial of 7 is " + f.fact(7)); System.out.println("Factorial of 9 is " + f.fact(9)); } } DESCRIPTION: In this program we find the factorial of numbers. This is a recursive program in which we create a function of name fact(). When it will call with an argument of 1, the function returns 1, otherwise it will return the product of fact(n-1)*n . To evaluate this expression fact () is called with (n-1) .This process repeats until n =1. OUTPUT: Q# 63. Write a program that shows recursion. CODE: class Rectest{ int values[]; Rectest (int i){ values = new int[ i ]; } //display array-- recursively void printArray( int i){ if ( i == 0 ) return; else printArray(i - 1); System.out.println(" [" + (i-1) + "] " + values [ i -1 ] ); } 55 | P a g e
  • 57. JAVA & OOPS Manual } class Recursion2{ public static void main(String args[]){ Rectest ob = new Rectest(10); int i; for(i=0 ; i<10 ; i++) ob.values[i] = i; ob.printArray(10); } } Description: In this program first make a class after and intiliaze value after this make a constructor with single value , after this make void print array method than make another class which is main class in this class declare new object ob than initialize I after this declare for loop than call printarray() function. OUTPUT: Q# 64. Write a program that shows the working of access specifies. Like we can access public methods and variables but not private one. class test{ int a; //default access public int b; //public access private int c; //private access void setc(int z){ c = z; } int getc(){ return c; } } 56 | P a g e
  • 58. JAVA & OOPS Manual class AccessTest{ public static void main(String args[]){ test ob = new test(); ob.a =10; //correct ob.b = 20; // //ob.c = 100; ob.setc(100); //this is not Ok(Error) // System.out.println("The values of a , b and c are : " + ob.a+" " + ob.b +" "+ ob.getc() ); } } DESCRIPTION:In this program we simply shows the working of access specifier. This program shows that in java or any other language we can access public methods and public variables from outside the class but we can’t access a private method or private variable form outside the class. There is one type also called protected whose methods and variables can access only by the child classes but not from outside the class. OUTPUT: Q# 65. Write a program that uses variable , method and blocks class UseStatic { static int a=3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("static block initialize. "); b = a*4; } public static void main(String args []) { 57 | P a g e
  • 59. JAVA & OOPS Manual meth(42); } } Description: In this program first make a class than initialize static member a and b, after this make a method name as static void meth in this function print value of x , a, and b , after this write main method and call meth. Output: Q# 66. Write a program that inside main() the static method accessed outside of the class. Class StaticDemo { Static int a = 42; Static int b = 99; Static void callme( ) { System.out.println(―a = ―+ a); } } Class StaticByName { Public static void main (String args []) { StaticDemo.callme(); } } Description: in this program first make a class after this make a class as name StaticDemo after this initialize static data member, than print value of a , after this make a main class and print the value of b. Output: 58 | P a g e
  • 60. JAVA & OOPS Manual Q# 67. Write a program that demonstrates an inner class with in for loop. class Outer { int outer_x = 100; void test () { for (int i = 0; i<10; i++ ); { // declare for loop class Inner { void display ( ) { System.out.println("display : outer_x = " + outer_x); // prit value outer_x } } Inner inner = new Inner(); inner . display( ); // display method call } } } class InnerClassDemo { public static void main (String args [ ]) { // main body of program start from here Outer outer = new Outer (); outer.test (); // declare objrct // call test method } } Description:In this program first make class outer and initialize outer_x after this make method test, and for loop declare after this make class inner than declare display method, and call with inner object , than make main class and make new object outer and call test method. Output: Q# 68. Write a program that demonstrates Strings. class StringDemo { //declare class public static void main (String args []) { 59 | P a g e // main body of program start
  • 61. JAVA & OOPS Manual String strOb1 = "First String "; //Declare strOb1 String strOb2 = "Second String "; //Declare strOb2 String strOb3 = strOb1 + " and " + strOb2; System.out.println(" strOb1 "); // print strOb1 System.out.println(" strOb2 "); // print strOb2 System.out.println(" strOb3 "); //Declare strOb3 // print strOb3 } } Description: this is a simple program in which first declare object then print them. Output: Q# 69. Write a program that demonstrates some string method. class StringDemo2 { public static void main (String args []) { String strOb1 = "First String "; String strOb2 = "Second String "; String strOb3 = strOb1; System.out.println(" Length of strOb1 :" + strOb1.length()); System.out.println(" Char at index 3 in strOb1:" + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println("strOb1 == strOb2 "); else System.out.println("strOb1 != strOb2"); if(strOb1.equals(strOb3)) System.out.print("strOb1 == strOb3 "); else System.out.println("strOb1 != strOb3"); } } 60 | P a g e
  • 62. JAVA & OOPS Manual Description: Output: Q# 70. Write a program that display all command line arguments class CommandLine { // class name declare public static void main (String args [ ]) { //main body of program start from here for(int i=0; i<args.length; i++) // declare for loop System.out.println("args[ " + i + " ] :" + args[i]); // print arguments } } Description:in this program first make a class than main method of body start from here than for loop declare after this print value. Output: Q# 71. Write a program that uses inheritance to extend Box class Box{ double width; double height; double depth; //Construct Clone Of An Object Box(Box ob){ //Pass Object To Constructor width = ob.width; height = ob.height; depth = ob.depth; } Box(double w, double h, double d){//Constructor Used When All Dimensions Specified 61 | P a g e
  • 63. JAVA & OOPS Manual width = w; height = h; depth = d; } Box(){//Constructor Used When No Dimensions Specified width = -1; height = -1; depth = -1; } Box(double len){//Constructor Used When Cube Is Created width = height = depth = len; } double volume(){ //Compute And Return Volume return width * height * depth; } } class BoxWeight extends Box{//Here, Box Is Extended To Include Weight. double weight; //Weight Of Box BoxWeight(double w, double h, double d, double m){ width = w; height = h; depth = d; weight = m; } } class DemoBoxWeight{ public static void main(String args[]){ BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); 62 | P a g e //Constructor For BoxWeight
  • 64. JAVA & OOPS Manual System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } } Description: Output: Q# 72. Write a program that show Super keyword implementation of BoxWeight. class Box{ //class name private double width; //declare width private double height; //declare height private double depth; //declare depth Box(Box ob){ width = ob.width; // define constructor //give value to ob height = ob.height; depth = ob.depth; } Box(double w, double h, double d){ width = w; //declare w height = h; //declare h depth = d; } Box() { width = -1; height = -1; depth = -1; 63 | P a g e //declare d //define Box constructor
  • 65. JAVA & OOPS Manual } Box(double len) { // again constructor define which define len width = height = depth = len; } double volume() { //volume funcation return width * height * depth; // return value of volume } } class BoxWeight extends Box { double weight; //BoxWeight inherited from Box //declare weight BoxWeight(BoxWeight ob) { super(ob); weight = ob.weight; //constructor define //call super to ob //initiliaze weight } BoxWeight(double w, double h, double d, double m) { with 3 arguments //define constructor super(w, h, d); weight = m; } BoxWeight() { super(); weight = -1; } BoxWeight(double len, double m) { super(len); weight = m; } } class DemoSuper { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); 64 | P a g e //initialize myBox1
  • 66. JAVA & OOPS Manual BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); myBox2 //initialize BoxWeight mybox3 = new BoxWeight(); // by default BoxWeight mycube = new BoxWeight(3, 2); // initialize mycube BoxWeight myclone = new BoxWeight(mybox1); // declare my clone double vol; vol = mybox1.volume(); //declare vol System.out.println("Volume of mybox1 is " + vol); //print volume of myBox1 System.out.println("Weight of mybox1 is " + mybox1.weight); of myBox 1 // print weight System.out.println(); //print nothing vol = mybox2.volume(); //declare vol System.out.println("Volume of mybox2 is " + vol); //print volume of myBox2 System.out.println("Weight of mybox2 is " + mybox2.weight); of myBox System.out.println(); vol = mybox3.volume(); // print weight //print nothing // declare vol System.out.println("Volume of mybox3 is " + vol); //print volume of mybox3 System.out.println("Weight of mybox3 is " + mybox3.weight); of myBox3 // print weigh System.out.println(); vol = myclone.volume(); System.out.println("Volume of myclone is " + vol); System.out.println("Weight of myclone is " + myclone.weight); System.out.println(); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); System.out.println("Weight of mycube is " + mycube.weight); System.out.println(); } } Description: In this program first a class name Box in this class I define weight, height, and depth, after this make constructor with one argument ob and declare ob in it. After this make constructor with 65 | P a g e
  • 67. JAVA & OOPS Manual three arguments than define bydefault constructor. After this volume method define. Than make another class which extends Box, in this class define new object weight , than make theor constructor in BoxWeight() method super method call, after this main class define , and define new object print their values which are define in above class . Output: Q# 73. cost. Write a program in which BoxWeight extends to includinf shipping class Box { // class na,e declare private double width; //declare width private double height; //declare height private double depth; //declare depth Box(Box ob) { // make constructor width = ob.width; // pass object to constructor height = ob.height; depth = ob.depth; } Box(double w, double h, double d) { dimensions specified // constructor used when all width = w; height = h; depth = d; } Box() { // constructor used when no dimensions specified width = -1; height = -1; depth = -1; } Box(double len) { width = height = depth = len; } 66 | P a g e // constructor used when cube is created
  • 68. JAVA & OOPS Manual double volume() { // compute and return volume return width * height * depth; } } class BoxWeight extends Box { double weight; // weight of box BoxWeight(BoxWeight ob) { super(ob); // construct clone of an object // pass object to constructor weight = ob.weight; } BoxWeight(double w, double h, double d, double m) { parameters are specified super(w, h, d); // constructor when all // call superclass constructor weight = m; } BoxWeight() { // default constructor super(); weight = -1; } BoxWeight(double len, double m) { // constructor used when cube is created super(len); weight = m; } } class Shipment extends BoxWeight { // Add shipping costs. double cost; Shipment(Shipment ob) { super(ob); // construct clone of an object // pass object to constructor cost = ob.cost; } Shipment(double w, double h, double d, double m, double c) { when all parameters are specified 67 | P a g e // constructor
  • 69. JAVA & OOPS Manual super(w, h, d, m); cost = c; // call superclass constructor } Shipment() { // default constructor super(); cost = -1; } Shipment(double len, double m, double c) {// constructor used when cube is created super(len, m); // call Super cost = c; //declare cost } } class DemoShipment { public static void main(String args[]) { Shipment shipment1 =new Shipment(10, 20, 15, 10, 3.41); Shipment shipment2 =new Shipment(2, 3, 4, 0.76, 1.28); double vol; vol = shipment1.volume(); //decare vol // initiliaze volume System.out.println("Volume of shipment1 is " + vol); System.out.println("Weight of shipment1 is "+ shipment1.weight); System.out.println("Shipping cost: $" + shipment1.cost); System.out.println(); vol = shipment2.volume(); //decare vol // initiliaze volume System.out.println("Volume of shipment2 is " + vol); System.out.println("Weight of shipment2 is "+ shipment2.weight); System.out.println("Shipping cost: $" + shipment2.cost); } } Description: In this program first a class name Box in this class I define weight, height, and depth, after this make constructor with one argument ob and declare ob in it. After this make constructor with three arguments than define bydefault constructor. After this volume method define. Than make 68 | P a g e
  • 70. JAVA & OOPS Manual another class which extends Box, in this class define new object weight , than make another constructor in BoxWeight() method super method call,after this make class Shipment which extends Boxweightin this class cost shipment is defined in constructor of shipment class. after this main class define , and define new object print their values which are define in above class Output: Q# 74. Write a program that demonstrate when constructor are called. class A { //class name declare A() { System.out.println("Inside A's constructor."); } } class B extends A { // Create a subclass by extending class A. B() { System.out.println("Inside B's constructor."); } } class C extends B { // Create another subclass by extending B. C() { System.out.println("Inside C's constructor."); } } class CallingCons { // class name definition public static void main(String args[]) { // main body of program start C c = new C(); } } Description: In this program first define a class A and its constructor , after this make another class B which is inherited from A, make the constructor and print value , after this make another class c which is inherited from class B, than make main class and make new object cand print . Output: 69 | P a g e
  • 71. JAVA & OOPS Manual Q# 75. Write a program that show method overriding. class A{ int i, j; A(int a, int b) { i = a; j = b; } void show() { // display i and j System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { // display k – this overrides show() in A System.out.println("k: " + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); } } Description: 70 | P a g e // this calls show() in B
  • 72. JAVA & OOPS Manual Output: Q# 76. Write a program that use Dynamic method dispatch. class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { void callme() { // override callme() System.out.println("Inside B's callme method"); } } class C extends A { void callme() { // override callme() System.out.println("Inside C's callme method"); } } class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A r = a; // r refers to an A object r.callme(); r = b; r.callme(); r = c; r.callme(); 71 | P a g e // calls A's version of callme // r refers to a B object // calls B's version of callme // r refers to a C object // calls C's version of callme
  • 73. JAVA & OOPS Manual } } Description: Output; Q# 77. Write a program that use run time poly-morphisam. class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Area for Figure is undefined."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } double area() {// override area for rectangle System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } double area() { // override area for right triangle System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class FindAreas { public static void main(String args[]) { Figure f = new Figure(10, 10); 72 | P a g e
  • 74. JAVA & OOPS Manual Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } } Description: Through the dual mechanisms of inheritance and run-time polymorphism, it is possible to define one consistent interface that is used by several different, yet related, types of objects. In this case, if an object is derived from Figure, then its area can be obtained by calling area( ). Output: Q# 78. Write a program that use abstract method and classe. abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } // area is now an abstract method abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { 73 | P a g e
  • 75. JAVA & OOPS Manual System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = r; System.out.println("Area is " + figref.area()); System.out.println("Area is " + figref.area()); } } Description: As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try creating a subclass that does not override area( ). You will receive a compile-time error Output: 74 | P a g e
  • 76. JAVA & OOPS Manual Chapter # 10(Exception Handling) Q# 79. Write a program using exceptions in it class Exc2{ public static void main(String args[]){ int d,a; try{ d=0; a=42/d; System.out.println("This will not be printed"); } catch(ArithmeticException e){ System.out.println("Division by zero"); } System.out.println("After catch statement"); } } Description: Notice that 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. Output: Q# 80. Write a program showing multiple catch Clauses. 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}; c[42]=99; } catch(ArithmeticException e){ System.out.println("Divide by 0:"+e); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array index oob: "+e); 75 | P a g e
  • 77. JAVA & OOPS Manual } System.out.println("After try/catch blocks."); } } Description: This program will cause a division-by-zero exception if it is started with no command line arguments, since a will equal zero. It will survive the division if you provide a command line argument, setting a to something larger than zero. But it will cause an. ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program attempts to assign a value to c[42]. Output: Q# 81. Write a program that Handle an exception and move on. import java.util.Random; class HandleError { 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); } } } Output: 76 | P a g e
  • 78. JAVA & OOPS Manual Q# 82. write a program of 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 //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 77 | P a g e
  • 79. JAVA & OOPS Manual } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } Description: As you can see, this program nests one try block within another. The program works as follows. When you execute the program with no command-line arguments, a divide-by-zero exception is generated by the outer try block. Execution of the program with one command-line argument generates 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. If you execute the program with two command-line arguments, an array boundary exception is generated from within the inner try block. Here are sample runs that illustrate each case. Output: Q# 83. Write a program that 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 if(a==2) { int c[] = { 1 }; c[42] = 99; } } 78 | P a g e // generate an out-of-bounds exception
  • 80. JAVA & OOPS Manual 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); } } } Description: As you can see, this program nests one try block within another. The program works as follows. When you execute the program with no command-line arguments, a divide-by-zero exception is generated by the outer try block. Execution of the program with one command-line argument generates 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. If you execute the program with two command-line arguments, an array boundary exception is generated from within the inner Output: Chapter#13 (String Handling) Q# 84. Write a program that use override toString () for Box. class Box { double width; double height; double depth; 79 | P a g e
  • 81. JAVA & OOPS Manual Box(double w, double h, double d) { width = w; height = h; depth = d; } public String toString () { return "Dimension are " + width + " By " + depth + " By " + height + " . "; } } class toStringDemo { public static void main (String args []) { Box b = new Box (10, 12, 14) ; String s =( "Box b :" + b); //Concatinate box object System.out.println(b); //Convert Box to String System.out.println(s); //print value of s. } //ending brace of main program } //ending brace of class Description: In this program first make a class than write its main body after this declares s and print value of b and s. Output: Q# 85. Write a program that demonstrate equals () and equalsIgnoreCase(). //Demonstrate equals() and equalIgnoreCase(). public class EqualsDemo { public static void main (String[] args) { String s1 = "Hellow"; // Declare and initialize s1 String s2 = "Hellow"; // Declare and initialize s2 String s3 = "Good-By"; // Declare and initialize s3 String s4 = "HELLOW"; // Declare and initialize s4 80 | P a g e
  • 82. JAVA & OOPS Manual System.out.println(s1 + " equals " + s2 + "->" + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + "->" + s1.equals(s3)); System.out.println(s1 + " equals " + s4 + "->" + s1.equals(s4)); System.out.println(s1 + " equals " + s2 + "->" + s1.equalsIgnoreCase(s2)); } } Description: In this program first make class than write its main method after this initialize String s1 to s4 than print values by equals method. Output: Q# 86. Write a program that use == method to give answer. public class EqualsNotEqualsTo { public static void main (String[] args) { String s1 = "Helow"; String s2 = new String (s1); System.out.println(s1 + " equals " + s2 + "->" + s1.equals(s2)); System.out.println(s1 + "==" + s2 + "->" + (s1==s2)); } } Description: Output: Q# 87. Write a program that use compareTo() to determine sort ordering for a bubble sort. //A bubble sort for string public class SortString { static String arr[] = { 81 | P a g e
  • 83. JAVA & OOPS Manual "my","Name","is","khan","i","am","the","student","of","BSCS.","i","am","studing","in"," NFC","IEFR","Faisalabad" }; public static void main (String[] args) { for(int j = 0; j <arr.length; j++){ for(int i =j+1; i<arr.length;i++){ if(arr[i].compareTo(arr[j])< 0){ String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } } Description: Output: Q# 88. Write a program that show how to use various index method t search inside of string. public class IndexOfDemo { public static void main(String[] args) { String s = " my name is hussain ahmad khan , i am the student of BSCS " + "gradugate doing from Nfc IEFR Faisalabad Punjab Pakistan."; System.out.println(s); System.out.println("Last Index of (t) = " + s.indexOf('t')); System.out.println("Last Index of (t) = " + s.lastIndexOf('t')); 82 | P a g e
  • 84. JAVA & OOPS Manual System.out.println("Last Index of (the) = " + s.indexOf("the")); System.out.println("Last Index of (the) = " + s.lastIndexOf("the")); System.out.println("Last Index of (t,10) = " + s.indexOf('t',10)); System.out.println("Last Index of (t, 60) = " + s.lastIndexOf('t', 60)); System.out.println("Last Index of (the,10) = " + s.indexOf("the",10)); System.out.println("Last Index of (the, 60) = " + s.lastIndexOf("the", 60)); } } Description: Output: Q# 89. Write a program that use substring() method to replace all instance of one substring with another within string. class StringReplace { public static void main (String[] args) { String org = "This is a Test. This is , too."; String search = "is"; String sub = "was"; String result = " "; int i; do { //replase all matching substring System.out.println(org); i = org.indexOf(search); if(i != -1){ result = org.substring(0, i); result = result + sub ; result = result + org.substring(i + search.length()); org = result; } 83 | P a g e
  • 85. JAVA & OOPS Manual } while (i != -1); } } Description: Output: Q# 90. Write a program that use trim() to process commands. import java.io.*; //this is for taking input and output public class UseTrim { //class name declare public static void main(String[] args) throws IOException { // main body of programme // BufferedReader br = new BufferedReader (new InputStreamReader(System.in)) ;// creat bufferedReader using System.in String str; //declare str System.out.println("Enter 'Stop' to quite. "); System.out.println("Enter State: "); do { //print line // do while declare str = br.readLine(); str = str.trim(); // print the line //Call readLine() method to str //remove whitespace if (str.equals("Illionois")) //define if statement System.out.println("Capital spring feild."); else if (str.equals("Missouri")) //print the line //else statement difine System.out.println("Capital is Jefferson city"); // print capital is Jefferson city else if(str.equals("California")) statement // otherwise equals method call using if System.out.println("Capital is Scramemento"); else if (str.equals("Washhington")) statement // print value //again equls method call using else if System.out.println("Capital is Olampia."); // print capital is olampia. 84 | P a g e
  • 86. JAVA & OOPS Manual } while(!str.equals("stop")); //while condition define } } Description: First declare class name Output: Q# 91. Write a program that convert uppercase latter to lowercase and lowercase to uppercase latters. public class ChangeCase { //class name declare public static void main(String[] args) { String s = "This is a test."; //main body of program start from here //declare and initialize s System.out.println("Orignal sentence:" + s); // print value of s String upper = s.toUpperCase(); //call toUpperCase() method String lower = s.toLowerCase (); //call toLowerCase() method System.out.println("Upper: " + upper); // print string line in upper case System.out.println("Lower case: " + lower); } // print string line in lower case // ending brace of main body } //ending brace of class Description: In this code first make a class than start main body of program. Than declare s and then call toLoweCase() method and toUpperCase() method. Than print their their value. Output: Q# 92. Write a program that define StringBuffer length vs. capacity. class StringBufferDemo { public static void main (String[] args) { 85 | P a g e
  • 87. JAVA & OOPS Manual StringBuffer sb = new StringBuffer ("Hellow"); System.out.println("Buffer before = " + sb); System.out.println("Char at (1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i'); sb.setLength(2); System.out.println("buffer after = " + sb); System.out.println("CharAt(1) after = " + sb.charAt(1)); } } Description: In this program first make class and write main method, after this call StringBuffer() method and declare sb after this print value of sb. Output: Q# 93. Write a program that demonstrate append() method . class AppendDemo { //class name declare public static void main (String[] args) { String s ; // print main body of program start //declare s int a = 42; declare and initialize a StringBuffer sb = new StringBuffer (40); // call stringBuffer() method. s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s); //print value of s } } // ending brace of main body //ending brace of class Description: In this program make class and main body of program start. Than initialize and declare a and s, after this call StringBuffer() method. Than print value of s. Output: 86 | P a g e
  • 88. JAVA & OOPS Manual Q# 94. Write a program that demonstrate insert() method. lass InsertDemo{ public static void main (String[] args) { StringBuffer sb = new StringBuffer ("I java"); sb.insert(2, "like "); //insert like on 2 number. System.out.println(sb); // print value of sb } } //ending brace of main body //ending brace of class Description: Output: Q# 95. Write a program that demonstratereplace() method. class ReplaceDemo { // class name start public static void main (String[] args) { //main body of program start StringBuffer sb = new StringBuffer ("This is a test."); System.out.println("Before replace: " + sb); sb.replace(5, 7, "was"); //Call StringBuffer() method //print value of sb //Call replace method System.out.println("After replace : " + sb); method. //print value of sb after replacing } } Description: In this code first make a class than write main body of program , after this call StringBuffer() method. Than print sb after this call replace() method and replace the words. Output: Q# 96. Write a program that demonstrate IndexOfDemo () method. public class IndexOfDemo { public static void main(String[] args) { //main body of program start String s = " my name is hussain ahmad khan , i am the student of BSCS " + 87 | P a g e
  • 89. JAVA & OOPS Manual "gradugate doing from Nfc IEFR Faisalabad Punjab Pakistan."; System.out.println(s); // print value of s System.out.println("Last Index of (t) = " + s.indexOf('t')); //print value System.out.println("Last Index of (t) = " + s.lastIndexOf('t')); //print value System.out.println("Last Index of (the) = " + s.indexOf("the")); //print value System.out.println("Last Index of (the) = " + s.lastIndexOf("the")); //print value System.out.println("Last Index of (t,10) = " + s.indexOf('t',10)); //print value System.out.println("Last Index of (t, 60) = " + s.lastIndexOf('t', 60)); //print value System.out.println("Last Index of (the,10) = " + s.indexOf("the",10)); //print value System.out.println("Last Index of (the, 60) = " + s.lastIndexOf("the", 60)); //print value } } //ending brace of main bpdy //ending brace of class Description: In this program first make a class than main body of program start. After this call StringBuffer() than declare I after this call indexOf() method than print value of I , after this call lastIndecOf() method than print value of i. Output: Chater#09(Package and inter face) Q# 97. Write a program that that demonstrates package access. package mypack; class Balance { String name; doublebal; Balance(String n, double b){ name = n; bal = b; } void show (){ 88 | P a g e
  • 90. JAVA & OOPS Manual if(bal<0) System.out.print("-->"); System.out.print(name + " : $" + bal); } } publicclass AccountBalance { publicstaticvoid main (String args [] ){ Balance current [] = new Balance [3]; current [0] = new Balance ("K.J.Fielding", 123.23); current [1] = new Balance ("Will Tell", 157.02); current [2] = new Balance ("Tom Jackson", -12.33); for (int i=0; i<3; i++) current [i].show(); } } Description: Ist I make a project in java eclipse, than I make a package name as mypack , after this I make a class in this package. After this I make a class name Balance,, after this declare name as tring and bal as double , than make constructor, after this make show method , than make main class , which is abstract from Balance, and show output. Output: Q# 98. Write a program that demonstrates class of one package call in second package. package p1; publicclass Protection { intn = 1; privateintn_pri = 2; protectedintn_pro = 3; publicintn_pub = 4; public Protection (){ System.out.println("base constructer"); System.out.println("n = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pro = " + n_pub); } } package p1; class Derived extends Protection { Derived() { System.out.println("derived System.out.println("n = " + //System.out.println("n_pri System.out.println("n_pro = System.out.println("n_pub = } 89 | P a g e constructor"); n); = " + n_pri); " + n_pro); " + n_pub);
  • 91. JAVA & OOPS Manual } This is class SamePackage.java package p1; class SamePackage { SamePackage(){ Protection p = new Protection (); System.out.println("Same package constructor"); System.out.println("n = " + p.n); //System.out.println("n_pri = " + p.npri); System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub); } } This is file class Protectionism.java /** * */ package p2; /** * @author hussain * */ class Protection2 extends p1.Protection{ /** * body */ public Protection2() { System.out.println("Derived other package constructor"); // class or package only // System.out.println("n = " + n); //class only //System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); 90 | P a g e
  • 92. JAVA & OOPS Manual } } This is class file OtherPackage.java /** * */ package p2; /** * @author hussain * */ public class OtherPackage { /** * */ public OtherPackage() { p1.Protection p = new p1.Protection (); System.out.println("Other Package Constructor"); // class or package only //System.out.println("n = " +p. n); //class only //System.out.println("n_pri" + p.n_pri); //class subclass or package only //System.out.println("n_pro = " p.n_pro); System.out.println("n_pub = " + p.n_pub); // TODO Auto-generated constructor stub } } Now Package p1.java package p2; 91 | P a g e
  • 93. JAVA & OOPS Manual publicclass Demo { /** * @param args */ publicstaticvoid main(String[] args) { Protection2 ob1 = new Protection2 (); OtherPackage ob2 = new OtherPackage(); } } The test file for P2 is shown next package p1; publicclass Demo { /** * @param args */ publicstaticvoid main(String[] args) { Protection ob1 = new Protection (); Derived ob2 = new Derived(); SamePackage ob3 = new SamePackage (); } } Description: The two classes defined in p2 cover the other two conditions which are affected by access control. The first class, Protection2, is a subclass of p1.Protection. This grants access to all of p1.Protection’s variables except for n_pri (because it is private) and n, the variable declared with the default protection. Remember, the default only allows access from within the class or the package, not extra-package subclasses. Finally, the class OtherPackage has access to only one variable, n_pub, which was declared public. Output: 92 | P a g e
  • 94. JAVA & OOPS Manual Q# 99. Write a program that demonstrate importing package. /** * */ package mypack; /** * @authorhussain * */ publicclass Balance { String name; doublebal; /** * */ public Balance(String n, double b){ name = n; bal = b; } publicvoid show (){ if(bal<0) System.out.print("-->"); System.out.print(name + " : $" + bal); } } This class is in another class and import package , member of other class //import java.util.*; import mypack.*; publicclass TestBalance { publicstaticvoid main (String args []){ Balance test = new Balance ("J . J . Jasper", 99.98); test.show(); } } 93 | P a g e
  • 95. JAVA & OOPS Manual Description: Balance class is now public. Also, its constructor and its show( ) method are public, too. This means that they can be accessed by any type of code outside the MyPack package. For example, here TestBalance imports MyPack and is then able to make use of the Balance class. Output: Q# 100. Write a program that demonstrate fixed storage in interface. package interface9; class FixedStack implements IntStack { privateintstck[]; privateinttos; // allocate and initialize stack FixedStack(int size) { stck = newint[size]; tos = -1; } // Push an item onto the stack publicvoid push(int item) { if(tos==stck.length-1) // use length member System.out.println("Stack is full."); else stck[++tos] = item; } // Pop an item from the stack publicint pop() { if(tos< 0) { System.out.println("Stack underflow."); return 0; } else returnstck[tos--]; } } publicclass IFTest { /** * @param args */ publicstaticvoid main(String[] args) { FixedStack mystack1 = new FixedStack(5); FixedStack mystack2 = new FixedStack(8); // push some numbers onto the stack for(int i=0; i<5; i++) mystack1.push(i); for(int i=0; i<8; i++) mystack2.push(i); // pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<5; i++) System.out.println(mystack1.pop()); 94 | P a g e
  • 96. JAVA & OOPS Manual System.out.println("Stack in mystack2:"); for(int i=0; i<8; i++) System.out.println(mystack2.pop()); } } Description: IntStack that creates a dynamic stack by use of the same interface definition. In this implementation, each stack is constructed with an initial length. If this initial length is exceeded, then the stack is increased in size. Each time more room is needed, the size of the stack is doubled. Q# 101. Write a program that demonstrate ? package interface9; //Implement a "growable" stack. class DynStack implements IntStack { privateintstck[]; privateinttos; // allocate and initialize stack DynStack(int size) { stck = newint[size]; tos = -1; } // Push an item onto the stack publicvoid push(int item) { // if stack is full, allocate a larger stack if(tos==stck.length-1) { int temp[] = newint[stck.length * 2]; // double size for(int i=0; i<stck.length; i++) temp[i] = stck[i]; stck = temp; stck[++tos] = item; } else stck[++tos] = item; } // Pop an item from the stack publicint pop() { if(tos< 0) { System.out.println("Stack underflow."); return 0; } else returnstck[tos--]; } } class IFTest2 { publicstaticvoid main(String args[]) { DynStack mystack1 = new DynStack(5); DynStack mystack2 = new DynStack(8); // these loops cause each stack to grow for(int i=0; i<12; i++) mystack1.push(i); for(int i=0; i<20; i++) mystack2.push(i); 95 | P a g e
  • 97. JAVA & OOPS Manual System.out.println("Stack in mystack1:"); for(int i=0; i<12; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<20; i++) System.out.println(mystack2.pop()); } } Description: mystack is a reference to the IntStack interface. Thus, when it refers to ds, it uses the versions of push( ) and pop( ) defined by the DynStack implementation. When it refers to fs, it uses the versions of push( ) and pop( ) defined by FixedStack. As explained, these determinations are made at run time. Accessing multiple implementations of an interface through an interface reference variable is the most powerful way that Java achieves run-time polymorphism. Output: Q# 102. Write a program that ? package interface9; import java.util.Random; interface SharedConstants { intNO = 0; intYES = 1; intMAYBE = 2; intLATER = 3; intSOON = 4; 96 | P a g e
  • 98. JAVA & OOPS Manual intNEVER = 5; } class Question implements SharedConstants { Random rand = new Random(); int ask() { int prob = (int) (100 * rand.nextDouble()); if (prob < 30) returnNO; // 30% elseif (prob < 60) returnYES; // 30% elseif (prob < 75) returnLATER; // 15% elseif (prob < 98) returnSOON; // 13% else returnNEVER; // 2% } } class AskMe implements SharedConstants { staticvoid answer(int result) { switch(result) { caseNO: System.out.println("No"); break; caseYES: System.out.println("Yes"); break; caseMAYBE: System.out.println("Maybe"); break; caseLATER: System.out.println("Later"); break; caseSOON: System.out.println("Soon"); break; caseNEVER: System.out.println("Never"); break; } } publicstaticvoid main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } } Description: This class provides pseudorandom numbers. It contains several methods which allow you to obtain random numbers in the form required by your program. In this example, the 97 | P a g e
  • 99. JAVA & OOPS Manual method nextDouble( ) is used. It returns random numbers in the range 0.0 to 1.0. 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. Here is the output of a sample run of this program. Output: Q# 103. Write a program that show interface can be extended. /** * */ package interface9; /** * @author hussain * */ //One interface can extend another. interface A { void meth1(); void meth2(); } // B now includes meth1() and meth2() -- it adds meth3(). interface B extends A { void meth3(); } // This class must implement all of A and B 98 | P a g e
  • 100. JAVA & OOPS Manual class MyClass implements B { public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3()."); } } class IFExtend { public static void main(String arg[]) { MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } } Description: you might want to try 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 Output: 99 | P a g e
  • 101. JAVA & OOPS Manual Chapter#12 (I/O,APPLET, AND OTHER TOPIC) Q# 104. Write a program that read the Character. package readingCharacter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BRRead { public static void main(String args []) throws IOException { char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter character, 'q' to quit."); do { c = (char) br.read(); System.out.println(c); } while(c != 'q'); } } Description: This output may look a little different from what you expected, because System.in is line buffered, by default. This means that no input is actually passed to the program until you press ENTER. As you can guess, this does not make read( ) particularly valuable for interactive, console input. Output: Q# 105. /** * 100 | P a g e Write a program that read String.
  • 102. JAVA & OOPS Manual */ package readingString; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author hussain * */ public class BRReadLine { /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // creat a bfferedreader line using system.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Ener lines of text."); System.out.println("Ener 'stop' of quit."); do{ str = br.readLine(); System.out.println(str); } while (!str.equals("stop")); } } Description: 101 | P a g e
  • 103. JAVA & OOPS Manual To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class.following program demonstrates BufferedReader and the readLine( ) method; the program reads and displays lines of text until you enter the word ―stop‖: Output: Q# 106. Write a program that create a tiny Text editor. /** * */ package readingString; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author hussain * */ public class TinyEdit { /** * @param args */ public static void main(String[] args) throws IOException { 102 | P a g e
  • 104. JAVA & OOPS Manual // creat a bfferedreader line using system.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str [] = new String[100]; System.out.println("Ener lines of text."); System.out.println("Ener 'stop' of quit."); for(int i = 0; i<00; i++){ str[i] = br.readLine(); if(str[i].equals("stop")) break; } System.out.print("n Here is your file:"); // display the line for(int i = 0; i<00; i++){ if (str[i].equals("stop")) break; System.out.print(str[i]); } } } Description: To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class.following program demonstrates BufferedReader and the readLine( ) method; the program reads and displays lines of text until you enter the word ―stop‖: Output: Q# 107. /** * */ 103 | P a g e Write a program that demonstrate System.out.write().
  • 105. JAVA & OOPS Manual package writingconsoeoutput; /** * @author hussain * */ public class WriteDemo { /** * @param args */ public static void main(String[] args) { int b; b = 'c'; System.out.print(b); System.out.write('n'); } } Description: There is nothing wrong with using System.out to write simple text output to the console when you are learning Java or debugging your programs. However, using a PrintWriter will make your real-world applications easier to internationalize. Because no advantage is gained by using a PrintWriter in the sample programs shown in this book, we will continue to use System.out to write to the console. Output: Q# 108. Write a program that demonstrate PrintWriter Class. /** * */ package printwriter; 104 | P a g e
  • 106. JAVA & OOPS Manual import java.io.PrintWriter; /** * @author hussain * */ public class PrintwriterDemo { /** * @param args */ public static void main(String[] args) { PrintWriter pw = new PrintWriter (System.out, true); pw.println("This is a String"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } } Description: The following program uses read( ) to input and display the contents of a text file, the name of which is specified as a command-line argument. Note the try/catch blocks that handle the two errors that might occur when this program is used—the specified file not being found or the user forgetting to include the name of the file. You can use this same approach whenever you use command-line arguments. Output: 105 | P a g e
  • 107. JAVA & OOPS Manual Q# 109. Write a program that demonstrate a text file. /** * */ package readandwrite; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * @author hussain * */ public class ShowFile { /** * @param args */ public static void main(String[] args) throws IOException { int i; FileInputStream fin; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e){ System.out.println("File Not Found"); return; } catch (ArrayIndexOutOfBoundsException e){ System.out.println("Ener lines of text."); System.out.println("Usage : ShowFile File"); return; } 106 | P a g e
  • 108. JAVA & OOPS Manual do { i = fin.read(); if (i != -1) System.out.print((char)i); } while (i != -1); fin.close(); } } Description: To write to a file, you will use the write( ) method defined by FileOutputStream. Its simplest form is shown here: void write(int byteval) throws IOException This method writes the byte specified by byteval to the file. Although byteval is declared as an integer, only the low-order eight bits are written to the file. If an error occurs during writing, an IOException is thrown Output: Q# 110. Write a program that demonstrate to copy a text file. /** * */ package readandwrite; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * @author hussain * 107 | P a g e
  • 109. JAVA & OOPS Manual */ public class CopyFile { /** * @param args */ public static void main(String[] args) throws IOException{ int i; FileInputStream fin; FileOutputStream fout; try { // open input file try { fin = new FileInputStream(args[0]); } catch (FileNotFoundException e){ System.out.print("Input File Not Foud"); return; } // open output file try { fout = new FileOutputStream(args[1]); } catch (FileNotFoundException e){ System.out.print("Error oprning output file"); return; } } catch(ArrayIndexOutOfBoundsException e){ System.out.print("Usage : CopyFile From To"); return; } // copy file try { 108 | P a g e
  • 110. JAVA & OOPS Manual do { i = fin.read(); if(i != -1) fout.write(i); } while (i != -1); }catch (IOException e){ System.out.print("File Error"); } fin.close(); fout.close(); } } Description: Output: Q# 111. Write a program that demonstrate on simple simple Applet method. package AppletFundamental; import java.applet.Applet; import java.awt.Graphics; publicclassSimpleAppletextends Applet { publicvoid paint (Graphics g){ g.drawString("A simple Applet", 20, 20); } } Description: This applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the console-based I/O classes. The AWT contains support for a window-based, graphical interface. As you might expect, the AWT is quite large and sophisticated Output: 109 | P a g e
  • 111. JAVA & OOPS Manual Q# 112. Write a program that demonstrate instanceof () Operator. /** * */ package instanceoof; /** * @author hussain * */ class A{ int i,j; } class B{ int i,j; } class C extends A { int k; } 110 | P a g e
  • 112. JAVA & OOPS Manual class D extends A { int k; } class Instanceof { /** * @param args */ public static void main(String[] args) { A a = new A (); B b = new B(); C c = new C(); D d = new D(); if(a instanceof A) System.out.println("a is instanceof of A"); if (b instanceof B) System.out.println("b is instanceof of B"); if (c instanceof C) System.out.println("c is instanceof of C"); if (d instanceof D) System.out.println("d is instanceof of D"); if (a instanceof C) System.out.println("a can b cast to C"); System.out.println(); // compare type of derived type A ob; ob = d; // a refrence to d System.out.println("ob now refrence to d"); if (ob instanceof D) System.out.println("ib is instanceof of D"); System.out.println(); 111 | P a g e
  • 113. JAVA & OOPS Manual ob = c; System.out.println("ob now refer to c"); if (ob instanceof D) System.out.println("ob can b cast to D"); else System.out.print("ob cannot b cast to D"); if (ob instanceof A) System.out.print("ob can b cast to A"); System.out.println(); // all object can be cast cast to object if (a instanceof Object) System.out.print("a must b cast to Object."); if (b instanceof Object) System.out.print("b must b cast to Object."); if (c instanceof Object) System.out.print("c must b cast to Object."); if (d instanceof Object) System.out.print("d must b cast to Object."); } } Description: The instanceof operator isn’t needed by most programs, because, generally, you know the type of object with which you are working. However, it can be very useful when you’re writing generalized routines that operate on objects of a complex class hierarchy. Output: 112 | P a g e
  • 114. JAVA & OOPS Manual Q# 113. Write a program that that demonstrate how to use assert.? package assert1; publicclass AssertDemo { staticintval= 3; // val declare and initialize staticint getnum(){ // getnum() method start returnval--; // return decrement of val value } // ending brace of getnum() method publicstaticvoid main (String args []){ // main body of program start from here int n; // declare n for(int i = 0; i <10; i++){ // for loop n = getnum(); // call getnum () method assert n > 0 ; // will fail when n is zero System.out.println("n is" + n); // print value of n } } } Description: Thisvalue is converted to its string format and displayed if an assertion fails. Typically, you will specify a string for expr, but any non-void expression is allowed as long as it defines a reasonable string conversion. Output: Chapter#19(The Applet Classes) Q# 114. Write a program that demonstrates Applet Skelton. /** * */ package appletskelton1; 113 | P a g e
  • 115. JAVA & OOPS Manual import java.applet.Applet; import java.awt.Graphics; /** * @author hussain * */ public class AppletSkel extends Applet { //called first public void init(){ //initlization } public void start (){ // start or resume executation } public void stop(){ // suspends executation } public void destory (){ // perform shut down activity } public void paint (Graphics g){ //redisplay content of window } } Description: Output: 114 | P a g e
  • 116. JAVA & OOPS Manual Q# 115. Write a program that demonstrate foreground and background ground color of and out put of String. package displaymethod; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class Sample extends Applet { //private static final long serialVersionUID = 1L; String msg; // set forgroung and background color public void init (){ setBackground(Color.cyan); setForeground(Color.red); msg = "Inide init( ) --"; } // initiliaze the string to displaymethod public void start (){ msg += "Inside start ( ) --"; } 115 | P a g e
  • 117. JAVA & OOPS Manual // display msg in applet window public void paint (Graphics g){ msg += "Inside start ( )."; g.drawString(msg, 10, 30); } } Description: The methods stop( ) and destroy( ) are not overridden, because they are not needed by this simple applet. Output: Q# 116. Write a program that demonstrate simple Banner Applet. package bannerapplet3; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class SimpleBanner extends Applet implements Runnable{ String msg = "A simple Moving. "; Thread t = null; int state; boolean stopFlag; 116 | P a g e
  • 118. JAVA & OOPS Manual public void init (){ setBackground(Color.CYAN); setForeground(Color.red); } public void start (){ t = new Thread (this); stopFlag = false; t.start(); } public void run (){ char ch; for(;;){ try{ repaint(); Thread.sleep(250); ch = msg .charAt(0); msg = msg.substring(1, msg.length()); msg += ch; if(stopFlag) break; } catch (InterruptedException e) { } } } public void stop (){ stopFlag = true; t = null; } public void paint (Graphics g){ g.drawString(msg, 50, 30); } 117 | P a g e
  • 119. JAVA & OOPS Manual } Description: Let’s take a close look at how this applet operates. First, notice that SimpleBanner extends Applet, as expected, but it also implements Runnable. This is necessary, since the applet will be creating a second thread of execution that will be used to scroll the banner. Inside init( ), the foreground and background colors of the applet are set. Output: Q# 117. Write a program that demonstrate showStatus(). package statuswindow4; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class StatusWindow extends Applet{ public void init (){ setBackground(Color.CYAN); } public void paint (Graphics g){ g.drawString("This is an Applet Window.", 10, 20); showStatus("This is shown in the status window."); 118 | P a g e
  • 120. JAVA & OOPS Manual } } Description: The status window is a good place to give the user feedback about what is occurring in the applet, suggest options, or possibly report some types of errors. The status window also makes an excellent debugging aid, because it gives you an easy way to output information about your applet. Output: Q# 118. Write a program that demonstrate passing parameter to Applet. package passingparameter5; import java.applet.Applet; import java.awt.Graphics; public class ParamDemo extends Applet{ String fontName; int fontSize; float leading; boolean active; public void start (){ String Param; 119 | P a g e
  • 121. JAVA & OOPS Manual fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found"; Param = getParameter("fontSize"); try{ if(Param != null) fontSize = Integer.parseInt(Param); else fontSize = 0; } catch(NumberFormatException e){ fontSize = -1; } Param = getParameter("leading"); try{ if (Param != null) leading = Float.valueOf(Param).floatValue(); else leading = 0; }catch(NumberFormatException e){ leading = -1; } Param = getParameter("Account Enabled"); if(Param != null) active = Boolean.valueOf(Param).booleanValue(); } public void Paint (Graphics g){ g.drawString("Font Name", 0, 10); g.drawString("Font Soze" + fontSize, 0, 26); g.drawString("Leading" + leading , 0, 42); g.drawString("Account Active" + active } 120 | P a g e ,0 , 58);
  • 122. JAVA & OOPS Manual } Description: It return values from getParameter( ). If a parameter isn’t available, getParameter( ) will return null. Also, conversions to numeric types must be attempted in a try statement that catches NumberFormatException. Uncaught exceptions should never occur within an applet Output: Q# 119. Write a program that display code and document bases. package getDocument; import java.awt.*; import java.applet.*; import java.net.*; /* <applet code="Bases" width=300 height=50> </applet> */ publicclassBasesextends Applet{ // Display code and document bases. publicvoid paint(Graphics g) { String msg; URL url = getCodeBase(); // get code base msg = "Code base: " + url.toString(); g.drawString(msg, 10, 20); url = getDocumentBase(); // get document base msg = "Document base: " + url.toString(); g.drawString(msg, 10, 40); } } Description: Output: 121 | P a g e
  • 123. JAVA & OOPS Manual Q# 120. Write a program that get code and display HTML file. package showDocument8; importjava.awt.*; import java.applet.*; import java.net.*; publicclassACDemoextends Applet{ publicvoid start() { AppletContext ac = getAppletContext(); URL url = getCodeBase(); // get url of this applet try { ac.showDocument(new URL(url+"Test.html")); } catch(MalformedURLException e) { showStatus("URL not found"); } } } Description: AppletContext and showDocument( ). Upon execution, it obtains the current applet context and uses that context to transfer control to a file called Test.html. This file must be in the same directory as the applet. Test.html can contain any valid hypertext that you like. Output: 122 | P a g e
  • 124. JAVA & OOPS Manual Chapter#20(Events Handling) Q# 121. Write a program that demonstrate mouse event handler. package handlingmouse1; //Demonstrate the mouse event handlers. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="MouseEvents" width=300 height=100> </applet> */ publicclassMouseEventsextends Applet implements MouseListener, MouseMotionListener { String msg = ""; intmouseX = 0, mouseY = 0; // coordinates of mouse publicvoid init() { addMouseListener(this); addMouseMotionListener(this); } // Handle mouse clicked. publicvoid mouseClicked(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } // Handle mouse entered. publicvoid mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } 123 | P a g e
  • 125. JAVA & OOPS Manual // Handle mouse exited. publicvoid mouseExited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. publicvoid mousePressed(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); } // Handle button released. publicvoid mouseReleased(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } // Handle mouse dragged. publicvoid mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } // Handle mouse moved. publicvoid mouseMoved(MouseEvent me) { // show status showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. publicvoid paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } Description: The MouseEvents class extends Applet and implements both the MouseListener and MouseMotionListener interfaces. These two interfaces contain methods that receive and process the various types of mouse events. Notice that the applet is both the source and the listener for these events. This works because Component, which supplies the addMouseListener( ) and addMouseMotionListener( ) methods, is a superclass of Applet. Being both the source and the listener for events is a common situation for applets. 124 | P a g e
  • 126. JAVA & OOPS Manual Inside init( ), the applet registers itself as a listener for mouse events. This is done by using addMouseListener( ) and addMouseMotionListener( ), which, as mentioned, are members of Component. Output: Q# 122. Write a program that demonstrate key event handler. package handlingkeybord; //Demonstrate the key event handlers. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="SimpleKey" width=300 height=100> </applet> */ publicclassSimpleKeyextends Applet implements KeyListener { String msg = ""; intX = 10, Y = 20; // output coordinates publicvoid init() { addKeyListener(this); requestFocus(); // request input focus } publicvoid keyPressed(KeyEvent ke) { showStatus("Key Down"); } publicvoid keyReleased(KeyEvent ke) { showStatus("Key Up"); } publicvoid keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } // Display keystrokes. publicvoid paint(Graphics g) { g.drawString(msg, X, Y); 125 | P a g e
  • 127. JAVA & OOPS Manual } } Description: If you want to handle the special keys, such as the arrow or function keys, you need to respond to them within the keyPressed( ) handler. They are not available through keyTyped( ). Output: program adapter in Q# 123. Write a that demonstrate an event handling. package adapter; //Demonstrate importjava.awt.*; import java.awt.event.*; import java.applet.*; publicclassAdapterDemoextends Applet { publicvoid init() { addMouseListener(new MyMouseAdapter(this)); addMouseMotionListener(new MyMouseMotionAdapter(this)); } } class MyMouseAdapter extends MouseAdapter { AdapterDemo adapterDemo; public MyMouseAdapter(AdapterDemo adapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse clicked. publicvoid mouseClicked(MouseEvent me) { adapterDemo.showStatus("Mouse clicked"); } } class MyMouseMotionAdapter extends MouseMotionAdapter { AdapterDemo adapterDemo; public MyMouseMotionAdapter(AdapterDemo adapterDemo) { an adapter. 126 | P a g e
  • 128. JAVA & OOPS Manual this.adapterDemo = adapterDemo; } // Handle mouse dragged. publicvoid mouseDragged(MouseEvent me) { adapterDemo.showStatus("Mouse dragged"); } } Description: As you can see by looking at the program, not having to implement all of the methods defined by the MouseMotionListener and MouseListener interfaces saves you a considerable amount of effort and prevents your code from becoming cluttered with empty methods. As an exercise, you might want to try rewriting one of the keyboard input examples shown earlier so that it uses a KeyAdapter. Output: Q# 124. Write a to inner classes package inner; program that show how uses .? //This applet does NOT use an inner class. import java.applet.*; import java.awt.event.*; /* <applet code="MousePressedDemo" width=200 height=100> </applet> */ publicclassMousePressextends Applet { publicvoid init() { addMouseListener(new MyMouseAdapter(this)); } } class MyMouseAdapter extends MouseAdapter { MousePress mousePress; public MyMouseAdapter(MousePress mousePressedDemo) { this.mousePress = mousePressedDemo; } publicvoid mousePressed(MouseEvent me) { mousePress.showStatus("Mouse Pressed."); 127 | P a g e
  • 129. JAVA & OOPS Manual } } Description: The following listing shows how the preceding program can be improved by using an inner class. Here, InnerClassDemo is a top-level class that extends Applet. MyMouseAdapter is an inner class that extends MouseAdapter. Because MyMouseAdapter is defined within the scope of InnerClassDemo, it has access to all of the variables and methods within the scope of that class. Therefore, the mousePressed( ) method can call the showStatus( ) method directly. It no longer needs to do this via a stored reference to the applet. Thus, it is no longer necessary to pass MyMouseAdapter( ) a reference to the invoking object. Output: Q# 125. Write a program that demonstrate Anonymous inner class. package anonymousinner; //Anonymous inner class demo. import java.applet.*; import java.awt.event.*; publicclassAnonymousInnerClassDemoextends Applet { publicvoid init() { addMouseListener(new MouseAdapter() { publicvoid mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } }); } } Description: There is one top-level class in this program: AnonymousInnerClassDemo. The init( ) method calls the addMouseListener( ) method. Its argument is an expression that defines and instantiates an anonymous inner class. Let’s analyze this expression carefully. 128 | P a g e
  • 130. JAVA & OOPS Manual Output: 129 | P a g e