java codes

162
Table of Contents Chapter # 1 (The Genesis of Java) 4 Q# 1. Write a java program which show hallow word app! 4 Chapter # 2 (An Overview Of Java) 4 Q# 2. Write a java program to display a simple string. 4 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) 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

Upload: hussain-sherwani

Post on 06-May-2015

5.245 views

Category:

Education


7 download

DESCRIPTION

In this Mannual there are sme Java Example Code with out and description.

TRANSCRIPT

Page 1: Java codes

Table of ContentsChapter # 1 (The Genesis of Java) 4

Q# 1. Write a java program which show hallow word app! 4

Chapter # 2 (An Overview Of Java) 4

Q# 2. Write a java program to display a simple string. 4

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

Page 2: Java codes

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. Write a program in which for loop is used and find the prime number by using this loop. 30

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. Write a for loop program in which initialization and iteration is moved out of the for loop. 31

Q# 37. Write a program of nested for loop. 32

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. 35

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. 37

Q# 45. Write a program that demonstrates return. 37

Chapter # 6 (Introducing classes) 38

Q# 46. Write a program that call this file BoxDemo.java. 38

Q# 47. Write a program that declares two Box object. 39

Q# 48. Write a program that includes a method inside the box class. 40

Q# 49. Write a program that volume () returns the volumeof a box 41

Q# 50. Write a program that use as parameterized method 42

Q# 51. Write a program that use a constructor to initialize the dimension f a box. 43

Q# 52. Write a program that uses a parameterized constructor to initialize the dimension.44

Q# 53. Write a program that defines an integer stack that can hold 10 values. 45

Chapter # 7 (A Closer Look at Methods and Classes) 46

Q# 54. Write a program that demonstrates method overloading. 46

1 | P a g e

Page 3: Java codes

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 50

Q# 58. Write a program that shows the overloading of constructors. 51

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. 54

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

Q# 63. Write a program that shows recursion. 56

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

Q# 65. Write a program that uses variable , method and blocks 58

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. 60

Q# 69. Write a program that demonstrates some string method. 61

Q# 70. Write a program that display all command line arguments 61

Q# 71. Write a program that uses inheritance to extend Box 62

Q# 72. Write a program that show Super keyword implementation of BoxWeight. 64

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. 74

Chapter # 10(Exception Handling) 75

Q# 79. Write a program using exceptions in it 75

Q# 80. Write a program showing multiple catch Clauses. 76

Q# 81. Write a program that Handle an exception and move on. 77

Q# 82. write a program of try statements 77

Q# 83. Write a program that can be implicitly nested via calls to methods. */ 79

Chapter#13 (String Handling) 80

2 | P a g e

Page 4: Java codes

JAVA & OOPS Manual

Q# 84. Write a program that use override toString () for Box. 80

Q# 85. Write a program that demonstrate equals () and equalsIgnoreCase(). 81

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.82

Q# 88. Write a program that show how to use various index method t search inside of string. 83

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. 86

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. 88

Chater#09(Package and inter face) 89

Q# 97. Write a program that that demonstrates package access. 89

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 ? 97

Q# 103. Write a program that show interface can be extended. 99

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

Q# 104. Write a program that read the Character. 100

Q# 105. Write a program that read String. 101

Q# 106. Write a program that create a tiny Text editor. 102

Q# 107. Write a program that demonstrate System.out.write( ). 104

Q# 108. Write a program that demonstrate PrintWriter Class. 105

Q# 109. Write a program that demonstrate a text file. 106

Q# 110. Write a program that demonstrate to copy a text file. 108

Q# 111. Write a program that demonstrate on simple simple Applet method. 110

Q# 112. Write a program that demonstrate instanceof () Operator. 110

3 | P a g e

Page 5: Java codes

JAVA & OOPS Manual

Q# 113. Write a program that that demonstrate how to use assert.? 113

Chapter#19(The Applet Classes) 114

Q# 114. Write a program that demonstrates Applet Skelton. 114

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. 117

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 | P a g e

Page 6: Java codes

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 | P a g e

Page 7: Java codes

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"); // this is a output line which show a string

x= x*2; //multiply again by 2

if(x>y) System.out.println("now x is greater than y"); // this is a output line which show a string

} //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); // this line show value of x

} // end of main program

6 | P a g e

Page 8: Java codes

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 | P a g e

Page 9: Java codes

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[]){ // This line begins the main() method.

int lightspeed; //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 int type 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 | P a g e

Page 10: Java codes

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.

char ch1, ch2; // daclere two character variable.

9 | P a g e

Page 11: Java codes

JAVA & OOPS Manual

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 ch1 assigned 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

Page 12: Java codes

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

Page 13: Java codes

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

Page 14: Java codes

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

Page 15: Java codes

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[]){ //daclre main line line of program main body of program start from here

int i = 257; //Initialize and Declare i

byte b; //initialize b

double d = 323.42; // Initialize and Declare d

System.out.println("\n Conversion of int tom byte."); // print string line

b = (byte) i; // 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"); // print string line

b = (byte) d; // 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

Page 16: Java codes

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)); // print line

System.out.println("result = " + result); // 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

Page 17: Java codes

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 []){ // main method

int x=67; // initialize and declare x

double y=67.25; //initialize and declare y

System.out.println("x mod 10 = " + x%10 ); //print modulus of x

System.out.println("y mod 10 = " + y%10 ); //print modulus of y

} // end main method

16 | P a g e

Page 18: Java codes

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

Page 19: Java codes

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 [ ] ) { // main body of programme start from here

byte a = 64, b; //Declare a

int i; // declare i

i = a<<2; //Decare i is lessthan 2

b = (byte) (a << 2); // convert data type

18 | P a g e

Page 20: Java codes

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); //Declare f

boolean g= !a; //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); //Print value of f

System.out.println(" !a = " + g); //Print value of g

} //main body of programme ended

} // class ended

Description:

Output:

19 | P a g e

Page 21: Java codes

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

Page 22: Java codes

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 switchclass 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

Page 23: Java codes

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; // this stop the execution and end the program

case 3: //if i=3 than this case is executed.

System.out.println("i is three.");

break; // this stop the execution and end the program.

default: //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

Page 24: Java codes

JAVA & OOPS Manual

System.out.println("i is less than 3"); // print the string

break; // this line break the loop

case 3:

case 4:

System.out.println("i is less than 5"); // print the string

break; // this line break the loop

default: //if no condition is true then this is executed.

System.out.println("i is 6 or more"); // 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. Write a programme that show the season when any month is given to it.

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; // break statement use to jump from the switch

