java lab manual -yna

80
Object Oriented Programming Lab Manual A. Yogananda 1

Upload: amar-singh

Post on 26-Mar-2015

605 views

Category:

Documents


4 download

DESCRIPTION

jntu cse java lab manual

TRANSCRIPT

Page 1: Java Lab Manual -Yna

Object Oriented

Programming Lab

Manual

A. Yogananda 1

Page 2: Java Lab Manual -Yna

Week1 : a) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating that there are no real solutions. import java.io.*; import java.math.*; class RealSolution {

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

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter value for a "); int a=Integer.parseInt(br.readLine()); System.out.println("Enter value for b "); int b=Integer.parseInt(br.readLine()); System.out.println("Enter value for c "); int c=Integer.parseInt(br.readLine()); int d=(b*b)-(4*a*c); if(d>0) {

System.out.println("roots are real distinct"); double r1= -b+(Math.sqrt(d)/(2*a)); double r2= -b-(Math.sqrt(d)/(2*a)); System.out.println("r1 ="+Math.round(r1)+"\n r2="+r2);

} else if(d<0)

System.out.println("roots are imaginary and complex"); else {

} }

}

System.out.println("roots are equal"); double r1= -b/(2*a); double r2= -b/(2*a); System.out.println("r1 ="+Math.round(r1)+"\nr2="+r2);

OUTPUT: C:\nanda>javac RealSolution.java C:\nanda>java RealSolution Enter value for a Enter value for a 1 1 Enter value for b Enter value for b 1 3 Enter value for c Enter value for c 1 2 roots are imaginary and complex roots are real distinct

r1 =-2 r2=-3.5

A. Yogananda 2

Page 3: Java Lab Manual -Yna

b) The Fibonacci sequence is defined by the following rule: The fist two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. import java.io.*; public class Fibonacci {

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

System.out.println("Enter the value for n "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); System.out.println("Fibonacci numbers Using Recursion"); for (int i = 0; i <= n-1; i++) {

int f = fib(i); System.out.println("fib(" + i + ") = " + f);

} System.out.println("Fibonacci numbers with Out Using Recursion"); int a=0,b=1; System.out.print(a+"\t"+b); for(int i=0;i<n-2;i++) {

int c=a+b; a=b; b=c; System.out.print”\t”+(c);

} } public static int fib(int n) {

if (n < 2) return n;

else return fib(n - 1) + fib(n - 2);

} } OUTPUT: C:\nanda\programs>javac Fibonacci.java C:\nanda\programs>java Fibonacci Enter the value for n 5 Fibonacci numbers Using Recursion fib(0) = 0 fib(1) = 1 fib(2) = 1 fib(3) = 2 fib(4) = 3 Fibonacci numbers with Out Using Recursion 0 1 1 2 3

A. Yogananda 3

Page 4: Java Lab Manual -Yna

Week2: a) Write a Java Program that prompts the user for an integer and then prints out all prime numbers up to that integer

import java.io.*; class Prime { public static void main(String[] args)throws IOException

{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter value to print prime numbers up to that number "); int n=Integer.parseInt(br.readLine()); int t; for(int i=1;i<=n;i++) {

t=0; for(int j=1;j<=i;j++) {

if(i%j==0) t++;

} if(t<=2) System.out.print(“ “+i);

} }

} OUTPUT: Enter value to print prime numbers up to that number 10 1 2 3 5 7

A. Yogananda 4

Page 5: Java Lab Manual -Yna

b) Write a Java program to multiply two given matrices. import java.io.*; class Matrix { public static void main(String[] args)throws IOException

{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the No.of rows for First Matrix "); int m=Integer.parseInt(br.readLine()); System.out.println("Enter the No.of columns for First Matrix "); int n=Integer.parseInt(br.readLine()); System.out.println("Enter the No.of rows for Second Matrix "); int p=Integer.parseInt(br.readLine()); System.out.println("Enter the No.of columns for Second Matrix "); int q=Integer.parseInt(br.readLine()); if(n==p) {

int a[][] = new int[m][n]; int a1[][] = new int[p][q]; int a2[][] = new int[m][q]; System.out.println("Enter the "+(m*n) +" elements of First matrix "); for(int i=0;i<m;i++) {

for(int j=0;j<n;j++) a[i][j]=Integer.parseInt(br.readLine());

} System.out.println("Enter the "+(p*q) +" elements of Second matrix "); for(int i=0;i<p;i++) {

for(int j=0;j<q;j++) a1[i][j]=Integer.parseInt(br.readLine());

} System.out.println("First Matrix is ");

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

for(int j=0;j<n;j++) System.out.print(" "+a[i][j]); System.out.println();

} System.out.println("Second Matrix is "); for(int i=0;i<p;i++) {

for(int j=0;j<q;j++) System.out.print(" "+a1[i][j]); System.out.println();

} System.out.println("Resultant Matrix is "); for(int i=0;i<m;i++) {

for(int j=0;j<q;j++) {

A. Yogananda 5

Page 6: Java Lab Manual -Yna

} }

else

for(int k=0;k<p;k++) a2[i][j]=a2[i][j]+a[i][k]*a1[k][j]; System.out.print(" "+a2[i][j]);

} System.out.println();

System.out.println("Multiplication is not possible"); }

} OUTPUT: Enter the No.of rows for First Matrix 3 Enter the No.of columns for First Matrix 3 Enter the No.of rows for Second Matrix 3 Enter the No.of columns for Second Matrix 3 Enter the 9 elements of First matrix 1 2 3 2 3 4 2 2 2 Enter the 9 elements of Second matrix 2 2 2 1 1 1 2 2 2

First Matrix is 1 2 3 2 3 4 2 2 2

Second Matrix is 2 2 2 1 1 1 2 2 2

A. Yogananda 6

Page 7: Java Lab Manual -Yna

Resultant Matrix is 10 10 10 15 15 15 10 10 10

C:\nanda\programs>java Matrix Enter the No.of rows for First Matrix 3 Enter the No.of columns for First Matrix 2 Enter the No.of rows for Second Matrix 3 Enter the No.of columns for Second Matrix 2 Multiplication is not possible

A. Yogananda 7

Page 8: Java Lab Manual -Yna

c) Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (Use StringTokenizer class of java.util)

import java.util.*; import java.io.*; class Stokenizer {

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

System.out.println("Enter the numbers using comma as delimiter "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String in=br.readLine(); StringTokenizer st=new StringTokenizer(in,","); int sum=0; System.out.println("Individual number are:"); while(st.hasMoreTokens()) {

String val=st.nextToken(); System.out.println("\t"+val); int n=Integer.parseInt(val); sum=sum+n;

} System.out.println("Sum of Individual Numbers are:"+sum);

} } OUTPUT : Enter the numbers using comma as delimiter 1,2,3,4,5 Individual number are:

1 2 3 4 5

Sum of Individual Numbers are:15

A. Yogananda 8

Page 9: Java Lab Manual -Yna

Week 3 : a) Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome.

import java.io.*; import java.lang.*; class Palindrom {

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

System.out.println("Enter the String to check whether it is a Palindrom or not"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str= br.readLine(); int n=str.length()-1; int flag=0; for(int i=0;i<(str.length())/2;i++,n--)

{ if(str.charAt(i)!=str.charAt(n))

flag=1; }

if(flag==0) System.out.println("Given string "+ str +" is a palindrom");

else

}

}

System.out.println("Given string "+ str +" is not a palindrom");

Output: Enter the String to check whether it is a Palindrom or not MadaM Given string MadaM is a palindrom

Enter the String to check whether it is a Palindrom or not kurnool Given string kurnool is not a palindrome

A. Yogananda 9

Page 10: Java Lab Manual -Yna

b) Write a Java program for sorting a given list of names in ascending order. import java.io.*; import java.lang.*; class Ascending { public static void main(String[] args)throws IOException { System.out.println("Enter the number of strings for sorting"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String s[]=new String[n]; String temp=null; System.out.println("Enter "+n+" Strings for sorting "); for(int i=0;i<n;i++) {

s[i]=br.readLine(); } for(int i=0;i<n;i++) {

for(int j=i+1;j<n;j++) {

if((s[j].compareTo(s[i]))<0) {

temp=s[i]; s[i]=s[j]; s[j]=temp;

} }

} System.out.println(); System.out.println("Elements after sorting"); for(int i=0;i<n;i++) {

System.out.println(s[i]); }

} } Output: Enter the number of strings for sorting 4 Enter 4 elements for sorting kurnool hyderabad bombay madras

Elements after sorting bombay hyderabad kurnool madras

A. Yogananda 10

Page 11: Java Lab Manual -Yna

c) Write a Java program to make frequency count of words in a given text.

import java.io.*; class FreqCount {

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

int nwords=1; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a string "); String s=br.readLine(); for(int i=0;i<s.length();i++)

if(s.charAt(i)==' ') nwords++;

System.out.println("No of words "+nwords); }

} Output: Enter a string hello hi how r u No of words 5

A. Yogananda 11

Page 12: Java Lab Manual -Yna

Week 4 : a) Write a Java program that reads a file name from the user, then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes.

import java.io.*; class FileInfo {

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

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the File name"); String fname=br.readLine(); File f1=new File(fname); System.out.println("File Name: "+f1.getName()); System.out.println("Path: "+f1.getPath()); System.out.println("Abs Path: "+f1.getAbsolutePath()); System.out.println("Parent: "+f1.getParent()); System.out.println(f1.exists() ? "exists" : "does not exist"); System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); System.out.println(f1.canRead() ? "is readable" : "is not readable"); System.out.println("is "+ (f1.isDirectory() ? "" : "not" + " a directory")); System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); System.out.println("File last modified: "+f1.lastModified()); System.out.println("File size : "+f1.length()+" Bytes");

} }

