Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
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