23 | P a g e

Page 25: Java codes

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

Page 26: Java codes

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) ; //print value of n

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

Page 27: Java codes

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 dowhileclass 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); // print value of n

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 { // This line is used for for handling exception and input errors

char choice; //Declare char as a choice

do { //

26 | P a g e

Page 28: Java codes

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. for\n"); //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 expression

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

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

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

System.out.println(" // ..."); // 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

27 | P a g e

Page 29: Java codes

JAVA & OOPS Manual

System.out.println("while(condition) statement;"); // print while condition statement

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

Page 30: Java codes

JAVA & OOPS Manual

Q# 32. Write a programme that demonstrate loop control veriable inside the for

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

29 | P a g e

Page 31: Java codes

JAVA & OOPS Manual

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)

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

30 | P a g e

Page 32: Java codes

JAVA & OOPS Manual

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:

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 []) { // main body of programme start from here

Int a , b; // 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.

31 | P a g e

Page 33: Java codes

JAVA & OOPS Manual

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.

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.

32 | P a g e

Page 34: Java codes

JAVA & OOPS Manual

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 causes it to terminates when i equals 10.

Output:

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.

33 | P a g e

Page 35: Java codes

JAVA & OOPS Manual

OUTPUT:

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:

34 | P a g e

Page 36: Java codes

JAVA & OOPS Manual

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.");

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

35 | P a g e

Page 37: Java codes

JAVA & OOPS Manual

public static void main (String args []) { // main body of program start from here

outer: for(int i = 0; i<3 ; i++) { // for loop declared

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

for(int j=0; j<100;j++) { // Again for loop declared

if (j == 10) // declared if condition j equals to 10

break outer; // exit both loops

System.out.print(j + " "); // print j

} //second loop body ended

System.out.println("This will not print");

} // 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 [ ] ) { // main body of program start

for (int i = 0; i < 10; i++ ) { // 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:

36 | P a g e

Page 38: Java codes

JAVA & OOPS Manual

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 [] ) { //main body of program start from here

outer: for(int i=o; i<10; i++) { for loop declare

for(int j=0; j<10; j++) { again for loop declare

if (j > i) { // if j is greater than i

System.out.println(); // print nothing

continue outer; // print

} // if condition finished

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 []) { // main body of program start

boolean t = true; t declared as a boolean type

System.out.println("Before the return. "); // print before the return

if(t) return; // return to caller

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

} // main body of program ended

} class ended

37 | P a g e

Page 39: Java codes

JAVA & OOPS Manual

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:

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:

38 | P a g e

Page 40: Java codes

JAVA & OOPS Manual

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 [] ) {

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:

39 | P a g e

Page 41: Java codes

JAVA & OOPS Manual

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 [ ]) { // main body of program start

Box mybox=new Box (); // declare a memory of for new box mybox

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 height of second box

mybox.height=18; // give value of height of second box

mybox.depth=23; //give value of depth of 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 height of second box

mybox2.depth=15; //give value of depth of second box

mybox.volume(); //display the volume of first box

mybox2.volume(); //display the volume of Second box

}

}

Description:

Output:

40 | P a g e

Page 42: Java codes

JAVA & OOPS Manual

Q# 49. Write a program that volume () returns the volumeof a boxclass 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;

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); // print volume of myBox1

vol=mybox2.volume(); // declare vol

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

} // 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:

41 | P a g e

Page 43: Java codes

JAVA & OOPS Manual

Q# 50. Write a program that use as parameterized methodclass 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 ) { // setdim method initialize

width=w; //declare width

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); // print volume of mybox1

vol=mybox2.volume(); // Initialize vol

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

} // ending brace of main body

} // ending brace of class

Description:

42 | P a g e

Page 44: Java codes

JAVA & OOPS Manual

Output:

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

class Box {

double width;

double height;

double depth;

Box( ) {

System.out.println("costructing box is ");

width=17;

height=19;

depth=15;

}

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:

43 | P a g e

Page 45: Java codes

JAVA & OOPS Manual

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;

}

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:

44 | P a g e

Page 46: Java codes

JAVA & OOPS Manual

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

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

45 | P a g e

Page 47: Java codes

JAVA & OOPS Manual

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 less than 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:

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

Q# 54. Write a program that demonstrates method overloading.

class OverloadDemo{ // declare class name

void test() { // declare test method

System.out.println("No parameters"); // print no parameter

} // ending brace of test method

46 | P a g e

Page 48: Java codes

JAVA & OOPS Manual

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); // print value of a

return a*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 [ ] ){ // main method call

OverloadDemo ob = new OverloadDemo (); // declare new object as ob

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 ); // print value of result

} // 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{

47 | P a g e

Page 49: Java codes

JAVA & OOPS Manual

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;

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;

48 | P a g e

Page 50: Java codes

JAVA & OOPS Manual

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;

}

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:

49 | P a g e

Page 51: Java codes

JAVA & OOPS Manual

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

(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:

50 | P a g e

Page 52: Java codes

JAVA & OOPS Manual

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;

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 [ ] ) {

51 | P a g e

Page 53: Java codes

JAVA & OOPS Manual

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

}

}

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;

52 | P a g e

Page 54: Java codes

JAVA & OOPS Manual

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:

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

53 | P a g e

Page 55: Java codes

JAVA & OOPS Manual

}

}

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) {

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

}

}

54 | P a g e

Page 56: Java codes

JAVA & OOPS Manual

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;

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:

55 | P a g e

Page 57: Java codes

JAVA & OOPS Manual

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

}

}

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:

56 | P a g e

Page 58: Java codes

JAVA & OOPS Manual

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;

}

}

class AccessTest{

public static void main(String args[]){

test ob = new test();

ob.a =10; //correct

ob.b = 20; //

//ob.c = 100; //this is not Ok(Error)

ob.setc(100); //

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:

57 | P a g e

Page 59: Java codes

JAVA & OOPS Manual

Q# 65. Write a program that uses variable , method and blocksclass 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 []) {

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;

58 | P a g e

Page 60: Java codes

JAVA & OOPS Manual

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:

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

}

}

59 | P a g e

Page 61: Java codes

JAVA & OOPS Manual

}

class InnerClassDemo {

public static void main (String args [ ]) { // main body of program start from here

Outer outer = new Outer (); // declare objrct

outer.test (); // 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 []) { // main body of program start

String strOb1 = "First String "; //Declare strOb1

String strOb2 = "Second String "; //Declare strOb2

String strOb3 = strOb1 + " and " + strOb2; //Declare strOb3

System.out.println(" strOb1 "); // print strOb1

System.out.println(" strOb2 "); // print strOb2

System.out.println(" strOb3 "); // print strOb3

}

}

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