Output: Enter the File name a.txt File Name: a.txt Path: a.txt Abs Path: D:\nanda\a.txt Parent: null exists is writeable is readable is not a directory is normal file is not absolute File last modified: 1268473188013 File size : 19 Bytes

A. Yogananda 12

Page 13: Java Lab Manual -Yna

/* Using command line arguments */ import java.io.*; class FileInfo {

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

File f1=new File(args[0]); System.out.println("File Name: "+f1.getName()); System.out.println("Path: "+f1.getPath()); System.out.println("Abs Path: "+f1.getAbsolutePath()); System.out.println("Parent: "+f1.getParent()); System.out.println(f1.exists() ? "exists" : "does not exist"); System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); System.out.println(f1.canRead() ? "is readable" : "is not readable"); System.out.println("is "+ (f1.isDirectory() ? "" : "not" + " a directory")); System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); System.out.println("File last modified: "+f1.lastModified()); System.out.println("File size : "+f1.length()+" Bytes");

} } Output: D:\nanda>java FileInfo a.txt File Name: a.txt Path: a.txt Abs Path: D:\nanda\a.txt Parent: null exists is writeable is readable is not a directory is normal file is not absolute File last modified: 1268473188013 File size : 19 Bytes

A. Yogananda 13

Page 14: Java Lab Manual -Yna

b) Write a Java program that reads a file and displays the file on the screen, with a line number before each line. import java.io.*; class LineNumber { public static void main(String[] args)throws IOException {

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the File Name"); String fname=br.readLine(); FileInputStream fin; int i=1,c=1; try

{ fin=new FileInputStream(fname);

} catch(FileNotFoundException e)

{ System.out.println("file cannot open"); return;

} System.out.print(c+":\t");

while(i!=-1) {

if((char)i=='\n') System.out.print(++c+":\t");

i=fin.read(); System.out.print((char)i);

} }

} Output: Enter the File Name a.txt 1: hello 2: hi 3: how r u?

Enter the File Name b.txt file cannot open

A. Yogananda 14

Page 15: Java Lab Manual -Yna

c) Write a Java program that displays the number of characters, lines and words in a text file. import java.io.*; class CountChar1 {

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

int ch; int char_ct=0; int word_ct=0; int line_ct=1; FileInputStream fin; try {

fin=new FileInputStream(args[0]); } catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Should Enter File name with extension at Run Time"); return;

} while((ch=fin.read())!=-1) {

++char_ct; if( ch==' ' || ch=='\t')

++word_ct; if(ch=='\n')

++line_ct; } word_ct+=line_ct; System.out.println("No of Chars:"+char_ct); System.out.println("No of Words:"+word_ct); System.out.println("No of Lines:"+line_ct); fin.close();

} } Output: D:\nanda>javac CountChar1.java D:\nanda>java CountChar1 a.txt No of Chars:32 No of Words:9 No of Lines:3 D:\nanda>java CountChar1 Should Enter File name with extension at Run Time

a.txt hello hi how r u wht r u doing

A. Yogananda 15

Page 16: Java Lab Manual -Yna

import java.io.*; class CountChar {

(or)

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

int ch; int char_ct=0; int word_ct=1; int line_ct=1; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the File Name With Extention"); String fname=br.readLine(); FileInputStream fin=new FileInputStream(fname); while((ch=fin.read())!=-1) {

char_ct++; switch((char)ch) {

case ' ' : case '\t':

case '\n':

}

}

word_ct++; break;

line_ct++; word_ct++; break;

} Output:

System.out.println("No of Chars:"+char_ct); System.out.println("No of Words:"+word_ct); System.out.println("No of Lines:"+line_ct); fin.close(); }

Enter the File Name with Extension a.txt No of Chars:32 No of Words:9 No of Lines:3

a.txt hello hi how r u wht r u doing

A. Yogananda 16

Page 17: Java Lab Manual -Yna

Week 5a Write a Java program that Implements stack ADT

import java.io.*; interface stack { int push(int x); int pop(); void display();

} class Astack implements stack {

int e[]; int max,lsize,t; Astack(int initcap) {

max=initcap; lsize=0; t = -1; e=new int[initcap];

} public int push(int x) {

if(lsize==max || t==max) return 1;

else {

e[++t]=x; lsize++; return 0;

} } public int pop() { if(t<0|| lsize==0) return 0;

else {

int x=e[t--]; lsize--; return x;

} } public void display() {

for(int i=t;i>=0;i--) System.out.println(" "+e[i]);

} }

A. Yogananda 17

Page 18: Java Lab Manual -Yna

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

int i,n,t,ch; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the size of the matrix:"); n=Integer.parseInt(br.readLine()); Astack a=new Astack(n); while(1==1)

{ System.out.println("1.push\n2.pop\n3.display\n4.exit"); System.out.println("\nenter ur choice:"); ch=Integer.parseInt(br.readLine()); switch(ch) {

case 1: System.out.println("\nenter a element:");

i=Integer.parseInt(br.readLine()); t=a.push(i); if(t==1) {

System.out.println("\nSTACK IS FULL"); break;

} break;

case 2: t=a.pop(); if(t==0) {

System.out.println("\nSTACK IS EMPTY"); break;

} else System.out.println("\nelement popped is:"+t); break;

case 3: System.out.println("\nELEMENTS IN THE STACK ARE:"); a.display(); break;

case 4:

return;

default: System.out.println("\nwrong option"); }

} }

} OUTPUT: enter the size of the matrix: 3 1.push 2.pop 3.display

A. Yogananda 18

Page 19: Java Lab Manual -Yna

4.exit

enter ur choice: 1

enter a element: 12 1.push 2.pop 3.display 4.exit

enter ur choice: 1

enter a element: 13 1.push 2.pop 3.display 4.exit

enter ur choice: 1

enter a element: 14 1.push 2.pop 3.display 4.exit

enter ur choice: 1 enter a element: 15 STACK IS FULL 1.push 2.pop 3.display 4.exit

enter ur choice: 3

ELEMENTS IN THE STACK ARE: 14 13 12 1.push 2.pop

A. Yogananda 19

Page 20: Java Lab Manual -Yna

3.display 4.exit

enter ur choice: 2

element popped is:14 1.push 2.pop 3.display 4.exit

enter ur choice: 4

A. Yogananda 20

Page 21: Java Lab Manual -Yna

b) Write a java program that Converts Infix expression into Postfix form import java.io.*; public class Week5b { private Stack theStack; private String input; private String output = ""; public Week5b(String in) {

input = in; int stackSize = input.length(); theStack = new Stack(stackSize);

} public String doTrans() { for (int j = 0; j < input.length(); j++) { char ch = input.charAt(j); switch (ch) { case '+': case '-':

gotOper(ch, 1); break; // (precedence 1)

case '*': // it's * or / case '/':

gotOper(ch, 2); // go pop operators break; // (precedence 2)

case '(': // it's a left paren theStack.push(ch); // push it break;

case ')': // it's a right paren gotParen(ch); // go pop operators break;

default: // must be an operand output = output + ch; // write it to output break;

} } while (!theStack.isEmpty()) {

output = output + theStack.pop(); } System.out.println(output);

return output; // return postfix } public void gotOper(char opThis, int prec1) { while (!theStack.isEmpty())

A. Yogananda 21

Page 22: Java Lab Manual -Yna

{ char opTop = theStack.pop(); if (opTop == '(') { theStack.push(opTop); break;

} // it's an operator else { // precedence of new op

int prec2; if (opTop == '+' || opTop == '-')

prec2 = 1; else

prec2 = 2; if (prec2 < prec1) // if prec of new op less { // than prec of old theStack.push(opTop); // save newly-popped op break;

} else // prec of new not less output = output + opTop; // than prec of old

} } theStack.push(opThis);

} public void gotParen(char ch) { while (!theStack.isEmpty()) { char chx = theStack.pop(); if (chx == '(') break;

else output = output + chx;

} } public static void main(String[] args) throws IOException { String input =""; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter infix expression:"); input=br.readLine(); String output; Week5b theTrans = new Week5b(input); output = theTrans.doTrans(); System.out.println("Postfix is " + output + '\n');

} class Stack { private int maxSize; private char[] stackArray;

A. Yogananda 22

Page 23: Java Lab Manual -Yna

private int top; public Stack(int max) {

maxSize = max; stackArray = new char[maxSize]; top = -1;

} public void push(char j) {

stackArray[++top] = j; } public char pop() { return stackArray[top--];

} public char peek() {

return stackArray[top]; } public boolean isEmpty() {

return (top == -1); }

} } Output: D:\nanda>javac Week5b.java D:\nanda>java Week5b enter infix expression: a+b*c-d abc*+d- Postfix is abc*+d-

A. Yogananda 23

Page 24: Java Lab Manual -Yna

c) Write a java program that evaluates the Postfix expression import java.io.*; public class Week5c { private Stack theStack; private String input; public Week5c(String s) { input = s;

} public int doParse() { theStack = new Stack(50); char ch; int j; int k; int num1, num2, interAns; BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); for (j = 0; j < input.length(); j++) { ch = input.charAt(j); if(ch>='a'&&ch<='z') { try {

System.out.println("enter a value for"+ch+":"); k=Integer.parseInt(b.readLine()); //theStack.displayStack("" + ch + " "); theStack.push(k);

} catch(Exception e) { }

} else // it's an operator { num2 = theStack.pop(); num1 = theStack.pop(); switch (ch)

{ case '+':

case '-':

case '*':

case '/':

interAns = num1 + num2; break;

interAns = num1 - num2;

break; interAns = num1 * num2;

break;

A. Yogananda 24

Page 25: Java Lab Manual -Yna

default:

}

}

}

