Вы находитесь на странице: 1из 80

Object Oriented Programming Lab Manual

A. Yogananda

1

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

1

Enter value for b

1

Enter value for c

1

roots are imaginary and complex

A. Yogananda

Enter value for a

1

Enter value for b

3

Enter value for c

2

roots are real distinct

r1 =-2

r2=-3.5

2

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

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

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 for(int i=0;i<m;i++)

{

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

{

A. Yogananda

Matrix is ");

5

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]); }
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();
}
}
else
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

Resultant Matrix is

10

15

10

10 10

15 15

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

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

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

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

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

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

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

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

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

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

 

word_ct++;

break;

 

case '\n':

 

line_ct++;

word_ct++;

break;

 

}

}

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:

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

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

class Stack1 { public static void main(String[] args)throws IOException { int i,n,t,ch; BufferedReader br=new
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;
}
case 3:
else
System.out.println("\nelement popped is:"+t);
break;
System.out.println("\nELEMENTS IN THE STACK ARE:");
a.display();
break;
case 4:
default:
return;
System.out.println("\nwrong option");
}
}
}
}
OUTPUT:
enter the size of the matrix:
3
1.push
2.pop
3.display
A. Yogananda
18
4.exit enter ur choice: 1 enter a element: 12 1.push 2.pop 3.display 4.exit enter ur
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
3.display 4.exit enter ur choice: 2 element popped is:14 1.push 2.pop 3.display 4.exit enter ur
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

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

case '*':

break;

//

(precedence 1) // 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

{

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

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

expression: a+b*c-d

abc*+d-

Postfix is abc*+d-

enter

infix

A. Yogananda

23

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

A. Yogananda

interAns = num1 + num2; break;

interAns = num1 - num2; break;

interAns = num1 * num2; break;

24

}

}

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

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

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

Week6a.java D:\nanda>appletviewer Week6a.java Save as Week6a.java import java.applet.*; import

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

(or)

public class Week6a extends Applet

{

public void paint(Graphics g)

{

setBackground(Color.blue); g.setColor(Color.orange); g.drawString("Welcome to Applet Programming",60,60);

}

}

A. Yogananda

27

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

<applet code="Week6a" width=400 height=200></applet> </HTML> A. Yogananda 28

A. Yogananda

28

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

Output:

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

Output: D:\nanda>javac Week6b.java D:\nanda>appletviewer Week6b.java A. Yogananda 30

A. Yogananda

Output: D:\nanda>javac Week6b.java D:\nanda>appletviewer Week6b.java A. Yogananda 30

30

Week 7: Write a Java program that works as a simple calculator. Use to buttons
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

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

{

 

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

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

}

}

}

Output:

{

t1.setText("0");

temp=""; } else if(str.equals("Reset")) } } } Output: { t1.setText("0"); A. Yogananda 34
temp=""; } else if(str.equals("Reset")) } } } Output: { t1.setText("0"); A. Yogananda 34

A. Yogananda

34

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;

Y = 10;

msg = "Mouse clicked."; setForeground(Color.cyan); setBackground(Color.red);

repaint();

}

public void mouseEntered(MouseEvent me) {

msg = "Mouse entered."; setForeground(Color.blue); setBackground(Color.white); repaint();

}

public void mouseExited(MouseEvent me) {

setBackground(Color.white); msg = "Mouse exited."; repaint();

}

public void mousePressed(MouseEvent me) {

X = me.getX();

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) { Font a=new Font("Algerian",Font.PLAIN,25);

A. Yogananda

// save coordinates

// Handle mouse entered.

// Handle mouse exited.

// Handle button pressed.

// save coordinates

// Handle button released.

35

setFont(a);

X = me.getX();

Y = me.getY();

msg = "Mouse Released"; repaint();

}

public void mouseDragged(MouseEvent me) {

X = me.getX();

Y = me.getY();

msg = "Mouse Dragged"; showStatus("Dragging mouse at " + X + ", " + Y);

repaint();

}

public void mouseMoved(MouseEvent me) {

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

// Handle mouse dragged.

// Handle mouse moved.

{

g.drawString(msg, X, Y);

}

}

Output:

paint(Graphics g) // Handle mouse dragged. // Handle mouse moved. { g.drawString(msg, X, Y); } }
paint(Graphics g) // Handle mouse dragged. // Handle mouse moved. { g.drawString(msg, X, Y); } }

A. Yogananda

36

A. Yogananda 37

A. Yogananda

A. Yogananda 37

37

Week 9a:

Write a Java program that creates three threads. First thread displays Good Morningevery one second, the second thread displays Helloevery 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

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

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

q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q=q;
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)
{
Q q=new Q(); new
Producer(q); new
Consumer(q);
System.out.println("press control+c to stop");
}
}
Output:
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

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

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:

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

A. Yogananda

43

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)

A. Yogananda

{

pw.write(in);

pw.flush();

}

br2.close();

44

}

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 file name) in server after entering the required information the result will be displayed in
a file name) in server after entering the required information the result will be displayed in

A. Yogananda

a file name) in server after entering the required information the result will be displayed in
a file name) in server after entering the required information the result will be displayed in

45

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

}

A. Yogananda

{

 

g.setColor(Color.green);

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

}

46

public static void main(String[] args)

{

 

Radioex rd=new Radioex();

rd.setSize(400,400);

rd.setVisible(true);

}

}

Output:

  Radioex rd=new Radioex(); rd.setSize(400,400); rd.setVisible(true); } } Output: A. Yogananda 47

A. Yogananda

  Radioex rd=new Radioex(); rd.setSize(400,400); rd.setVisible(true); } } Output: A. Yogananda 47

47

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

d.setVisible(true); } } Output: D:\nanda>javac Draw1.java D:\nanda>java Draw1 A. Yogananda 48

A. Yogananda

48

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

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

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

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:

120,Gertrude S te in,Elmsford,(914)5553476 131,Dalji t Sinno t,B ohemia,(516)5559811 Output: Sunil kumar P.N.V Or 52

Sunil kumar P.N.V

Or

52

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

{

public void init()

{

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

}

}

Output:

JScrollPane j=new JScrollPane( t, i,m); cp.add(j,BorderLayou t. CENTER); } } Output: Sunil kumar P.N.V 53

Sunil kumar P.N.V

53

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.

 

Privat

Publi

Protecte

No

e

c

d

modifier

Same class

No

Yes

Yes

Yes

Sunil kumar P.N.V

54

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

Sunil kumar P.N.V

55

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

Sunil kumar P.N.V

56

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.

Sunil kumar P.N.V

57

17) Final, Finally, Finalize Final: - When we declare a sub class a final the compiler will give error as cannot subclass final classFinal 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.

Sunil kumar P.N.V

58

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

}

}

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 methods cant 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 thisor super” in any way.

static data, they cannot refer this or super.

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 “statickeyword before the variable name.

A. Yogananda

60

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

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

int x = integer.parseInt(“433”); float f = float.valueOf(23.9).floatValue();

int I

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

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

A) Polymorphism Multiple inheritances

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.

overloading and overriding interfaces.

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

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

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

\ 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 doesnt 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

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

(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

Sunil kumar P.N.V

67

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.

Sunil kumar P.N.V

68

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 “.Execform. 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

Legacy classes

Legacy interface

Interfaces

Abstract collection

Collection