Output:

60 | P a g e

Page 62: Java codes

JAVA & OOPS Manual

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

}

}

Description:

Output:

Q# 70. Write a program that display all command line argumentsclass 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

}

}

61 | P a g e

Page 63: Java codes

JAVA & OOPS Manual

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 Boxclass 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

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;

62 | P a g e

Page 64: Java codes

JAVA & OOPS Manual

}

}

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){ //Constructor For BoxWeight

width = w;

height = h;

depth = d;

weight = m;

}

}

class DemoBoxWeight{

public static void main(String args[]){

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

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

double vol;

vol = mybox1.volume();

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

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

System.out.println();

vol = mybox2.volume();

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

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

}

}

Description:

Output:

63 | P a g e

Page 65: Java codes

JAVA & OOPS Manual

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){ // define constructor

width = ob.width; //give value to ob

height = ob.height;

depth = ob.depth;

}

Box(double w, double h, double d){ //define Box constructor

width = w; //declare w

height = h; //declare h

depth = d; //declare d

}

Box() {

width = -1;

height = -1;

depth = -1;

}

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 { //BoxWeight inherited from Box

double weight; //declare weight

BoxWeight(BoxWeight ob) { //constructor define

super(ob); //call super to ob

64 | P a g e

Page 66: Java codes

JAVA & OOPS Manual

weight = ob.weight; //initiliaze weight

}

BoxWeight(double w, double h, double d, double m) { //define constructor with 3 arguments

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); //initialize myBox1

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

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); // print weight of myBox 1

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); // print weight of myBox

65 | P a g e

Page 67: Java codes

JAVA & OOPS Manual

System.out.println(); //print nothing

vol = mybox3.volume(); // declare vol

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

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

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 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. Write a program in which BoxWeight extends to includinf shipping cost.

class Box { // class na,e declare

private double width; //declare width

private double height; //declare height

private double depth; //declare depth

66 | P a g e

Page 68: Java codes

JAVA & OOPS Manual

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) { // constructor used when all dimensions specified

width = w;

height = h;

depth = d;

}

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

width = -1;

height = -1;

depth = -1;

}

Box(double 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 {

double weight; // weight of box

BoxWeight(BoxWeight ob) { // construct clone of an object

super(ob); // pass object to constructor

weight = ob.weight;

}

BoxWeight(double w, double h, double d, double m) { // constructor when all parameters are specified

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

67 | P a g e

Page 69: Java codes

JAVA & OOPS Manual

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) { // construct clone of an object

super(ob); // pass object to constructor

cost = ob.cost;

}

Shipment(double w, double h, double d, double m, double c) { // constructor when all parameters are specified

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 {

68 | P a g e

Page 70: Java codes

JAVA & OOPS Manual

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; //decare vol

vol = shipment1.volume(); // 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(); //decare vol

vol = shipment2.volume(); // 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 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.");

}

}

69 | P a g e

Page 71: Java codes

JAVA & OOPS Manual

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:

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

}

70 | P a g e

Page 72: Java codes

JAVA & OOPS Manual

}

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(); // this calls show() in B

}

}

Description:

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

}

71 | P a g e

Page 73: Java codes

JAVA & OOPS Manual

}

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(); // calls A's version of callme

r = b; // r refers to a B object

r.callme(); // calls B's version of callme

r = c; // r refers to a C object

r.callme(); // calls C's version of callme

}

}

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

72 | P a g e

Page 74: Java codes

JAVA & OOPS Manual

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

73 | P a g e

Page 75: Java codes

JAVA & OOPS Manual

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() {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[]) {

74 | P a g e

Page 76: Java codes

JAVA & OOPS Manual

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

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:

75 | P a g e

Page 77: Java codes

JAVA & OOPS Manual

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

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:

76 | P a g e

Page 78: Java codes

JAVA & OOPS Manual

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:

Q# 82. write a program of try statements class NestTry {

public static void main(String args[]) {try {

int a = args.length;

77 | P a g e

Page 79: Java codes

JAVA & OOPS Manual

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

}}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:

78 | P a g e

Page 80: Java codes

JAVA & OOPS Manual

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; // generate an out-of-bounds exception

}}catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out-of-bounds: " + e);}

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

try {int a = args.length;

//If no command-line args are present, the following statement will generate a divide-by-zero exception

int b = 42 / a;System.out.println("a = " + a);nesttry(a);

}catch(ArithmeticException e) {

System.out.println("Divide by 0: " + e);}

}}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

79 | P a g e

Page 81: Java codes

JAVA & OOPS Manual

Output:

Chapter#13 (String Handling)

Q# 84. Write a program that use override toString () for Box.class Box {

double width;

double height;

double depth;

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:

80 | P a g e

Page 82: Java codes

JAVA & OOPS Manual

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

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

81 | P a g e

Page 83: Java codes

JAVA & OOPS Manual

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[] = {

"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:

82 | P a g e

Page 84: Java codes

JAVA & OOPS Manual

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

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) {

83 | P a g e

Page 85: Java codes

JAVA & OOPS Manual

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;

}

}

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) // main body of programme

throws IOException { //

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

String str; //declare str

System.out.println("Enter 'Stop' to quite. "); // print the line

84 | P a g e

Page 86: Java codes

JAVA & OOPS Manual

System.out.println("Enter State: "); //print line

do { // do while declare

str = br.readLine(); //Call readLine() method to str

str = str.trim(); //remove whitespace

if (str.equals("Illionois")) //define if statement

System.out.println("Capital spring feild."); //print the line

else if (str.equals("Missouri")) //else statement difine

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

else if(str.equals("California")) // otherwise equals method call using if statement

System.out.println("Capital is Scramemento"); // print value

else if (str.equals("Washhington")) //again equls method call using else if statement

System.out.println("Capital is Olampia."); // print capital is olampia.

}

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) { //main body of program start from here

String s = "This is a test."; //declare and initialize s

System.out.println("Orignal sentence:" + s); // print value of s

String upper = s.toUpperCase(); //call toUpperCase() method

85 | P a g e

Page 87: Java codes

JAVA & OOPS Manual

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) {

StringBuffer sb = new StringBuffer ("Hellow");

System.out.println("Buffer before = " + sb);

System.out.println("Char at (1) before = " + sb.charAt(1));

sb.setCharAt(1, 'i');

sb.setLength(2);

System.out.println("buffer after = " + sb);

System.out.println("CharAt(1) after = " + sb.charAt(1));

}

}