interAns = num1 / num2; break;

interAns = 0;

theStack.push(interAns);

interAns = theStack.pop(); return interAns;

} public static void main(String[] args) throws IOException { String input = " "; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter a postfix expression:"); input=br.readLine(); int output; Week5c aParser = new Week5c(input); output = aParser.doParse(); System.out.println("Evaluates to " + output);

} class Stack {

private int maxSize; private int[] stackArray; private int top; public Stack(int size) { maxSize = size; stackArray = new int[maxSize]; top = -1;

} public void push(int j) { stackArray[++top] = j;

} public int pop() {

return stackArray[top--]; } public int peek() {

return stackArray[top]; } public boolean isEmpty() {

return (top == -1); } public boolean isFull() {

A. Yogananda 25

Page 26: Java Lab Manual -Yna

return (top == maxSize - 1); } public int size() {

return top + 1; } public int peekN(int n) { return stackArray[n];

} public void displayStack(String s) {

System.out.print(s); System.out.print("Stack (bottom>top): "); for (int j = 0; j < size(); j++)

{ System.out.print(peekN(j)); System.out.print(' ');

} System.out.println("");

} } } Output: enter a postfix expression: abc*+d- enter a value fora: 6 enter a value forb: 2 enter a value forc: 2 enter a value ford: 6 Evaluates to 4

A. Yogananda 26

Page 27: Java Lab Manual -Yna

Week 6 : a)Develop an applet that displays a simple message.

import java.applet.*; import java.awt.*; /*<applet code="Week6a" width=400 height=200></applet>*/ public class Week6a extends Applet {

public void paint(Graphics g) {

g.drawString("Welcome to Applet Programming",60,60); }

} OUTPUT: D:\nanda>javac Week6a.java D:\nanda>appletviewer Week6a.java

Save as Week6a.java import java.applet.*; import java.awt.*;

public class Week6a extends Applet {

public void paint(Graphics g) {

(or)

setBackground(Color.blue); g.setColor(Color.orange);

g.drawString("Welcome to Applet Programming",60,60); }

}

A. Yogananda 27

Page 28: Java Lab Manual -Yna

Save the file with an extension .html (applet.html) <HTML> <applet code="Week6a" width=400 height=200></applet> </HTML>

A. Yogananda 28

Page 29: Java Lab Manual -Yna

b) Develop an applet that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named “Compute” is clicked.

import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="Week6b" width=250 height=250></applet>*/ public class Week6b extends Applet implements ActionListener {

TextField t1,t2; Button compute,reset;

public void init() {

compute=new Button("COMPUTE"); reset=new Button("RESET"); Label l3=new Label("Finding the Factorial of a given Number"); Label l1=new Label("Enter a no: ",Label.RIGHT); Label l2=new Label("Factorial is:",Label.RIGHT); t1=new TextField(10); t2=new TextField(10); add(l3); add(l1); add(t1); add(l2); add(t2); add(compute); add(reset); compute.addActionListener(this); reset.addActionListener(this);

} public void actionPerformed(ActionEvent ae) {

String str=ae.getActionCommand(); if(str.equals("COMPUTE")) {

int f=1; int n=Integer.parseInt(t1.getText()); for(int i=1;i<=n;i++) f=f*i; t2.setText(String.valueOf(f));

} else

{

} }

}

t1.setText(""); t2.setText("");

A. Yogananda 29

Page 30: Java Lab Manual -Yna

Output: D:\nanda>javac Week6b.java D:\nanda>appletviewer Week6b.java

A. Yogananda 30

Page 31: Java Lab Manual -Yna

Week 7: Write a Java program that works as a simple calculator. Use to buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.

import java.io.*; import java.applet.*; import java.awt.event.*; import java.awt.*; /*<applet code=" SimpleCalculator " width=150 height=150></applet>*/ public class SimpleCalculator extends Applet implements ActionListener {

Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,reset; TextField t1; int n1,n2,r; String temp="",s=""; public void init() {

b1=new Button("0"); b2=new Button("1"); b3=new Button("2"); b4=new Button("3"); b5=new Button("4"); b6=new Button("5"); b7=new Button("6"); b8=new Button("7"); b9=new Button("8"); b10=new Button("9"); b11=new Button("+"); b12=new Button("-"); b13=new Button("*"); b14=new Button("%"); b15=new Button("="); reset=new Button("Reset"); t1=new TextField(15); add(t1); add(b1); add(b2); add(b3); add(b4); add(b5); add(b6); add(b7); add(b8); add(b9); add(b10); add(b11); add(b12); add(b13); add(b14); add(b15); add(reset);

A. Yogananda 31

Page 32: Java Lab Manual -Yna

b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); b10.addActionListener(this); b11.addActionListener(this); b12.addActionListener(this); b13.addActionListener(this); b14.addActionListener(this); b15.addActionListener(this); reset.addActionListener(this);

} public void actionPerformed(ActionEvent ae) {

String str=ae.getActionCommand(); if(str.equals("0")) {

temp+=str; t1.setText(temp);

} if(str.equals("1")) {

temp+=str; t1.setText(temp);

} else if(str.equals("2")) {

temp+=str; t1.setText(temp);

} else if(str.equals("3")) {

temp+=str; t1.setText(temp);

} else if(str.equals("4")) {

temp+=str; t1.setText(temp);

} else if(str.equals("5")) {

temp+=str; t1.setText(temp);

} else if(str.equals("6"))

A. Yogananda 32

Page 33: Java Lab Manual -Yna

{ temp+=str; t1.setText(temp);

}

else if(str.equals("7")) {

temp+=str; t1.setText(temp);

} else if(str.equals("8")) {

temp+=str; t1.setText(temp);

} else if(str.equals("9")) {

temp+=str; t1.setText(temp);

} else if(str.equals("+")) {

s=str; t1.setText("+"); n1=Integer.parseInt(temp); temp="";

} else if(str.equals("*")) {

s=str; t1.setText("*"); n1=Integer.parseInt(temp); temp="";

} else if(str.equals("-")) {

s=str; t1.setText("-"); n1=Integer.parseInt(temp); temp="";

} else if(str.equals("%")) {

s=str; t1.setText("%"); n1=Integer.parseInt(temp); temp="";

} else if(str.equals("=")) {

A. Yogananda 33

Page 34: Java Lab Manual -Yna

n2=Integer.parseInt(temp); if(s.equals("+")) r=n1+n2; else if(s.equals("-")) r=n1-n2; else if(s.equals("*")) r=n1*n2; else r=n1%n2; t1.setText(String.valueOf(r)); temp="";

} else if(str.equals("Reset")) {

t1.setText("0"); }

} } Output:

A. Yogananda 34

Page 35: Java Lab Manual -Yna

Week 8: Java program for handling mouse events.

import java.awt.*; import java.awt.font.*; import java.awt.event.*; import java.applet.*; /* <applet code="MouseEvents" width=350 height=350> </applet> */ public class MouseEvents extends Applet

implements MouseListener, MouseMotionListener { String msg = "Nothing"; int X = 20, Y = 20; // coordinates of mouse public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { // Handle mouse clicked.

X = 0; // save coordinates Y = 10; msg = "Mouse clicked."; setForeground(Color.cyan); setBackground(Color.red); repaint(); } public void mouseEntered(MouseEvent me) { // Handle mouse entered. msg = "Mouse entered."; setForeground(Color.blue); setBackground(Color.white); repaint(); } public void mouseExited(MouseEvent me) { // Handle mouse exited. setBackground(Color.white); msg = "Mouse exited."; repaint(); } public void mousePressed(MouseEvent me) { // Handle button pressed. X = me.getX(); // save coordinates

Y = me.getY(); Font b=new Font("Arial",Font.ITALIC,15); setFont(b); msg = "Mouse Pressed"; setBackground(Color.green); setForeground(Color.black); repaint(); } public void mouseReleased(MouseEvent me) { // Handle button released. Font a=new Font("Algerian",Font.PLAIN,25);

A. Yogananda 35

Page 36: Java Lab Manual -Yna

setFont(a); X = me.getX(); Y = me.getY(); msg = "Mouse Released"; repaint(); } public void mouseDragged(MouseEvent me) { // Handle mouse dragged. X = me.getX(); Y = me.getY(); msg = "Mouse Dragged"; showStatus("Dragging mouse at " + X + ", " + Y); repaint(); } public void mouseMoved(MouseEvent me) { // Handle mouse moved. // show status msg="Moving Mouse"; showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); repaint(); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) {

g.drawString(msg, X, Y); }

} Output:

A. Yogananda 36

Page 37: Java Lab Manual -Yna

A. Yogananda 37

Page 38: Java Lab Manual -Yna

Week 9a:

Write a Java program that creates three threads. First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds. class A implements Runnable {

String tname; Thread t; A(String tn)

{ t=new Thread(this,tn); tname=tn; t.start();

} public void run() {

try {

if(tname.equals("GoodMorning")) for(int i=0;i<7;i++)

{ System.out.println(tname+" "+i); t.sleep(1000);

} else if(tname.equals("Hello")) for(int i=0;i<6;i++)

{ System.out.println(tname+" "+i); t.sleep(2000);

} else if(tname.equals("Welcome")) for(int i=0;i<5;i++)

{ System.out.println(tname+" "+i); t.sleep(3000);

} }

catch(Exception e) {

System.out.println(e); }

} } class Week9a{ public static void main(String[] args) { A a=new A("GoodMorning"); A d=new A("Hello"); A c=new A("Welcome"); } }

A. Yogananda 38

Page 39: Java Lab Manual -Yna

Output: GoodMorning 0 Hello 0 Welcome 0 GoodMorning 1 Hello 1 GoodMorning 2 Welcome 1 GoodMorning 3 Hello 2 GoodMorning 4 GoodMorning 5 Hello 3 Welcome 2 GoodMorning 6 Hello 4 Welcome 3 Hello 5 Welcome 4

A. Yogananda 39

Page 40: Java Lab Manual -Yna

Week9b:

Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.

class Q {

int n; boolean valueSet=false; synchronized int get() {

while(!valueSet) try{

wait(); }

catch(InterruptedException e) {

System.out.println("InterruptedException caught"); } System.out.println("Got:"+n); valueSet=false; notify(); return n;

} synchronized void put(int n) {

while(valueSet) try{

wait(); }

catch(InterruptedException e) {

System.out.println("InterruptedException caught"); } this.n= n; valueSet=true; System.out.println("Put:"+n); notify();

} } class Producer implements Runnable {

Q q; Producer(Q q) {

this.q=q; new Thread(this,"producer").start();

} public void run() {

int i=0; while(true) {

A. Yogananda 40

Page 41: Java Lab Manual -Yna

q.put(i++); }

} } class Consumer implements Runnable {

Q q; Consumer(Q q) {

this.q=q; new Thread(this,"consumer").start();

} public void run() {

while(true) {

q.get(); }

} } class Pc {

public static void main(String[] args) {

} } Output:

Q q=new Q(); new Producer(q); new Consumer(q); System.out.println("press control+c to stop");

press control+c to stop Put:0 Got:0 Put:1 Got:1 Put:2 Got:2 Put:3 Got:3 Put:4 Got:4 Put:5 Got:5 Put:6 Got:6 Put:7 Got:7 Put:8 Got:8

A. Yogananda 41

Page 42: Java Lab Manual -Yna

Week10: Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the textfields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a NumberFormatException. If Num2 were Zero, the program would throw an ArithmeticException Display the exception in a message dialog box.

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class We10 extends JFrame implements ActionListener { Container c; JButton btn,btn1; JLabel l1,l2,l3; JTextField t1,t2,t3; JPanel p; We10()

{ super("Exception Handler"); c=getContentPane(); c.setBackground(Color.red); btn=new JButton("Div"); btn.addActionListener(this); t1=new JTextField(15); t2=new JTextField(15); t3=new JTextField(15); l1=new JLabel("Num1"); l2=new JLabel("Num2"); l3=new JLabel("Res"); p=new JPanel(); p.setLayout(new GridLayout(2,3)); p.add(l1);p.add(l2);p.add(l3); p.add(t1);p.add(t2);p.add(t3); c.add(new JLabel("Division"),"North"); c.add("Center",p); c.add("South",btn);

} public void actionPerformed(ActionEvent e) {

if(e.getSource()==btn) {

try {

}

int a=Integer.parseInt(t1.getText()); int b=Integer.parseInt(t2.getText()); float c= a/b; t3.setText(""+c);

catch(NumberFormatException nf) {

A. Yogananda 42

Page 43: Java Lab Manual -Yna

t3.setText(" "); JOptionPane.showMessageDialog(this,"only int div");

} catch(ArithmeticException ae) {

t3.setText(" "); JOptionPane.showMessageDialog(this," div / 0 error");

} }

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

We10 w=new We10(); w.setSize(400,400); w.setVisible(true);

w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

} C:\nanda\programs>javac We10.java C:\nanda\programs>java We10 Output:

A. Yogananda 43

Page 44: Java Lab Manual -Yna

Week 11 : Write a Java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. For ex: The data sent from the client is enter the file name, and the result produced by the server is the content of that file. (Use java.net)

import java.net.*; import java.io.*; public class Client { public static void main(String a[]) throws Exception { String s1;

Socket s=new Socket(InetAddress.getLocalHost(),95); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); while((s1=br.readLine())!=null) System.out.println(s1);

br.close(); s.close();

} }

Server.java

import java.net.*; import java.io.*; import java.lang.*; public class Server { public static void main(String a[])throws Exception { ServerSocket ss=new ServerSocket(95); Socket s=ss.accept(); PrintWriter pw=new PrintWriter(s.getOutputStream(),true); String in,out; BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter a file name"); String s1=br1.readLine(); File f=new File(s1); if(f.exists()) { BufferedReader br2=new BufferedReader(new FileReader(s1));

while((in=br2.readLine())!=null) { pw.write(in); pw.flush(); } br2.close();

A. Yogananda 44

Page 45: Java Lab Manual -Yna

} pw.close(); s.close(); ss.close();

} } Output: First Compile Both the files in two different Command prompts ,afterwards start the Server by running it and then run the Client then it is going to display information (enter a file name) in server after entering the required information the result will be displayed in the Client.

A. Yogananda 45

Page 46: Java Lab Manual -Yna

Week12 a) Write a java program that simulates a traffic light. The program lets the user select one of three lights:

red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be

on at a time No light is on when the program starts. import java.awt.*; import java.awt.event.*;

class Radioex extends Frame implements ItemListener

{

String msg="";

CheckboxGroup cbg;

Checkbox r,y,g;

Radioex()

{

setLayout(new FlowLayout());

cbg=new CheckboxGroup();

r=new Checkbox("Red",cbg,false);

y=new Checkbox("Yellow",cbg,false);

g=new Checkbox("Green",cbg,false);

add(r);

add(y); add(g);

r.addItemListener(this);

y.addItemListener(this);

g.addItemListener(this);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we)

{

}

});

}

System.exit(0);

public void itemStateChanged(ItemEvent ie)

{

repaint();

}

public void paint(Graphics g)

{

if((cbg.getSelectedCheckbox().getLabel()).equals("Red"))

{

g.setColor(Color.red);

g.fillOval(90,70,80,80);

}

else if((cbg.getSelectedCheckbox().getLabel()).equals("Yellow"))

{

g.setColor(Color.yellow);

g.fillOval(90,70,80,80);

}

else if((cbg.getSelectedCheckbox().getLabel()).equals("Green"))

{

g.setColor(Color.green);

g.fillOval(90,70,80,80);

}

}

A. Yogananda 46

Page 47: Java Lab Manual -Yna

public static void main(String[] args)

{

Radioex rd=new Radioex();

rd.setSize(400,400);

rd.setVisible(true);

}

}

Output:

A. Yogananda 47

Page 48: Java Lab Manual -Yna

b) Write a Java program that allows the user to draw lines, rectangles and ovals. import java.awt.*; import java.awt.event.*; class Draw1 extends Frame { Draw1()

{

{

} });

this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we) System.exit(0); // close the application

} public void paint(Graphics g) {

g.setColor(Color.orange); g.drawRect(40,40,150,150); g.setColor(Color.yellow); g.fillOval(90,70,80,80); //face g.setColor(Color.black); g.fillOval(110,95,5,5); // eyes g.fillOval(145,95,5,5); g.drawLine(130,95,130,115); g.setColor(Color.red); g.fillArc(113,115,35,20,0,-180); //mouth

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

Draw1 d=new Draw1(); d.setSize(400,400); d.setTitle("My drawing"); d.setVisible(true);

} } Output: D:\nanda>javac Draw1.java D:\nanda>java Draw1

A. Yogananda 48

Page 49: Java Lab Manual -Yna

Week 13 : a) Write a java program to create an abstract class named Shape that contains an empty method named numberOfSides ( ).Provide three classes named Trapezoid, Triangle and Hexagon such that each one of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that tells the number of sides. abstract class shapes { abstract void numberOfSides(); } class Trapezoid extends shapes { void numberOfSides() { System.out.println("Trapezoid contains 4 sides"); } } class Triangle extends shapes { void numberOfSides() { System.out.println("Triangle contain 3 sides"); } } class Hexagon extends shapes { void numberOfSides() { System.out.println("Hexagon contains 6 sides"); } } class Week13 { public static void main(String[] args) { Trapezoid t=new Trapezoid(); Triangle e=new Triangle(); Hexagon h=new Hexagon(); t.numberOfSides(); e.numberOfSides(); h.numberOfSides();

} } Output: Trapezoid contains 4 sides Triangle contain 3 sides Hexagon contains 6 sides

A. Yogananda 49

Page 50: Java Lab Manual -Yna

b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the

header, and the remaining lines correspond to rows in the table. The elements are separated by

commas. Write a java program to display the table using Jtable component.

DataFileTableModel.java

import javax.swing.*; import javax.swing.table.*; import javax.swing.event.*; import java.io.*; import java.util.*;

public class DataFileTableModel extends AbstractTableModel {

protected Vector data; protected Vector columnNames ; protected String datafile;

public DataFileTableModel(String f){

datafile = f; initVectors(); }

public void initVectors() { String aLine ; data = new Vector(); columnNames = new Vector(); try { FileInputStream fin = new FileInputStream(datafile); BufferedReader br = new BufferedReader(new InputStreamReader(fin)); // extract column names StringTokenizer st1 =

new StringTokenizer(br.readLine(), ","); while(st1.hasMoreTokens()) columnNames.addElement(st1.nextToken());

// extract data while ((aLine = br.readLine()) != null) {

StringTokenizer st2 = new StringTokenizer(aLine, ",");

while(st2.hasMoreTokens()) data.addElement(st2.nextToken()); }

br.close(); }

catch (Exception e) { e.printStackTrace(); }

}