Description:

In this program first make class and write main method, after this call StringBuffer() method and declare sb after this print value of sb.

Output:

Q# 93. Write a program that demonstrate append() method .

86 | P a g e

Page 88: Java codes

JAVA & OOPS Manual

class AppendDemo { //class name declare

public static void main (String[] args) { // print main body of program start

String s ; //declare s

int a = 42; declare and initialize a

StringBuffer sb = new StringBuffer (40); // call stringBuffer() method.

s = sb.append("a = ").append(a).append("!").toString();

System.out.println(s); //print value of s

} // ending brace of main body

} //ending brace of class

Description:

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

Output:

Q# 94. Write a program that demonstrate insert() method.lass InsertDemo{

public static void main (String[] args) {

StringBuffer sb = new StringBuffer ("I java");

sb.insert(2, "like "); //insert like on 2 number.

System.out.println(sb); // print value of sb

} //ending brace of main body

} //ending brace of class

Description:

Output:

Q# 95. Write a program that demonstratereplace() method.class ReplaceDemo { // class name start

public static void main (String[] args) { //main body of program start

StringBuffer sb = new StringBuffer ("This is a test."); //Call StringBuffer() method

System.out.println("Before replace: " + sb); //print value of sb

sb.replace(5, 7, "was"); //Call replace method

87 | P a g e

Page 89: Java codes

JAVA & OOPS Manual

System.out.println("After replace : " + sb); //print value of sb after replacing method.

}

}

Description:

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

Output:

Q# 96. Write a program that demonstrate IndexOfDemo () method.public class IndexOfDemo {

public static void main(String[] args) { //main body of program start

String s = " my name is hussain ahmad khan , i am the student of BSCS " +

"gradugate doing from Nfc IEFR Faisalabad Punjab Pakistan.";

System.out.println(s); // print value of s

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

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

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

System.out.println("Last Index of (the) = " + s.lastIndexOf("the")); //print value

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

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

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

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

} //ending brace of main bpdy

} //ending brace of class

Description:

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

Output:

88 | P a g e

Page 90: Java codes

JAVA & OOPS Manual

Chater#09(Package and inter face)

Q# 97. Write a program that that demonstrates package access.package mypack;class Balance {

String name;double bal;Balance(String n, double b){

name = n;bal = b;

}void show (){

if(bal<0)System.out.print("-->");

System.out.print(name + " : $" + bal);}

}public class AccountBalance {

public static void main (String args [] ){Balance current [] = new Balance [3];current [0] = new Balance ("K.J.Fielding", 123.23);current [1] = new Balance ("Will Tell", 157.02);current [2] = new Balance ("Tom Jackson", -12.33);for (int i=0; i<3; i++)

current [i].show();}

}

Description:

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

Output:

Q# 98. Write a program that demonstrates class of one package call in second package.

package p1;

89 | P a g e

Page 91: Java codes

JAVA & OOPS Manual

public class Protection {int n = 1;private int n_pri = 2;protected int n_pro = 3;public int n_pub = 4;public Protection (){

System.out.println("base constructer");System.out.println("n = " + n_pri);System.out.println("n_pro = " + n_pro);System.out.println("n_pro = " + n_pub);

}}

package p1;

class Derived extends Protection {

Derived() {System.out.println("derived constructor");System.out.println("n = " + n);//System.out.println("n_pri = " + n_pri);System.out.println("n_pro = " + n_pro);System.out.println("n_pub = " + n_pub);

}

}

This is class SamePackage.java

package p1;

class SamePackage {SamePackage(){

Protection p = new Protection ();System.out.println("Same package constructor");System.out.println("n = " + p.n);//System.out.println("n_pri = " + p.npri);System.out.println("n_pro = " + p.n_pro);System.out.println("n_pub = " + p.n_pub);

}}

This is file class Protectionism.java

/**

*

*/

package p2;

/**

* @author hussain

*

90 | P a g e

Page 92: Java codes

JAVA & OOPS Manual

*/

class Protection2 extends p1.Protection{

/**

* body

*/

public Protection2() {

System.out.println("Derived other package constructor");

// class or package only

// System.out.println("n = " + n);

//class only

//System.out.println("n_pri = " + n_pri);

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

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

}

}

This is class file OtherPackage.java

/**

*

*/

package p2;

/**

* @author hussain

*

*/

public class OtherPackage {

/**

*

*/

public OtherPackage() {

p1.Protection p = new p1.Protection ();

91 | P a g e

Page 93: Java codes

JAVA & OOPS Manual

System.out.println("Other Package Constructor");

// class or package only

//System.out.println("n = " +p. n);

//class only

//System.out.println("n_pri" + p.n_pri);

//class subclass or package only

//System.out.println("n_pro = " p.n_pro);

System.out.println("n_pub = " + p.n_pub);

// TODO Auto-generated constructor stub

}

}

Now Package p1. java

package p2;

public class Demo {

/** * @param args */public static void main(String[] args) {

Protection2 ob1 = new Protection2 ();OtherPackage ob2 = new OtherPackage();

}

}

The test file for P2 is shown next

package p1;

public class Demo {

/** * @param args */public static void main(String[] args) {

Protection ob1 = new Protection ();Derived ob2 = new Derived();SamePackage ob3 = new SamePackage ();

}

}

Description:

The two classes defined in

92 | P a g e

Page 94: Java codes

JAVA & OOPS Manual

p2 cover the other two conditions which are affected by access control. The first class,

Protection2, is a subclass of p1.Protection. This grants access to all of p1.Protection’s

variables except for n_pri (because it is private) and n, the variable declared with the

default protection. Remember, the default only allows access from within the class or

the package, not extra-package subclasses. Finally, the class OtherPackage has access

to only one variable, n_pub, which was declared public.

Output:

Q# 99. Write a program that demonstrate importing package.

/** * */package mypack;

/** * @author hussain * */public class Balance {

String name;double bal;/** * */public Balance(String n, double b){

name = n;bal = b;

}public void show (){

if(bal<0)System.out.print("-->");

System.out.print(name + " : $" + bal);}

}

93 | P a g e

Page 95: Java codes

JAVA & OOPS Manual

This class is in another class and import package , member of other class

//import java.util.*; import mypack.*;

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

Balance test = new Balance ("J . J . Jasper", 99.98);test.show();

}}

Description:

Balance class is now public. Also, its constructor and its

show( ) method are public, too. This means that they can be accessed by any type of

code outside the MyPack package. For example, here TestBalance imports MyPack