public int getRowCount() { return data.size() / getColumnCount(); }

public int getColumnCount(){

return columnNames.size(); }

A. Yogananda 50

Page 51: Java Lab Manual -Yna

public String getColumnName(int columnIndex) { String colName = "";

if (columnIndex <= getColumnCount())

colName = (String)columnNames.elementAt(columnIndex);

return colName; }

public Class getColumnClass(int columnIndex){

return String.class; }

public boolean isCellEditable(int rowIndex, int columnIndex) {

return false; }

public Object getValueAt(int rowIndex, int columnIndex) {

return (String)data.elementAt ( (rowIndex * getColumnCount()) + columnIndex);

}

public void setValueAt(Object aValue, int rowIndex, int columnIndex) { return; }

}

DataFileTable.java import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*;

public class DataFileTable extends JPanel {

public DataFileTable(String dataFilePath) { JTable table;

DataFileTableModel model; Font f;

f = new Font("SanSerif",Font.PLAIN,24); setFont(f); setLayout(new BorderLayout());

model = new DataFileTableModel(dataFilePath);

table = new JTable(); table.setModel(model); table.createDefaultColumnsFromModel();

JScrollPane scrollpane = new JScrollPane(table); add(scrollpane); }

A. Yogananda 51

Page 52: Java Lab Manual -Yna

Sunil kumar P.N.V 52

public Dimension getPreferredSize(){ return new Dimension(400, 300); }

public static void main(String s[]) {

JFrame frame = new JFrame("Data File Table"); DataFileTable panel;

panel = new DataFileTable("customers.txt");

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setForeground(Color.black); frame.setBackground(Color.lightGray); frame.getContentPane().add(panel,"Center");

frame.setSize(panel.getPreferredSize()); frame.setVisible(true); frame.addWindowListener(new WindowCloser()); }

} class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.getWindow(); win.setVisible(false);

System.exit(0); }

}

Customers.txt

Id,Name,City,Phone 102,Beth Reiser,New York,(212)5558725 111,Dylan Ricci,Syracuse,(315)5554486 116,Brian Gugliuzza,Mamaroneck,(914)5553817 120,Gertrude Stein,Elmsford,(914)5553476 131,Daljit Sinnot,Bohemia,(516)5559811

Output:

Or

Page 53: Java Lab Manual -Yna

Sunil kumar P.N.V 53

import java.awt.*; import javax.swing.*; /*<applet code="Table" width=500 height=500>

</applet> */ public class Table extends JApplet {

public void init() {

} }

Output:

Container cp=getContentPane(); cp.setLayout(new BorderLayout()); final String[] head={"Name","Qualification","Address"}; final Object[][] data={{"Hari","B.Tech","HYD"},

{"Ravi","M.Tech","KNL"}, {"Kalyan","M.Tech","KNL"}};

JTable t=new JTable(data,head); int i=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int m=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane j=new JScrollPane(t,i,m); cp.add(j,BorderLayout.CENTER);

Page 54: Java Lab Manual -Yna

Sunil kumar P.N.V 54

Privat

e

Publi

c

Protecte

d

No

modifier

Same class No Yes Yes Yes

Interview Questions:

1) OOPS concepts

Polymorphism

Ability to take more than one form, In java we achieve this using Method Overloading

(compile time polymorphism), Method overriding (runtime polymorphism)

Inheritance

Is the process by which one object acquires the properties of another object.

Encapsulation

Wrapping of data and function into a single unit called encapsulation. Ex:- all java programs.

Abstraction

Nothing but representing the essential futures without including background details.

Dynamicbinding

Code associated with a given procedural call is not known until the time of the call at runtime.

Dynamic binding is nothing but late binding.

2) class & object?

Kclass is a Template that describes the Kind of State(The Instance Variables) and Behavior

(Methods)

Kclass is a blue print of an object, component means u can use a piece of code like an independent

piece.like

Object \ instance of class, u can reuse it in any application

3) System.out.println()

K println() is a methd of java.io.printWriter.

\ “out” is an instance variable of java.lang.System class.

4) Transient & volatile

Transient --> the object or variable will not persist.

Volatile --> value will be changed unexpectedly by the other part of the program.

5) Access Specifiers & Access modifiers?

Access Specifiers K A.S gives access privileges to outside of application (or) others; they are Public,

Protected, Private, Defaults

Access Modifiers K A.M which gives additional meaning to data, methods and classes, final cannot

be modified at any point of time.

Page 55: Java Lab Manual -Yna

Sunil kumar P.N.V 55

Same package Subclass No Yes Yes Yes

Same package non-subclass No Yes Yes Yes

Different package subclass No Yes Yes No

Different package non-

subclass

No Yes No NO

6) Default Values

long \ -2^63 to 2^63 –1 \ 0L

Int \ -2^31 to 2^31 –1 \ 0

Short \ -2^15 to 2^15 –1 \ 0

Byte \ -2^7 to 2^7 –1 \ 0

char \ 0 to 2^7 –1 \ null character (or) „\u 0000‟

double \ 0.0d

float \ 0.0f

Boolean \ false

Character \ „\u0000‟

7) Byte code & JIT compiler

Byte code is a highly optimized set of instructions. JVM is an interpreter for byte code.

Translating a java program into byte code helps makes it much easier to run a program in a wide

variety of environment.

JIT is a part of JVM, it compiles byte code into executable code in real time, will increase the

performance of the interpretations.

8) Wrapper classes

Primitive data types can be converted into objects by using wrapper classes. These are

java.lang.package.

9) Does Java pass method arguments by value or by reference?

A) Java passes all arguments by value, not by reference

10) Arguments & Parameters

While defining method, variable passed in the method are called parameters. While using those

methods, values passed to those variables are called arguments.

11) Public static void main (String [] args)

K What if the main method is declared as private?

The program compiles properly but at runtime it will give "Main method not public." Message

Page 56: Java Lab Manual -Yna

Sunil kumar P.N.V 56

K What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

K We can write “static public void” instead of “public static void” but not “public void static”.

K If I do not provide the String array as the argument to the method?

Program compiles but throws a runtime error "NoSuchMethodError".

K If no arguments on the command line, String array of Main method will be empty of null?

It is empty. But not null.

\ Variables can have the same name as a method or a class

12) Can an application have multiple classes having main method?

A) Yes it is possible. While starting the application we mention the class name to be run. The JVM

will look for the Main method only in the class whose name you have mentioned. Hence there is not

conflict amongst the multiple classes having main method.

13) Can I have multiple main methods in the same class?

A) No the program fails to compile. The compiler says that the main method is already defined in the

class.

14) Constructor

The automatic initialization is performed through the constructor, constructor has same name has

class name. Constructor has no return type not even void. We can pass the parameters to the

constructor. this () is used to invoke a constructor of the same class. Super () is used to invoke a super

class constructor. Constructor is called immediately after the object is created before the new operator

completes.

K Constructor can use the access specifiers public, protected or private or have no access modifier

(package access)

\ Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp

K Constructor can be overloaded, we cannot override.

K You cannot use this() and Super() in the same constructor.

Class A (

A() {

System.out.println(“hello”);

}}

Class B extends A {

Page 57: Java Lab Manual -Yna

Sunil kumar P.N.V 57

B(){

System.out.println(“friend”);

}}

Class print {

Public static void main (String args []){

B b = new B();

}

o/p:- Hello

friend

15) Diff Constructor & Method

Constructor Method

Use to instance of a class Grouping java statement

No return type Void (or) valid return type

Same name as class name As a name except the class method name, begin

with lower case.

“This” refer to another constructor in the same

class

Refers to instance of class

“Super” to invoke the super class constructor Execute an overridden method in the super class

“Inheritance” cannot be inherited Can be inherited

We can overload but we cannot overridden Can be inherited

Will automatically invoke when an object is

created

Method has called explicitly

16) Garbage collection

G.C is also called automatic memory management as JVM automatically removes the unused

variables/objects (value is null) from the memory. User program cann't directly free the object from

memory, instead it is the job of the garbage collector to automatically free the objects that are no

longer referenced by a program. Every class inherits finalize () method from java.lang.Object, the

finalize () method is called by garbage collector when it determines no more references to the object

exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on

calling System.gc () and Runtime.gc (), JVM tries to recycle the unused objects, but there is no

guarantee when all the objects will garbage collected.

Page 58: Java Lab Manual -Yna

Sunil kumar P.N.V 58

17) Final, Finally, Finalize

Final: - When we declare a sub class a final the compiler will give error as “cannot subclass final

class” Final to prevent inheritance and method overriding. Once to declare a variable as final it

cannot occupy memory per instance basis. \ Final class cannot have static methods

à Final class cannot have abstract methods

\ Final class can have only a final method.

Finally: - Finally create a block of code that will be executed after try catch block has completed.

Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally

block will execute even if no catch statement match the exception. Any time a method is about to

return to the caller from inside try/catch block, via an uncaught exception or an explicit return

statement, the finally clause is also execute.

Using System.exit (); in try block will not allow finally code to execute

Finalize: - some times an object need to perform some actions when it is going to destroy, if an object

holding some non-java resource such as file handle (or) window character font, these resources are

freed before the object is going to destroy any cleanup processing before the object is garbage

collected.

18) Superclass & Subclass

A super class is a class that is inherited whereas subclass is a class that does the inheriting

19) Diff forms of Polymorphism? Method overloading, Method overriding?

A) Method overloading, Method overriding through inheritance

Method Overloading & Method Overriding?