and is then able to make use of the Balance class.

Output:

Q# 100. Write a program that demonstrate fixed storage in interface.package interface9;class FixedStack implements IntStack {

private int stck[];private int tos;// allocate and initialize stackFixedStack(int size) {stck = new int[size];tos = -1;}// Push an item onto the stackpublic void push(int item) {if(tos==stck.length-1) // use length memberSystem.out.println("Stack is full.");elsestck[++tos] = item;}// Pop an item from the stackpublic int pop() {if(tos < 0) {System.out.println("Stack underflow.");return 0;}elsereturn stck[tos--];}}

public class IFTest {

/**

94 | P a g e

Page 96: Java codes

JAVA & OOPS Manual

* @param args */public static void main(String[] args) {

FixedStack mystack1 = new FixedStack(5);FixedStack mystack2 = new FixedStack(8);// push some numbers onto the stackfor(int i=0; i<5; i++) mystack1.push(i);for(int i=0; i<8; i++) mystack2.push(i);// pop those numbers off the stackSystem.out.println("Stack in mystack1:");for(int i=0; i<5; i++)System.out.println(mystack1.pop());System.out.println("Stack in mystack2:");for(int i=0; i<8; i++)System.out.println(mystack2.pop());

}

}

Description:

IntStack that creates a dynamic stack by

use of the same interface definition. In this implementation, each stack is constructed

with an initial length. If this initial length is exceeded, then the stack is increased in

size. Each time more room is needed, the size of the stack is doubled.

Q# 101. Write a program that demonstrate ?package interface9;

//Implement a "growable" stack.class DynStack implements IntStack {

private int stck[];private int tos;

// allocate and initialize stackDynStack(int size) {

stck = new int[size];tos = -1;

}// Push an item onto the stack

public void push(int item) {// if stack is full, allocate a larger stack

if(tos==stck.length-1) {int temp[] = new int[stck.length * 2]; // double sizefor(int i=0; i<stck.length; i++) temp[i] = stck[i];stck = temp;stck[++tos] = item;

}else

stck[++tos] = item;}

// Pop an item from the stackpublic int pop() {

if(tos < 0) {System.out.println("Stack underflow.");return 0;

95 | P a g e

Page 97: Java codes

JAVA & OOPS Manual

}else

return stck[tos--];}

}class IFTest2 {

public static void main(String args[]) {DynStack mystack1 = new DynStack(5);DynStack mystack2 = new DynStack(8);// these loops cause each stack to growfor(int i=0; i<12; i++) mystack1.push(i);for(int i=0; i<20; i++) mystack2.push(i);System.out.println("Stack in mystack1:");for(int i=0; i<12; i++)

System.out.println(mystack1.pop());System.out.println("Stack in mystack2:");for(int i=0; i<20; i++)

System.out.println(mystack2.pop());}

}

Description:

mystack is a reference to the IntStack interface. Thus, when it refers to

ds, it uses the versions of push( ) and pop( ) defined by the DynStack implementation.

When it refers to fs, it uses the versions of push( ) and pop( ) defined by FixedStack.

As explained, these determinations are made at run time. Accessing multiple

implementations of an interface through an interface reference variable is the most

powerful way that Java achieves run-time polymorphism.

Output:

96 | P a g e

Page 98: Java codes

JAVA & OOPS Manual

Q# 102. Write a program that ?package interface9;import java.util.Random;interface SharedConstants {

int NO = 0;int YES = 1;int MAYBE = 2;int LATER = 3;int SOON = 4;int NEVER = 5;

}class Question implements SharedConstants {

Random rand = new Random();int ask() {

int prob = (int) (100 * rand.nextDouble());if (prob < 30)return NO; // 30%else if (prob < 60)

return YES; // 30%else if (prob < 75)

return LATER; // 15%else if (prob < 98)

return SOON; // 13%else

return NEVER; // 2%}

}class AskMe implements SharedConstants {

static void answer(int result) {switch(result) {case NO:

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

97 | P a g e

Page 99: Java codes

JAVA & OOPS Manual

case YES:System.out.println("Yes");break;

case MAYBE:System.out.println("Maybe");

break;case LATER:

System.out.println("Later");break;

case SOON:System.out.println("Soon");break;

case NEVER:System.out.println("Never");break;

}}

public static void main(String args[]) {Question q = new Question();answer(q.ask());answer(q.ask());answer(q.ask());answer(q.ask());}

}

Description:

This

class provides pseudorandom numbers. It contains several methods which allow you

to obtain random numbers in the form required by your program. In this example, the

method nextDouble( ) is used. It returns random numbers in the range 0.0 to 1.0.

In this sample program, the two classes, Question and AskMe, both implement the

SharedConstants interface where NO, YES, MAYBE, SOON, LATER, and NEVER are

defined. Inside each class, the code refers to these constants as if each class had defined

or inherited them directly. Here is the output of a sample run of this program.

Output:

98 | P a g e

Page 100: Java codes

JAVA & OOPS Manual

Q# 103. Write a program that show interface can be extended./**

*

*/

package interface9;

/**

* @author hussain

*

*/

//One interface can extend another.

interface A {

void meth1();

void meth2();

}

// B now includes meth1() and meth2() -- it adds meth3().

interface B extends A {

void meth3();

}

// This class must implement all of A and B

class MyClass implements B {

public void meth1() {

System.out.println("Implement meth1().");

}

public void meth2() {

System.out.println("Implement meth2().");

}

public void meth3() {

System.out.println("Implement meth3().");

}

}

class IFExtend {

public static void main(String arg[]) {

99 | P a g e

Page 101: Java codes

JAVA & OOPS Manual

MyClass ob = new MyClass();

ob.meth1();

ob.meth2();

ob.meth3();

}

}

Description:

you might want to try removing the implementation for meth1( )

in MyClass. This will cause a compile-time error. As stated earlier, any class that

implements an interface must implement all methods defined by that interface,

including any that are inherited from other interfaces

Output:

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

Q# 104. Write a program that read the Character.package readingCharacter;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class BRRead {

public static void main(String args [])

throws IOException {

char c;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

do {

100 | P a g e

Page 102: Java codes

JAVA & OOPS Manual

c = (char) br.read();

System.out.println(c);

} while(c != 'q');

}

}

Description:

This output may look a little different from what you expected, because System.in is

line buffered, by default. This means that no input is actually passed to the program

until you press ENTER. As you can guess, this does not make read( ) particularly

valuable for interactive, console input.

Output:

Q# 105. Write a program that read String./**

*

*/

package readingString;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

/**

* @author hussain

*

*/