Method Overloading (Compile time polymorphism)

Define two or more methods within the same class (or) subclass that share the same name and

their parameter declarations are different then the methods are said to be overloaded. Overloaded

methods must differ in number of parameters & return type.

\ Overloaded methods are not required to have the same return type or the list of thrown

exceptions.

\ Overloading is particularly used while implementing several methods that implement similar

behavior but for different data types.

Page 59: Java Lab Manual -Yna

Method Overriding (Runtime polymorphism)

When a method in a subclass has the same name, return type and parameters as the method in

the super class then the method in the subclass is override the method in the super class.

\ The access modifier for the overriding method may not be more restrictive than the access

modifier of the superclass method

\ If the super class method is public, the overriding method must be public

\ If the superclass method is protected, the overriding method may be protected or public

\ If the superclass method is package, the overriding method may be packagage, protected, or

public

\ If the superclass methods is private, it is not inherited and overriding is not an issue

\ Methods declared as final cannot be overridden.

\ The throws clause of the overriding method may only include exceptions that can be thrown by

the superclass method, including it's subclasses

K Only member method can be overriden, not member variable

class Parent{

int i = 0;

void amethod(){

System.out.println("in Parent");

}

}

class Child extends Parent{

int i = 10;

void amethod(){

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

}

}

class Test{

public static void main(String[] args){

Parent p = new Child ();

Child c = new Child ();

A. Yogananda 59

Page 60: Java Lab Manual -Yna

}

}

O/p: - i=0 in Child

i=10 in Child

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

p.amethod();

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

c.amethod();

20) Static

Static variables and methods are instantiated only once per class. In other words they are class

variables, not instance variables. If you change the value of a static variable in a particular object, the

value of that variable changes for all instances of that class. Static methods can be referenced with the

name of the class.

\ When a member is declared a static it can be accessed before any object of its class are created.

\ Instance variables declared as static are essentially global variables.

\ If you do not specify an initial value to an instance & Static variable a default value will be

assigned automatically.

\ Methods declared as static have some restrictions they can access only static data, they can only

call other static data, they cannot refer this or super.

\ Static methods can‟t be overriden to non-static methods.

\ Static methods are called by the static methods only, an ordinary method can call the static

methods, but static methods cannot call ordinary methods.

\ Static methods are implicitly "final", because overriding is only done based on the type of the

objects

\ They cannot refer “this” or “super” in any way.

21) Class variable & Instance variable & Instance methods & class methods

Instance variable \ variables defined inside a class are called instance variables with multiple instance

of class; each instance has a variable stored in separate memory location.

Class variables \ you want a variable to be common to all classes then we crate class variables. To

create a class variable put the “static” keyword before the variable name.

A. Yogananda 60

Page 61: Java Lab Manual -Yna

Class methods \ we create class methods to allow us to call a method without creating a instance of

the class. To declare a class method uses the “static” key word.

Instance methods \ we define a method in a class, in order to use that methods we need to first create

objects of the class.

22) Static block

Static block which exactly executed exactly once when the class is first loaded into JVM. Before

going to the main method the static block will execute.

23) Static methods cannot access instance variables why?

Static methods can be invoked before the object is created, Instance variables are created only

when the new object is created. Since there is no possibility to the static method to access the instance

variables. Instance variables are called called as non-static variables.

24) String & StringBuffer

String is a fixed length of sequence of characters, String is immutable.

StringBuffer represent growable and writeable character sequence, StringBuffer is mutable

which means that its value can be changed. It allocates room for 16 addition character space when no

specific length is specified. Java.lang.StringBuffer is also a final class hence it cannot be sub classed.

StringBuffer cannot be overridden the equals () method.

25) Conversions

String to Int Conversion:-

int I = integer.valueOf(“24”).intValue();

int x = integer.parseInt(“433”);

float f = float.valueOf(23.9).floatValue();

Int to String Conversion:-

String arg = String.valueOf (10);

26) Super ()

super () always calling the constructor of immediate super class, super () must always be the

first statements executed inside a subclass constructor.

A. Yogananda 61

Page 62: Java Lab Manual -Yna

27) How will u implement 1) polymorphism 2) multiple inheritance 3) multilevel inheritance in

java?

A) Polymorphism – overloading and overriding

Multiple inheritances – interfaces.

Multilevel inheritance – extending class.

28) What are different types of inner classes?

Nested top-level classes- If you declare a class within a class and specify the static modifier, the

compiler treats the class just like any other top-level class. Any class outside the declaring class

accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.inner.

Top-level inner classes implicitly have access only to static variables. There can also be inner

interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables

and access to the member class is restricted, just like methods and variables. This means public

member class acts similarly to a nested top-level class. The primary difference between member

classes and nested top-level classes is that member classes have access to the specific instance of the

enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only

within the block of their declaration. In order for the class to be useful beyond the declaration block,

it would need to implement a more publicly available interface. Because local classes are not

members the modifiers public, protected, private and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As

anonymous classes have no name, you cannot provide a constructor.

\ Inner class inside method cannot have static members or blocks

29) Which circumstances you use Abstract Class & Interface?

--> If you need to change your design make it an interface.

--> Abstract class provide some default behaviour, A.C are excellent candidates inside of application

frame work. A.C allow single inheritance model which should be very faster.

30) Abstract Class

Any class that contain one are more abstract methods must also be declared as an abstract,

there can be no object of an abstract class, we cannot directly instantiate the abstract classes. A.C can

contain concrete methods.

\Any sub class of an Abstract class must either implement all the abstract methods in the super class

or be declared itself as Abstract.

A. Yogananda 62

Page 63: Java Lab Manual -Yna

K Compile time error occur if an attempt to create an instance of an Abstract class.

K You cannot declare “abstract constructor” and “abstract static method”.

K Abstract class can have static, final method.

K An abstract method also declared private, native, final, synchronized, or strictfp.

K An abstract method declared in a non-abstract class

K A class can be declared abstract even if it does not actually have any abstract methods. Declaring

such a class abstract indicates that the implementation is somehow incomplete and is meant to serve

as a super class for one or more subclasses that will complete the implementation.

Abstract class A {

Public abstract callme ();

void callmetoo () {

}

}

class B extends A(

void callme(){

}

}

class AbstractDemo{

public static void main(string args[]){

B b = new B();

b.callme();

b.callmetoo();

}

}

31) Interface

Interface is similar to class but they lack instance variable, their methods are declared with out

any body. Interfaces are designed to support dynamic method resolution at run time. All methods in

interface are implicitly abstract, even if the abstract modifier is omitted. Interface methods have no

implementation;

K Interface can be extended, Interface can be implemented.

K An interface body may contain constant declarations, abstract method declarations, inner classes

and inner interfaces.

K All methods of an interface are implicitly abstract, public, even if the public modifier is omitted.

A. Yogananda 63

Page 64: Java Lab Manual -Yna

K Interface methods cannot be declared protected, private, strictfp, native or synchronized.

K All Variables are implicitly final, public, static fields

K A compile time error occurs if an interface has a simple name the same as any of it's enclosing

classes or interfaces.

K top-level interfaces may only be declared public, inner interfaces may be declared private and

protected but only if they are defined in a class.

K A class can only extend one other class.

K A class may implements more than one interface.

K Interface can extend more than one interface.

Interface A

{

final static float pi = 3.14f;

}

class B implements A

{

public float compute(float x, float y)

{

return(x*y);

}

}

class test{

public static void main(String args[])

{

A a = new B();

a.compute();

}

}

32) Diff Interface & Abstract Class?

\ Abstract classes may have some executable methods and methods left unimplemented. Interface

contains no implementation code.

\ An abstract class can have nonabstract methods. All methods of an Interface are abstract.

A. Yogananda 64

Page 65: Java Lab Manual -Yna

\ An abstract class can have instance variables. An Interface cannot.

\ An abstract class can define constructor. An Interface cannot.

\ An abstract class can have any visibility: public, private, protected. An Interface visibility must be

public (or) none.

33) What are some alternatives to inheritance?

Delegation is an alternative to inheritance. Delegation means that you include an instance of

another class as an instance variable, and forward messages to the instance. It is often safer than

inheritance because it forces you to think about each message you forward, because the instance is of

a known class, rather than a new class, and because it doesn‟t force you to accept all the methods of

the super class: you can provide only the methods that really make sense. On the other hand, it

makes you write more code, and it is harder to re-use (because it is not a subclass).

34) When we use Abstract class?

Let us take the behaviour of animals, animals are capable of doing different things like flying,

digging,

Walking. But these are some common operations performed by all animals, but in a different way as

well. When an operation is performed in a different way it is a good candidate for an abstract

method.

Public Abstarctclass Animal{

Public void eat(food food) {

}

public void sleep(int hours)

{

}

public abstract void makeNoise()

}

public Dog extends Animal

{

public void makeNoise()

{

System.out.println(“Bark! Bark”);

}

}

A. Yogananda 65

Page 66: Java Lab Manual -Yna

public Cow extends Animal

{

public void makeNoise()

{

System.out.println(“moo! moo”);

}

}

35) Serializable & Externalizable

Serializable --> is an interface that extends serializable interface and sends data into streams in

compressed format. It has 2 methods writeExternal (objectOutput out), readExternal (objectInput

in).

Externalizable \ is an Interface that extends Serializable Interface. And sends data into

Streams in Compressed Format. It has two methods, writeExternal (ObjectOuput out) and

readExternal (ObjectInput in).

36) Internalisation & Localization

Internalisation -- Making a programme to flexible to run in any locale called internalisation.

Localization -- Making a programme to flexible to run in a specific locale called Localization.

37) Serialization

Serialization is the process of writing the state of the object to a byte stream; this is useful

when ever you want to save the state of your programme to a persistence storage area.

38) Synchronization

Synchronization is a process of controlling the access of shared resources by the multiple

threads in such a manner that only one thread can access one resource at a time. (Or) When 2 are

more threads need to access the shared resources they need to some way ensure that the resources

will be used by only one thread at a time. This process which is achieved is called synchronization.

(i) Ex: - Synchronizing a function:

public synchronized void Method1 () {

// Appropriate method-related code.

}

A. Yogananda 66

Page 67: Java Lab Manual -Yna

Sunil kumar P.N.V 67

(ii) Ex: - Synchronizing a block of code inside a function:

public myFunction () {

synchronized (this) {

// Synchronized code here.

}

}

(iii) Ex: - public Synchronized void main (String args [])

But this is not the right approach because it means servlet can handle one request at a time.

39) Different level of locking using Synchronization?

A) Class level, Object level, Method level, Block level

40) Monitor

A monitor is a mutex, once a thread enters a monitor, all other threads must wait until that

thread exist the monitor.

41) Diff = = and .equals ()?

== \ Compare object references whether they refer to the same instance are not.

equals () \ method compare the characters in the string object.

42) Marker Interfaces (or) Tagged Interfaces :-

An Interface with no methods. Is called marker Interfaces, eg., Serializable, SingleThread

Model, Cloneable.

43) URL Encoding & URL Decoding

URL Encoding is the method of replacing all the spaces and other extra characters into their

corresponding Hex Characters and URL Decoding is the reverse process converting all Hex

Characters back their normal form.

44) URL & URLConection

URL is to identify a resource in a network, is only used to read something from the network.

URL url = new URL (protocol name, host name, port, url specifier)

URLConnection can establish communication between two programs in the network.

URL hp = new URL (“www.yahoo.com”);

URLConnection con = hp.openConnection ();

45) Runtime class

Page 68: Java Lab Manual -Yna

Sunil kumar P.N.V 68

Runtime class encapsulate the run-time environment. You cannot instantiate a Runtime object.

You can get a reference to the current Runtime object by calling the static method

Runtime.getRuntime ()

Runtime r = Runtime.getRuntime ()

Long mem1;

mem1 = r.freeMemory ();

mem1 = r.totalMemory ();

46) Execute other programs

You can use java to execute other heavy weight process on your multi tasking operating

system, several form of exec () method allows you to name the programme you want to run.

Runtime r = Runtime.getRuntime ();

Process p = null;

try{

p = r.exce (“notepad”);

p.waiFor ()

}

47) System class

System class hold a collection of static methods and variables. The standard input, output,

error output of the java runtime are stored in the in, out, err variables.

48) Class

Class encapsulate the run-time state of an object or interface. Methods in this class are

static Class forName(String name)

throws ClassNotFoundException

getClass()

getClassLoader() getConstructor()

getField() getDeclaredFields()

getMethods() getDeclearedMethods()

getInterface() getSuperClass()

49) Native Methods

Native methods are used to call subroutine that is written in a language other than java, this

subroutine exist as executable code for the CPU.

Page 69: Java Lab Manual -Yna

Sunil kumar P.N.V 69

50) Cloneable Interface

Any class that implements the cloneable interface can be cloned, this interface defines no

methods. It is used to indicate that a class allow a bit wise copy of an object to be made.

51) Clone

Generate a duplicate copy of the object on which it is called. Cloning is a dangerous action.

52) Comparable Interface

Classes that implements comparable contain objects that can be compared in some meaningful

manner. This interface having one method compare () the invoking object with the object. For sorting

comparable interface will be used.

Ex: - int compareTo (Object obj)

53) java.lang.Reflect (package)

Reflection is the ability of software to analyse it self, to obtain information about the field,

constructor, methods & modifier of class. You need this information to build software tools that

enables you to work with java beans components.

54) InstanceOf

Instanceof means by which your program can obtain run time type information about an

object.

Ex: - A a = new A ();

a instanceof A;

55) java lack pointers how do I implements classic pointer structures like linked list?

A) using object reference.

56) java.Exe

Micro soft provided sdk for java, which includes “jexegentool”. This converts class file into an

“.Exec” form. Only disadvantage is user needs a M.S java V.M installed.

57) bin & Lib in jdk?

bin contains all tools such as javac, appletviewer and awt tool.

lib contains API and all packages.

Collections Frame Work

58)

Collection classes Collection

Interfaces

Legacy classes Legacy interface

Abstract collection Collection Dictionary Enumerator

Abstract List List Hash Table

Page 70: Java Lab Manual -Yna

Sunil kumar P.N.V 70

Abstract Set Set Stack

Array List Sorted Set Vector

Linked List Map Properties

Hash set Iterator

Tree Set

Hash Map

Tree Map

Collection Classes

Array List K Array List extends AbstractList and implements the List interface. ArrayList is a

variable length of array of object references, ArrayList support dynamic array that grow as

needed. A.L allows rapid random access to element but slow for insertion and deletion from the

middle of the list.

K ArrayList is a replacement for Vector.

1. Linked List K Extends AbstactSequentialList and implements List interface. L.L provides

optimal sequence access, in expensive insertion and deletion from the middle of the list, relatively

slow for random access.

Methods>> void addFirst (Object obj), addLast (Object obj), Object getFirst (), Object getLast ().

Hash Set K HashSet extends AbstractSet implements Set interface, it creates a collection that uses

HashTable for storage, H.S does not guarantee the order of its elements, if u need storage go for

TreeSet

Methods>> add (), remove (), size ().

Tree Set K Extends Abstract Set implements Set interface. Objects are stored in sorted, ascending

order. Access and retrial times are quite fast.

Hash Map K Extends Abstract Map and implements Map interface. H.P does not guarantee the

order of elements, so the order in which the elements are added to a H.P is not necessary the order in

which they are ready by the iterate.

K HashMap is similar to Hashtable.

Tree Map K implements Map interface, a TreeMap provides an efficient means of storing

key/value pairs in sorted order and allows rapid retrieval.

Collection Interfaces

Collection K Collection is a group of objects, collection does not allow duplicate elements.

Methods>> boolean add (Object obj), boolean addAll (Collection c), Iterator iterator (),

Page 71: Java Lab Manual -Yna

Sunil kumar P.N.V 71

boolean remove(Object obj), boolean removeAll(Collection c).

List K List will extend collection, List stores a sequence of elements that can contain duplicates,

elements can be accessed their position in the list using a zero based index.

Methods>> void add(int index, Object obj), boolean addAll(int index, Collection c), Object get(int index),

int indexOf(Object obj), int lastIndexOf(Object obj), ListIterator iterator(), Object remove(int index).

Set K Set will extend collection, Set cannot contain duplicate elements.

Sorted Set K Extends Set to handle Sorted Sets.

Methods>> Object last (), Object first ().

Map K Map maps unique key to value in a map for every key there is a corresponding value and

you will lookup the values using keys. Map cannot contain duplicate “key” and “value”. In map

both the “key” & “value” are objects.

Methods>> Object get (Object k), Object put (Object k, Object v).

Iterator K Before accessing a collection through an iterator you must obtain one if the collection

classes provide an iterator () method that returns an iterator to the start of the collection. By using

iterator object you can access each element in the collection, one element at a time.

Ex: - ArayList arr = new ArrayList ();

Arr.add (“c”);

Iterator itr = arr.iterator ();

While (itr.hashNext ())

{

Object element = itr.next ();

}

List Iterator K List Iterator gives the ability to access the collection, either forward/backward

direction

Legacy Classes

Dictionary K is an abstract class that represent key/value storage repository and operates much

like “Map” once the value is stored you can retrieve it by using key.

Hash Table K HashTable stores key/value pairs in hash table, HashTable is Synchronized when

using hash table you have to specify an object that is used as a key, and the value that you want to

linked to that key. The key is then hashed, and the resulting hash code is used as the index at which

the value is stored with the table. Use H.T to store large amount of data, it will search as fast as

vector.

Page 72: Java Lab Manual -Yna

Methods>> boolean containsKey(Object key), boolean containsValue(Object value), Object get(Object key),

Object put(Object key, Object value)

Stack K is a sub class of vector, stack includes all the methods defined by vector and adds several

of its own.

Vector K vector holds any type of objects, it is not fixed length and vector is synchronized. We can

store primitive data types as well as objects. Default length of vector is up to 10.

Methods>> final void addElement(Object element), final int size(), final int capacity(), final boolean

removeElementAt(int index), final void removeAllElements().

Properties K is a subclass of HashTable, it is used to maintain the list of values in which the

“key/value” is String.

Legacy Interfaces

Enumeration K Define methods by which you can enumerate the elements in a collection of

objects. Enumeration is synchronized it having 2 methods hasMoreElements(), nextElement().

59) Array

Array of fixed length of same data type, we can store primitive data types as well as class

objects.

K Arrays are initialized to the default value of their type when they are created, not declared, even if

they are local variables

60) Diff Iterator & Enumeration

Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is

collection interface which extends from „List‟ interface. Enumeration is a legacy interface,

Enumeration having 2 methods „Boolean hasMoreElements()‟ & „Object NextElement()‟. Iterator

having 3 methods „boolean hasNext()‟, „object next()‟, „void remove()‟.

61) List Iterator

It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and

modification of the elements. Methods are „hasNext()‟, „ hasPrevious()‟.

62) Diff HashTable & HashMap

\ Both provide key/value to access the data. The H.T is one of the original collection class in java.