public class BRReadLine {

/**

* @param args

101 | P a g e

Page 103: Java codes

JAVA & OOPS Manual

*/

public static void main(String[] args)

throws IOException {

// TODO Auto-generated method stub

// creat a bfferedreader line using system.in

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str;

System.out.println("Ener lines of text.");

System.out.println("Ener 'stop' of quit.");

do{

str = br.readLine();

System.out.println(str);

} while (!str.equals("stop"));

}

}

Description:

To read a string from the keyboard, use the version of readLine( ) that is a member of

the BufferedReader class. following program demonstrates BufferedReader and the readLine( ) method;

the program reads and displays lines of text until you enter the word “stop”:

Output:

Q# 106. Write a program that create a tiny Text editor./**

*

*/

package readingString;

102 | P a g e

Page 104: Java codes

JAVA & OOPS Manual

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

/**

* @author hussain

*

*/

public class TinyEdit {

/**

* @param args

*/

public static void main(String[] args)

throws IOException {

// creat a bfferedreader line using system.in

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str [] = new String[100];

System.out.println("Ener lines of text.");

System.out.println("Ener 'stop' of quit.");

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

str[i] = br.readLine();

if(str[i].equals("stop")) break;

}

System.out.print("\n Here is your file:");

// display the line

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

if (str[i].equals("stop")) break;

System.out.print(str[i]);

}

}

}

103 | P a g e

Page 105: Java codes

JAVA & OOPS Manual

Description:

To read a string from the keyboard, use the version of readLine( ) that is a member of

the BufferedReader class. following program demonstrates BufferedReader and the readLine( ) method;

the program reads and displays lines of text until you enter the word “stop”:

Output:

Q# 107. Write a program that demonstrate System.out.write( )./**

*

*/

package writingconsoeoutput;

/**

* @author hussain

*

*/

public class WriteDemo {

/**

* @param args

*/

public static void main(String[] args) {

int b;

b = 'c';

System.out.print(b);

System.out.write('\n');

}

104 | P a g e

Page 106: Java codes

JAVA & OOPS Manual

}

Description:

There is nothing wrong with using System.out to write simple text

output to the console when you are learning Java or debugging your programs.

However, using a PrintWriter will make your real-world applications easier to

internationalize. Because no advantage is gained by using a PrintWriter in the

sample programs shown in this book, we will continue to use System.out to write

to the console.

Output:

Q# 108. Write a program that demonstrate PrintWriter Class./**

*

*/

package printwriter;

import java.io.PrintWriter;

/**

* @author hussain

*

*/

public class PrintwriterDemo {

/**

* @param args

*/

public static void main(String[] args) {

PrintWriter pw = new PrintWriter (System.out, true);

pw.println("This is a String");

int i = -7;

pw.println(i);

105 | P a g e

Page 107: Java codes

JAVA & OOPS Manual

double d = 4.5e-7;

pw.println(d);

}

}

Description:

The following program uses read( ) to input and display the contents of a text file,

the name of which is specified as a command-line argument. Note the try/catch blocks

that handle the two errors that might occur when this program is used—the specified

file not being found or the user forgetting to include the name of the file. You can use

this same approach whenever you use command-line arguments.

Output:

Q# 109. Write a program that demonstrate a text file. /**

*

*/

package readandwrite;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

/**

* @author hussain

*

*/

public class ShowFile {

/**

* @param args

106 | P a g e

Page 108: Java codes

JAVA & OOPS Manual

*/

public static void main(String[] args)

throws IOException {

int i;

FileInputStream fin;

try {

fin = new FileInputStream(args[0]);

} catch(FileNotFoundException e){

System.out.println("File Not Found");

return;

} catch (ArrayIndexOutOfBoundsException e){

System.out.println("Ener lines of text.");

System.out.println("Usage : ShowFile File");

return;

}

do {

i = fin.read();

if (i != -1) System.out.print((char)i);

} while (i != -1);

fin.close();

}

}

Description:

To write to a file, you will use the write( ) method defined by FileOutputStream.

Its simplest form is shown here:

void write(int byteval) throws IOException

This method writes the byte specified by byteval to the file. Although byteval is declared

as an integer, only the low-order eight bits are written to the file. If an error occurs

during writing, an IOException is thrown

Output:

107 | P a g e

Page 109: Java codes

JAVA & OOPS Manual

Q# 110. Write a program that demonstrate to copy a text file./**

*

*/

package readandwrite;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

/**

* @author hussain

*

*/

public class CopyFile {

/**

* @param args

*/

public static void main(String[] args)

throws IOException{

int i;

FileInputStream fin;

FileOutputStream fout;

try {

// open input file

try {

fin = new FileInputStream(args[0]);

108 | P a g e

Page 110: Java codes

JAVA & OOPS Manual

} catch (FileNotFoundException e){

System.out.print("Input File Not Foud");

return;

}

// open output file

try {

fout = new FileOutputStream(args[1]);

} catch (FileNotFoundException e){

System.out.print("Error oprning output file");

return;

}

} catch(ArrayIndexOutOfBoundsException e){

System.out.print("Usage : CopyFile From To");

return;

}

// copy file

try {

do {

i = fin.read();

if(i != -1) fout.write(i);

} while (i != -1);

}catch (IOException e){

System.out.print("File Error");

}

fin.close();

fout.close();

}

}

Description:

Output:

109 | P a g e

Page 111: Java codes

JAVA & OOPS Manual

Q# 111. Write a program that demonstrate on simple simple Applet method. package AppletFundamental;

import java.applet.Applet;import java.awt.Graphics;

public class SimpleApplet extends Applet {public void paint (Graphics g){

g.drawString("A simple Applet", 20, 20);}

}

Description:

This applet begins with two import statements. The first imports the Abstract Window

Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the

console-based I/O classes. The AWT contains support for a window-based, graphical

interface. As you might expect, the AWT is quite large and sophisticated

Output:

Q# 112. Write a program that demonstrate instanceof () Operator./**

*

110 | P a g e

Page 112: Java codes

JAVA & OOPS Manual

*/

package instanceoof;

/**

* @author hussain

*

*/

class A{

int i,j;

}

class B{

int i,j;

}

class C extends A {

int k;

}

class D extends A {

int k;

}

class Instanceof {

/**

* @param args

*/

public static void main(String[] args) {

A a = new A ();

B b = new B();

C c = new C();

D d = new D();

if(a instanceof A)

System.out.println("a is instanceof of A");

if (b instanceof B)

System.out.println("b is instanceof of B");

111 | P a g e

Page 113: Java codes

JAVA & OOPS Manual

if (c instanceof C)

System.out.println("c is instanceof of C");

if (d instanceof D)

System.out.println("d is instanceof of D");

if (a instanceof C)

System.out.println("a can b cast to C");

System.out.println();

// compare type of derived type

A ob;

ob = d; // a refrence to d

System.out.println("ob now refrence to d");

if (ob instanceof D)

System.out.println("ib is instanceof of D");

System.out.println();

ob = c;

System.out.println("ob now refer to c");

if (ob instanceof D)

System.out.println("ob can b cast to D");

else

System.out.print("ob cannot b cast to D");

if (ob instanceof A)

System.out.print("ob can b cast to A");

System.out.println();

// all object can be cast cast to object

if (a instanceof Object)

System.out.print("a must b cast to Object.");

if (b instanceof Object)

System.out.print("b must b cast to Object.");

if (c instanceof Object)

System.out.print("c must b cast to Object.");

if (d instanceof Object)

System.out.print("d must b cast to Object.");

112 | P a g e

Page 114: Java codes

JAVA & OOPS Manual

}

}

Description:

The instanceof operator isn’t needed by most programs, because, generally, you know

the type of object with which you are working. However, it can be very useful when you’re

writing generalized routines that operate on objects of a complex class hierarchy.

Output:

Q# 113. Write a program that that demonstrate how to use assert.?package assert1;

public class AssertDemo {static int val= 3; // val declare and initializestatic int getnum(){ // getnum() method start

return val--; // return decrement of val value} // ending brace of getnum() methodpublic static void main (String args []){ // main body of program start

from here int n; // declare nfor(int i = 0; i <10; i++){ // for loop

n = getnum(); // call getnum () methodassert n > 0 ; // will fail when n is zeroSystem.out.println("n is" + n); // print value of

n}

}}

Description:

This value is converted to its string format and displayed if an assertion fails. Typically, you

will specify a string for expr, but any non-void expression is allowed as long as it

defines a reasonable string conversion.

Output:

113 | P a g e

Page 115: Java codes

JAVA & OOPS Manual

Chapter#19(The Applet Classes)

Q# 114. Write a program that demonstrates Applet Skelton./**

*

*/

package appletskelton1;

import java.applet.Applet;

import java.awt.Graphics;

/**

* @author hussain

*

*/

public class AppletSkel extends Applet {

//called first

public void init(){

//initlization

}

public void start (){

// start or resume executation

}

public void stop(){

// suspends executation

114 | P a g e

Page 116: Java codes

JAVA & OOPS Manual

}

public void destory (){

// perform shut down activity

}

public void paint (Graphics g){

//redisplay content of window

}

}

Description:

Output:

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

package displaymethod;

import java.applet.Applet;

import java.awt.Color;

import java.awt.Graphics;

public class Sample extends Applet {

//private static final long serialVersionUID = 1L;

String msg;

115 | P a g e

Page 117: Java codes

JAVA & OOPS Manual

// set forgroung and background color

public void init (){

setBackground(Color.cyan);

setForeground(Color.red);

msg = "Inide init( ) --";

}

// initiliaze the string to displaymethod

public void start (){

msg += "Inside start ( ) --";

}

// display msg in applet window

public void paint (Graphics g){

msg += "Inside start ( ).";

g.drawString(msg, 10, 30);

}

}

Description:

The methods stop( ) and destroy( ) are not overridden, because they are not needed

by this simple applet.

Output:

Q# 116. Write a program that demonstrate simple Banner Applet.package bannerapplet3;

116 | P a g e

Page 118: Java codes

JAVA & OOPS Manual

import java.applet.Applet;

import java.awt.Color;

import java.awt.Graphics;

public class SimpleBanner extends Applet implements Runnable{

String msg = "A simple Moving. ";

Thread t = null;

int state;

boolean stopFlag;

public void init (){

setBackground(Color.CYAN);

setForeground(Color.red);

}

public void start (){

t = new Thread (this);

stopFlag = false;

t.start();

}

public void run (){

char ch;

for(;;){

try{

repaint();

Thread.sleep(250);

ch = msg .charAt(0);

msg = msg.substring(1, msg.length());

msg += ch;

if(stopFlag)

break;

} catch (InterruptedException e) {

}

117 | P a g e

Page 119: Java codes

JAVA & OOPS Manual

}

}

public void stop (){

stopFlag = true;

t = null;

}

public void paint (Graphics g){

g.drawString(msg, 50, 30);

}

}

Description:

Let’s take a close look at how this applet operates. First, notice that SimpleBanner

extends Applet, as expected, but it also implements Runnable. This is necessary, since

the applet will be creating a second thread of execution that will be used to scroll the

banner. Inside init( ), the foreground and background colors of the applet are set.

Output:

Q# 117. Write a program that demonstrate showStatus().package statuswindow4;

import java.applet.Applet;

import java.awt.Color;

118 | P a g e

Page 120: Java codes

JAVA & OOPS Manual

import java.awt.Graphics;

public class StatusWindow extends Applet{

public void init (){

setBackground(Color.CYAN);

}

public void paint (Graphics g){

g.drawString("This is an Applet Window.", 10, 20);

showStatus("This is shown in the status window.");

}

}

Description:

The status window

is a good place to give the user feedback about what is occurring in the applet, suggest

options, or possibly report some types of errors. The status window also makes an

excellent debugging aid, because it gives you an easy way to output information about

your applet.

Output:

Q# 118. Write a program that demonstrate passing parameter to Applet.package passingparameter5;

import java.applet.Applet;

119 | P a g e

Page 121: Java codes

JAVA & OOPS Manual

import java.awt.Graphics;

public class ParamDemo extends Applet{

String fontName;

int fontSize;

float leading;

boolean active;

public void start (){

String Param;

fontName = getParameter("fontName");

if(fontName == null)

fontName = "Not Found";

Param = getParameter("fontSize");

try{

if(Param != null)

fontSize = Integer.parseInt(Param);

else

fontSize = 0;

}

catch(NumberFormatException e){

fontSize = -1;

}

Param = getParameter("leading");

try{

if (Param != null)

leading = Float.valueOf(Param).floatValue();

else

leading = 0;

}catch(NumberFormatException e){

leading = -1;

}

Param = getParameter("Account Enabled");

if(Param != null)

120 | P a g e

Page 122: Java codes

JAVA & OOPS Manual

active = Boolean.valueOf(Param).booleanValue();

}

public void Paint (Graphics g){

g.drawString("Font Name", 0, 10);

g.drawString("Font Soze" + fontSize, 0, 26);

g.drawString("Leading" + leading , 0, 42);

g.drawString("Account Active" + active ,0 , 58);

}

}