H.M is part of new collection frame work.

\ H.T is synchronized and H.M is not.

\ H.M permits null values in it while H.T does not.

\ Iterator in the H.M is fail safe while the enumerator for the H.T is not.

63)Exception Handling

Object

A. Yogananda 72

Page 73: Java Lab Manual -Yna

Sunil kumar P.N.V 73

Throwable

Error Exception

AWT Error Virtual Machine Error

Compile time.Ex Runtime Exception

(checked) (Unchecked)

OutOfMemory.E StackOverFlow.E EOF.E FilenotFound.E

Arithmetic.E NullPointer.E

Indexoutof

Bound.E StirngIndexoutOfBound

64) Diff Exception & Error

ArrayIndexoutOfBound.E

Exception and Error both are subclasses of the Throwable class.

Exception\Exception is generated by java runtime system (or) by manually. An exception is a

abnormal condition that transfer program execution from a thrower to catcher.

Error KWill stop the program execution, Error is a abnormal system condition we cannot

handled these.

65) try, catch, throw, throws

Try -> This is used to fix up the error, to prevent the program from automatically terminating, try-

catch is used to catching an exception that are thrown by the java runtime system.

Throw -> is used to throw an exception explicitly.

Throws -> A Throws clause list the type of exceptions that a methods might through.

66) Checked & UnChecked Exception :-

Page 74: Java Lab Manual -Yna

Sunil kumar P.N.V 74

Checked exception is some subclass of Exception. Making an exception checked forces client

programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown

by java.io.FileInputStream's read() method·

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its

subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force

client programmers either to catch the exception or declare it in a throws clause. In fact, client

programmers may not even know that the exception could be thrown. eg,

StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must

be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Checked Exceptions Un checked exception

ClassNotFoundException ArithmeticException

NoSuchMethodException ArrayIndexOutOfBoundException

NoSuchFieldException ClasscastException

InterruptedException IllegalArgumentException

IllegalAccessException IllegalMonitorSateException

CloneNotSupportedException IllegalThreadStateException

IndexOutOfBoundException

NullPointerException

NumberFormatException

StringIndexOutOfBounds

OutOfMemoryError --> Signals that JVM has run out of memory and that the garbage collector

is unable to claim any more free memory.

StackOverFlow --> Signals that a stack O.F in the interpreter.

ArrayIndexOutOfbound --> For accessing an array element by providing an index values <0 or

> or equal to the array size.

StringIndexOutOfbound --> For accessing character of a string or string buffer with index

values <0 or > or equal to the array size.

Arithmetic Exception --> such as divide by zero.

ArrayStore Exception --> Assignment to an array element of incompatible types.

ClasscastException --> Invalid casting.

IllegalArgument Exception --> Illegal argument is used to invoke a method.

Page 75: Java Lab Manual -Yna

Sunil kumar P.N.V 75

Nullpointer Exception --> If attempt to made to use a null object.

NumberFormat Exception --> Invalid conversition of string to numeric format.

ClassNotfound Exception --> class not found.

Instantion Exception --> Attempt to create an object of an Abstract class or Interface.

NosuchField Exception --> A request field does not exist.

NosuchMethod Exception --> A request method does not exist.

67) Can I catch an exception and give my own error message?

A) Yes, you can catch servlet errors and give custom error pages for them, but if there are exceptional

conditions you can anticipate, it would be better for your application to address these directly and try

to avoid them in the first place. If a servlet relies upon system or network resources that may not be

available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error

page.

RequestDispatcher dispatcher = null;

request.getRequestDispatcher (/err/SQL.jsp);

try {

// SQL operation

}

catch (SQLException se) {

dispatcher.forward (request, response);

}

Web.xml:-

<error-page>

<error-code>

HTTP error code

<error-code>

<exception-type>

java.lang.RuntimeException

</exception-type>

<location>

/err/RuntimeException.jsp

</location>

</error-page>

Page 76: Java Lab Manual -Yna

Sunil kumar P.N.V 76

68) Methods in Exceptions?

A) getMessage (), toString(), printStackTrace(), getLocalizedMessage(),

69) Primitive multi tasking

If the thread of different priorities shifting the control depends on the priority .i.e; a thread

with higher priority is executed first than the thread with lower priority. This process of shifting

control is known as primitive multi tasking.

70) Thread Class

Methods: -

getName() run()

getPriority() Sleep()

isAlive() Start()

join()

71) Object class

All other classes are sub classes of object class; Object class is a super class of all other class.

Methods: -

void notify() void notifyAll()

Object Clone() Sting toString()

Boolean equals(Object object) Void wait()

void finalize() void wait(long milliseconds,

int nanoseconds)

72) throwable class

Methods: -

String getMessage() Void printStackTrace()

String toString() Throwable fillInStackTrace()

73) java.sql Package

Interfaces Classes Exceptions

Statement DriverManager SQL Exception

PreparedStateme

nt

Time ClassNotFoundException

CallableStatemen

t

TimeStamp Instantiation Exception

ResultSet

Page 77: Java Lab Manual -Yna

Sunil kumar P.N.V 77

ResultSetMetaDa

ta

Connection

74) java.lang Package

Interfaces Classes Exceptions

Cloneable Double, Float, Long, Integer,

Short, Byte, Boolean,

Character,

ArithmeticException,

ArrayIndexOutOfBoundOf.E,

ClassCast.E, ClassNotFound.E

Runnable Class, ClassLoader IlleAcess.E, IllegalArgument.E

Comparable Process, RunTime, Void IllegalSate.E, NullPointer.E

String, StringBuffer NoSuchField.E, NoSuchMethod.E

Thread, ThreadGroup NumberFormat.E

75) java.IO Package

Interfaces Classes Exceptions

DataInputstream BufferInputstream, BufferOutputStream

DataOutputstrea

m

BufferReader, BufferWriter

ObjectInputStrea

m

ByteArrayInputStream,

ByteArrayOutputstream

ObjectOutputstre

am

CharacterarrayReader,

CharacterArayWriter

Serializable DataInputStream, DataOutputStream

Externializable Filereader, FileWriter

ObjectInputStream,

ObjectOutputStream

Threading Questions

1) What threads will start when you start the java program?

A) Finalizer, Main, Reference Handler, Signal dispatcher.

2) Thread

Thread is a smallest unit of dispatchable code.

3) Sleep(), wait(), notify(), notifyAll(), stop(), suspend(), resume()

sleep K sleep for a thread until some specific amount of time.

Page 78: Java Lab Manual -Yna

Sunil kumar P.N.V 78

wait \ wait for a thread until some specific condition occurs (Or) Tells the calling thread to give

up the monitor and go to sleep until some other thread enters the same monitor and calls notify().

notify( ) K wakes up the first thread that called wait() on the same object.

notifyAll ( )K wakes up all the threads that called wait() on the same object, the highest priority

thread will run first.

stop( ) K The thread move to dead state.

suspend ( ) & resume( ) K To pass and restart the execution of a thread. In case of suspend, thread

will be 1suspended by calling the lock on the object. Resume will restart from where it is suspended.

join( ) K wait for a thread to terminate.

4) yield( )

Yield method temporarily stop the callers thread and put at the end of queue to wait for

another turn to be executed. It is used to make other threads of the same priority have the chance to

run.

-> Thread.sleep(milliseconds);

-> Thread.sleep(milliseconds, nanoseconds);

5) Daemon Thread

Daemon thread is one which serves another thread, it has no other role normally a daemon

thread carry some background program. When daemon thread remains the program exist.

6) Thread Priority

MIN_PRIORITY = 1

NORM_PRIORITY = 5

MAX_PRIORITY = 10

7) Can I restart a stopped thread?

A) Once a thread is stopped, it cannot be restarted. Keep in mind though that the use of the stop ()

method of Thread is deprecated and should be avoided.

8) Thread Priorities

Class A implements Runnable{

Thread t;

Public clicker(int p){

T = new Thread(this)

t.setPriority(p);

}

public void run(){

}

Page 79: Java Lab Manual -Yna

public void stop(){

}

public void start(){

t.start();

}

try{

thread.sleep(1000);

}

lo.stop();

hi.stop();

try{

hi.t.join();

lo.t.join();

}

class HiLo{

public static void main(Stirng args[]){

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

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

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

Lo.start();

Hi.start();

9) What is the use of start() function in starting a thread? why we do not use the run() method

directly to run the thread?

K Start method tell the JVM that it needs to create a system specific thread. After creating the system

resources it passes the runnable object to it to execute the run() method.

\ calling run() method directly has the thread execute in the same as the calling object, not a separate

thread of execution.

10) what are the different levels of locking using „Synchronize‟ key word?

A) class level, method level, object level, block level

A. Yogananda 79

Page 80: Java Lab Manual -Yna

REFERENCES : 1. Java; the complete reference, 7th editon, Herbert schildt, TMH. 2. Understanding OOP with Java, updated edition, T. Budd, pearson eduction. 3. An Introduction to programming and OO design using Java, J.Nino and F.A. Hosch, John wiley & sons. 4. An Introduction to OOP, second edition, T. Budd, pearson education. 5. Introduction to Java programming 6th edition, Y. Daniel Liang, pearson education. 6. An introduction to Java programming and object oriented application development, R.A. Johnson- Thomson. 7. Core Java 2, Vol 1, Fundamentals, Cay.S.Horstmann and Gary Cornell, seventh Edition, Pearson Education. 8 .Core Java 2, Vol 2, Advanced Features, Cay.S.Horstmann and Gary Cornell, Seventh Edition, Pearson Education

A. Yogananda 80