Description:

It return values from getParameter( ). If a

parameter isn’t available, getParameter( ) will return null. Also, conversions to numeric

types must be attempted in a try statement that catches NumberFormatException.

Uncaught exceptions should never occur within an applet

Output:

Q# 119. Write a program that display code and document bases.package getDocument;

import java.awt.*;import java.applet.*;import java.net.*;/*<applet code="Bases" width=300 height=50></applet>*/public class Bases extends Applet{// Display code and document bases.

public void paint(Graphics g) {String msg;URL url = getCodeBase(); // get code basemsg = "Code base: " + url.toString();g.drawString(msg, 10, 20);url = getDocumentBase(); // get document base

121 | P a g e

Page 123: Java codes

JAVA & OOPS Manual

msg = "Document base: " + url.toString();g.drawString(msg, 10, 40);

}}

Description:

Output:

Q# 120. Write a program that get code and display HTML file.package showDocument8;

import java.awt.*;import java.applet.*;import java.net.*;

public class ACDemo extends Applet{public void start() {

AppletContext ac = getAppletContext();URL url = getCodeBase(); // get url of this applettry {

ac.showDocument(new URL(url+"Test.html"));} catch(MalformedURLException e) {

showStatus("URL not found");}

}}

Description:

AppletContext and showDocument( ).

Upon execution, it obtains the current applet context and uses that context to

transfer control to a file called Test.html. This file must be in the same directory

as the applet. Test.html can contain any valid hypertext that you like.

Output:

122 | P a g e

Page 124: Java codes

JAVA & OOPS Manual

Chapter#20(Events Handling)

Q# 121. Write a program that demonstrate mouse event handler.package handlingmouse1;

//Demonstrate the mouse event handlers.import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="MouseEvents" width=300 height=100></applet>*/public class MouseEvents extends Appletimplements MouseListener, MouseMotionListener {String msg = "";int mouseX = 0, mouseY = 0; // coordinates of mousepublic void init() {addMouseListener(this);addMouseMotionListener(this);}// Handle mouse clicked.public void mouseClicked(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse clicked.";repaint();}// Handle mouse entered.public void mouseEntered(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse entered.";repaint();}

123 | P a g e

Page 125: Java codes

JAVA & OOPS Manual

// Handle mouse exited.public void mouseExited(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse exited.";repaint();}// Handle button pressed.public void mousePressed(MouseEvent me) {

// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "Down";repaint();}// Handle button released.public void mouseReleased(MouseEvent me) {// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "Up";repaint();}// Handle mouse dragged.public void mouseDragged(MouseEvent me) {// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "*";showStatus("Dragging mouse at " + mouseX + ", " + mouseY);repaint();}// Handle mouse moved.public void mouseMoved(MouseEvent me) {// show statusshowStatus("Moving mouse at " + me.getX() + ", " + me.getY());}// Display msg in applet window at current X,Y location.public void paint(Graphics g) {g.drawString(msg, mouseX, mouseY);}

}

Description:

The MouseEvents class extends Applet and

implements both the MouseListener and MouseMotionListener interfaces. These

two interfaces contain methods that receive and process the various types of mouse

events. Notice that the applet is both the source and the listener for these events.

This works because Component, which supplies the addMouseListener( ) and

addMouseMotionListener( ) methods, is a superclass of Applet. Being both the

source and the listener for events is a common situation for applets.

124 | P a g e

Page 126: Java codes

JAVA & OOPS Manual

Inside init( ), the applet registers itself as a listener for mouse events. This is done

by using addMouseListener( ) and addMouseMotionListener( ), which, as mentioned,

are members of Component.

Output:

Q# 122. Write a program that demonstrate key event handler.package handlingkeybord;

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

125 | P a g e

Page 127: Java codes

JAVA & OOPS Manual

}}

Description:

If you want to handle the special keys, such as the arrow or function keys, you need

to respond to them within the keyPressed( ) handler. They are not available through

keyTyped( ).

Output:

Q# 123. Write a program that demonstrate an adapter in event handling.

package adapter;

//Demonstrate an adapter.import java.awt.*;import java.awt.event.*;import java.applet.*;public class AdapterDemo extends Applet {public void init() {addMouseListener(new MyMouseAdapter(this));addMouseMotionListener(new MyMouseMotionAdapter(this));}}class MyMouseAdapter extends MouseAdapter {AdapterDemo adapterDemo;public MyMouseAdapter(AdapterDemo adapterDemo) {

this.adapterDemo = adapterDemo;}// Handle mouse clicked.public void mouseClicked(MouseEvent me) {adapterDemo.showStatus("Mouse clicked");}}class MyMouseMotionAdapter extends MouseMotionAdapter {AdapterDemo adapterDemo;public MyMouseMotionAdapter(AdapterDemo adapterDemo) {

126 | P a g e

Page 128: Java codes

JAVA & OOPS Manual

this.adapterDemo = adapterDemo;}// Handle mouse dragged.public void mouseDragged(MouseEvent me) {adapterDemo.showStatus("Mouse dragged");}}

Description:

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

Output:

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

package inner;

//This applet does NOT use an inner class.import java.applet.*;import java.awt.event.*;/*<applet code="MousePressedDemo" width=200 height=100></applet>*/public class MousePress extends Applet {

public void init() {addMouseListener(new MyMouseAdapter(this));

}}class MyMouseAdapter extends MouseAdapter {

MousePress mousePress;public MyMouseAdapter(MousePress mousePressedDemo) {

this.mousePress = mousePressedDemo;}public void mousePressed(MouseEvent me) {

mousePress.showStatus("Mouse Pressed.");

127 | P a g e

Page 129: Java codes

JAVA & OOPS Manual

}}

Description:

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

Output:

Q# 125. Write a program that demonstrate Anonymous inner class.package anonymousinner;

//Anonymous inner class demo.import java.applet.*;import java.awt.event.*;

public class AnonymousInnerClassDemo extends Applet {public void init() {addMouseListener(new MouseAdapter() {public void mousePressed(MouseEvent me) {showStatus("Mouse Pressed");}});}}

Description:

There is one top-level class in this program: AnonymousInnerClassDemo. The init( )

method calls the addMouseListener( ) method. Its argument is an expression that defines

and instantiates an anonymous inner class. Let’s analyze this expression carefully.

128 | P a g e

Page 130: Java codes

JAVA & OOPS Manual

Output:

129 | P a g e