Thursday, May 7, 2009

2-2 java lab programs

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

SOURCE PROGRAM:

import java.util.*;
public class quadratic
{
public static void main(String j[])
{
int a,b,c;
double r1,r2;
double disc;
Scanner sr=new Scanner(System.in);
System.out.println("enter the values of a,b,c");
a=sr.nextInt();
b=sr.nextInt();
c=sr.nextInt();
disc=b*b-4*a*c;
if(disc>=0)
{ r1=(-b+Math.sqrt(disc))/2*a;
r2=(-b-Math.sqrt(disc))/2*a;
System.out.println("the roots are"+r1+" "+r2);
}
else
System.out.println("no real solutions");
}
}
Output:
enter the values of a,b,c
1 20 1
the roots are-0.05012562893380057-19.9498743710662

2)The Fibonacci sequence is defined by the following rule: The first 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.

SOURCE PROGRAM:

import java.util.*;
class A
{
void fib(int f,int s,int n)
{
if(n<=0)
return;
else
{
System.out.print("\t"+f);
fib(s,f+s,n-1);
}

}
}

class B
{
void febanacci(int n)
{
int a=-1,b=1;
int c=a+b;
while(c<=n-2)
{
c=a+b;
System.out.print("\t"+c);
a=b;
b=c;
}

}
}

class fibonacci
{

public static void main(String args[])
{
int n;
Scanner sr=new Scanner(System.in);
System.out.println("enter the value of n");
n=sr.nextInt();
A ob1=new A();
System.out.println("FIBANACCI SERIES IS WITH RECURSION");
// with recursion
ob1.fib(0,1,n);
//without recursion
System.out.println();
System.out.println("FIBANACCI SERIES IS WITHOUT RECURSION");
B ob2=new B();
ob2.febanacci(n);

}
}

Output:
enter the value of n
3
FIBANACCI SERIES IS WITH RECURSION
0 1 1
FIBANACCI SERIES IS WITHOUT RECURSION
0 1 1 2


3)Write a java program that prompts the user for an integer and then prints out all prime no’s up to that integer:

SOURCE PROGRAM:

import java.util.*;
public class prime
{
public static void main(String j[])
{ int isprime;
int n;
Scanner sr=new Scanner(System.in);
System.out.println("enter the value of n");
n=sr.nextInt();
for(int i=1;i<=n;i++)
{ isprime=0;
for(int f=2;f<i;f++)
{ if(i%f==0)
isprime=1;
}
if(isprime==0)
System.out.println(i+"is prime");

}
}
}

Output:
enter the value of n
5
1is prime
2is prime
3is prime
5is prime

4)Write a Java program to multiply two given matrices.

SOURCE PROGRAM:

class MatrixMultiply
{
public static void main(String[] args)
{
int array[][] = {{5,6,7},{4,8,9}};
int array1[][] = {{6,4},{5,7},{1,1}};
int array2[][] = new int[3][3];
int x= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i< x; i++)
{
for(int j = 0; j<= x; j++)
{
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int y= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i<y; i++)
{
for(int j = 0; j<y-1; j++)
{
System.out.print(" "+array1[i][j]);
}
System.out.println();
}
for(int i = 0; i< x; i++) {
for(int j = 0; j<y-1; j++) {
for(int k = 0; k< y; k++){
array2[i][j] += array[i][k]*array1[k][j];
} } }
System.out.println("Multiply of both matrix : ");
for(int i = 0; i<x; i++) {
for(int j = 0; j<y-1; j++)
{
System.out.print(" "+array2[i][j]);
}
System.out.println();
}
}
}

Output:
Matrix 1 :
5 6 7
4 8 9
Matrix 2 :
6 4
5 7
1 1
Multiply of both matrix :
67 69
73 81

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

SOURCE PROGRAM:

import java.util.*;
public class sum
{
public static void main(String l[])
{ int sum=0;
String ints;
Scanner sr=new Scanner(System.in);
System.out.println("enter the string of integers");
ints=sr.nextLine();
StringTokenizer s=new StringTokenizer(ints);
while(s.hasMoreTokens())
{ String s3;
s3=s.nextToken();
System.out.println(s3);
sum+=Integer.parseInt(s3);
}
System.out.println("sum is"+sum);
}
}

Output:
enter the string of integers
1234 23 323 23
1234
23
323
23
sum is1603

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

SOURCE PROGRAM:

import java.io.*;
class palindrome
{
public static void main(String arg[])throws IOException
{
DataInputStream in=new DataInputStream(System.in); //input syntax
int l,i,j,flag=1;
String s;
System.out.println("Enter the string:");
s=in.readLine();
l=s.length();
for(i=0,j=l-1;i<=j;i++,j--)
{
if(s.charAt(i)==s.charAt(j))
{
}
else
{
flag=0;
break;
}
}
if(flag==1)
System.out.print(s+" is palindrome");
else
System.out.print(s+" is not palindrome");
}
}

Output:
Enter the string:
MADAM
MADAM is palindrome

7)Write a Java program for sorting a given list of names in ascending order.

SOURCE PROGRAM:

import java.util.*;
import java.lang.*;
public class sort
{
public static void main(String args[])
{
Scanner sr=new Scanner(System.in);
String name[]=new String[5];
System.out.println("enter the string");
for(int i=0;i<5;i++)
{
name[i]=sr.nextLine();
} for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(name[i].compareTo(name[j])<0)
{
String t;
t=name[i];
name[i]=name[j];
name[j]=t;
}
}
}
System.out.println("names in ascending order");
for(int i=0;i<5;i++)
{
System.out.println(name[i]);
}
}
}

Output:
enter the string
nilima
kalyani
sangeetha
names in ascending order
kalyani
nilima
sangeetha


8)Write a java program to make frequency count of words in a given text

SOURCE PROGRAM:

import java.util.*;
import java.lang.String.*;
public class token {
public static void main(String jk[])
{ String text;
String word;
int count=0;
Scanner sr=new Scanner(System.in);
System.out.println("enter the text");
text=sr.nextLine();
System.out.println("enter the word");
word=sr.nextLine();
StringTokenizer st=new StringTokenizer(text,":? ");
while(st.hasMoreTokens())
{
if(word.equals(st.nextToken()))
count++;
}
System.out.println("frequency"+count);
}
}

Output:
enter the text
welcome to oops lab record where you find lab programs of lab sessions
enter the word
lab


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

SOURCE PROGRAM:

import java.io.*;
import java.util.*;
public class file
{
public static void main(String l[])
{
String fname;
Scanner sr=new Scanner(System.in);
System.out.println("enter a file name");
fname=sr.nextLine();
File f1=new File(fname);
if(f1.exists())
{
System.out.println("name:"+f1.getName());
System.out.println(" path:"+f1.getPath());
System.out.println("abspath:"+f1.getAbsolutePath());
System.out.println("parent:"+f1.getParent());
System.out.println("canread:"+f1.canRead());
System.out.println("canwrite:"+f1.canWrite());
System.out.println("is directory:"+f1.isDirectory());
System.out.println("isfile:"+f1.isFile());
System.out.println("lastmodified:"+f1.lastModified());
System.out.println("size:"+f1.length()+"bytes");
}
}

}

Output:
enter a file name
c:\quadratic.java
name: quadratic.java
path:c:\ quadratic.java
abspath:c:\ quadratic.java
parent:c:\
canread:true
canwrite:true
is directory:false
isfile:true
lastmodified:1237828257078
size:456bytes

10)Write a Java program that reads a file and displays the file on the screen, with a line number before each line.

SOURCE PROGRAM:

import java.util.*;
import java.io.*;
public class lines
{
public static void main(String k[]) throws IOException
{
String j;
Scanner sr=new Scanner(System.in);
System.out.println("enter the file name");
j=sr.nextLine();
FileReader fr=new FileReader(j);
BufferedReader br=new BufferedReader(fr);
String line;
int count=1;
while((line=br.readLine())!=null)
{ System.out.println(count+":"+line);
count++;
}
}
}

Output:
enter the file name
c:\hi.txt
1:hello
2:welcome
3:to oops lab
4:thank you
5:bye


11)Write a Java program that displays the number of characters, lines and words in a text file.

SOURCE PROGRAM:

import java.util.*;
import java.io.*;
public class filecontentcount
{
public static void main(String l[]) throws IOException{
String fname;
Scanner sr=new Scanner(System.in);
System.out.println("enter the file name");
fname=sr.nextLine();
int chars=0,c=0,lines=0,words=0;
FileReader fr=new FileReader(fname);
String whitespace="\n\t\r";
boolean lastwhitespace=true;
int index;
while((c=fr.read())!=-1)
{
chars++;
if(c=='\n')
lines++;
index=whitespace.indexOf(c);
if(index==-1)
{
if(lastwhitespace==true)
words++;
lastwhitespace=false;
}
else
lastwhitespace=true;
if(chars>0)
lines++;
}
System.out.println("no of chars="+chars);
System.out.println("no of words="+words);
System.out.println("no of lines="+lines);
} }

Output:
enter the file name
c:\hi.txt
no of chars=45
no of words=5
no of lines=50


12)Write a Java program that Implements stack ADT

SOURCE PROGRAM:

import java.util.*;
class stack
{
int size,top=-1;
char d[];
stack(int a)
{
size=a;
d=new char[size-1];
}
void display()
{
if(top<0)
{
System.out.println("no elements");
}
for(int i=0;i<=top;i++)
{
System.out.println(d[i]+" ");
} }
void push(char a)
{
if(top==size-1)
{
System.out.println("stack is full");
}
else
{
// System.out.println();
top+=1;
d[top]=a;
System.out.println(" the elements after inserting top are");
display();
}
}
void pop()
{
if(top==-1)
{
System.out.println("stack is empty");
}
else
{
d[top]=d[top-1];
top-=1;
System.out.print(" the elements after deleting top are ");
display();
}
} }
public class stack2
{
public static void main(String l[])
{
stack s=new stack(5);
s.push('h');
s.push('s');
s.push('a');
s.pop();
}
}

Output:
the elements after inserting top are
h
the elements after inserting top are
h
s
the elements after inserting top are
h
s
a
the elements after deleting top are
h
s



13)Write a Java program that Evaluates the postfix expression

SOURCE PROGRAM:

import java.util.*;
import java.io.*;
class Stack
{
final int SIZE=100;
private double stack[];
private int top;
Stack()
{ stack=new double[SIZE];
top=-1;
}
public boolean Push(double val)
{ if(top==SIZE)
{
return false;
}
else
{ stack[++top]=val;
return true;
}
}
public double Pop()
{ if(top==-1)
{ return -1;
}
return stack[top--];
}
}
class PostfixEvaluation
{
boolean isOperator(char input)
{
String oprs=" /*+-%";
if((oprs.indexOf(input))!=-1)
return true;
else
return false;
}
boolean isSpace(char input)
{ return(input==' ');
}
double getResult(double op1,double op2,char opr)
{ switch(opr)
{
case '+':
return op1+op2;
case '-':
return op1-op2;
case '/':
return op1/op2;
case '*':
return op1*op2;
case '%':
return op1%op2;
}
return 0;
}
public double Evaluate(String Str,double vals[])
{
int count=0;
int currentVal=0;
char Symbol;
double op1,op2,res;
Stack stk=new Stack();
while(count<=Str.length()-1)
{ Symbol=Str.charAt(count);
if(isSpace(Symbol))
{ count++;
continue;
}
else if(isOperator(Symbol))
{ op2=stk.Pop();
op1=stk.Pop();
res=getResult(op1,op2,Symbol);
stk.Push(res);
} else if(Character.isDigit(Symbol))
{
stk.Push(Double.parseDouble(Symbol+""));
}
else
{ stk.Push(vals[currentVal++]);
}
count++;
}
res=stk.Pop();
System.out.println("Result of Expression = "+res);
return res;
}
}
class postfixEval
{ public static void main(String args[]) throws IOException
{
String Expr;
double vals[]=new double[50];
Scanner sr=new Scanner(System.in);
System.out.println("Enter a Valid Postfix Expression:");
Expr=sr.nextLine();
int count=0;
int currentVal=0;
PostfixEvaluation e1=new PostfixEvaluation();

while(count<=Expr.length()-1)
{
if(!Character.isDigit(Expr.charAt(count)) && !e1.isOperator(Expr.charAt(count)) && !e1.isSpace(Expr.charAt(count)))
{
System.out.println("Enter a Value For: "+Expr.charAt(count));
vals[currentVal++]=sr.nextDouble();
}
count++;
}
e1.Evaluate(Expr,vals);
}
}

Output:
Enter a Valid Postfix Expression:
ab+
Enter a Value For: a 1
Enter a Value For: b 2
Result of Expression = 3.0


14)Develop an applet that displays a simple message.

SOURCE PROGRAM:

import java.applet.*;
import java.awt.*;
/**/
public class helloworld extends Applet
{
String msg="";
public void init()
{
msg+="init";

}
public void start()
{
msg+="start";
}
public void paint(Graphics g)
{
g.drawString(msg, 10, 10);
showStatus("helloworld");
}
}

Output:



15)Write a Java program that works as a sample calculator, use a grid layout to arrange buttons for the digits and for the + _ * % operations. Add a text field to display the result

SOURCE PROGRAM:

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener
{
JLabel a[];
JTextField b[];
JButton d[];
JPanel pan;
public static void main(String args[])
{
new Calculator();
}
public Calculator()
{
int i;
Container c=getContentPane();
c.setLayout(new GridLayout(3,2));
pan=new JPanel();
pan.setLayout(new GridLayout(1,8));
a=new JLabel[3];
b=new JTextField[3];
d=new JButton[8];
for(i=0;i<=a.length-1;i++)
{
a[i]=new JLabel();
b[i]=new JTextField(10);
b[i].addActionListener(this);
c.add(a[i]);
c.add(b[i]);
} a[0].setText("first number");
a[1].setText("second number");
a[2].setText("result");
b[2].setEditable(false);
for(i=0;i<=d.length-1;i++)
{ String names[]={"+","-","*","/","%","sqrt","pow","exit"};
d[i]=new JButton(names[i]);
pan.add(d[i]);
d[i].addActionListener(this);
} c.add(pan,BorderLayout.SOUTH);
setSize(500,300);
show();
} public void actionPerformed(ActionEvent e)
{ int value1,value2;
value1=Integer.parseInt(b[0].getText());
value2=Integer.parseInt(b[1].getText());
if(e.getSource()==d[0])
b[2].setText(" "+(value1+value2));
else if(e.getSource()==d[1])
b[2].setText(" "+(value1-value2));
else if(e.getSource()==d[2])
b[2].setText(" "+(value1*value2));
else if(e.getSource()==d[3])
b[2].setText(" "+(value1/value2));
else if(e.getSource()==d[4])
b[2].setText(" "+(value1%value2));
else if(e.getSource()==d[5])
b[2].setText(" "+Math.sqrt(value1));
else if(e.getSource()==d[6])
b[2].setText(" "+Math.pow(value1,value2));
else
System.exit(0);
}
}

Output:


16)Write a java program for handling mouse events

SOURCE PROGRAM:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**/
public class mousedemo extends Applet implements MouseListener, MouseMotionListener {
String msg="";
int x=10,y=10;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
msg="clicked";
}
public void mouseEntered(MouseEvent me)
{
msg="mouse is on applet";
repaint();
}
public void mouseExited(MouseEvent me)
{
msg="mouse is outside applet";
repaint();
}
public void mousePressed(MouseEvent me)
{
msg="move button down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
msg="mouse button up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
msg="mouse is outside applet";
repaint();
}
public void mouseMoved(MouseEvent me)
{
int mx=me.getX();
int my=me.getY();
showStatus("mouse moving at"+me.getX()+","+me.getY());

repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, x, y) ;
}
}


OUTPUT:


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

SOURCE PROGRAM:

import java.lang.String.*;
import java.lang.*;
class threadd implements Runnable
{
Thread t;
String msg;
long waittime;
threadd(long wt,String message)
{
t=new Thread("print thread");
msg=message;
waittime=wt;
t.start();

}
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(msg);
try
{
Thread.sleep(waittime);
}
catch(InterruptedException ae)
{
System.out.println("execpton"+ae);
}
} }
}
public class threaddemo {
public static void main(String j[])
{
threadd h=new threadd(1000,"goodmorning");
h.run();
threadd w=new threadd(2000,"hello");
w.run();
threadd g=new threadd(3000,"welcome");
g.run();
try
{
Thread.sleep(15000);
}
catch(InterruptedException ae)
{
System.out.println("execpton"+ae);
}
}
}

Output:
goodmorning
goodmorning
goodmorning
goodmorning
goodmorning
hello
hello
hello
hello
hello
welcome
welcome
welcome
welcome
welcome


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

SOURCE PROGRAM:

class q
{
int n;
boolean valueset=false;
synchronized int get()
{
while(!valueset)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("get"+n);
valueset=false;
notify();
return n;
}
return n;
}
synchronized void put(int n)
{
while(valueset)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
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,"produce").start();
}
public void run()
{
int i=0;
while(true)
{
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();
}
}
}
public class demo
{
public static void main(String k[])
{
q q=new q();
new producer(q);
new consumer(q);
System.out.println("press ctrl+c to stop");
}
}

Output:
press ctrl+c to stop
put0
get0
put1
get1
put2
get2
put3
get3
put4
get4
put5
get5
put6
get6





19)Write a Java program to create an abstract class named shape that contains an empty method named numberOfsides(). Provide three classes named trapezoidal, triangle and hexagon such that each one of the classes extends the shape. Each one of the classes contains only the method numberOfsides() that shows the no of sides in the given geometrical figure

SOURCE PROGRAM:

abstract class shape
{
abstract void numberofsides();

}
class trapezoid extends shape
{
int sides;
trapezoid()
{
sides=4;
}
void numberofsides()
{
System.out.println("trapezoid has "+sides+"sides");
}
}

class triangle extends shape
{
int sides;
triangle()
{
sides=3;
}
void numberofsides()
{
System.out.println("triangle has "+sides+"sides");
}
}
class hexagon extends shape
{
int sides;
hexagon()
{
sides=6;
}
void numberofsides()
{
System.out.println("square has "+sides+"sides");
}

}

public class abstracts{
public static void main(String k[])
{
trapezoid g=new trapezoid();
triangle t=new triangle();
hexagon s=new hexagon();
t.numberofsides();
g.numberofsides();
s.numberofsides();
}
}

Output:
triangle has 3sides
trapezoid has 4sides
square has 6sides


ADDITIONAL
ADVANCED PROGRAMMES


20)Write a program to demonstrate method overloading.

SOURCE PROGRAM:

class OverloadDemo
{
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625


21)Write a program to overloading constructors with example

SOURCE PROGRAM:

class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}

output
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0


22)Write a program to pass objects as parameters

SOURCE PROGRAM:

class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
} // return true if o is equal to the invoking object
boolean equals(Test o)
{
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}

Output:
ob1 == ob2: true
ob1 == ob3: false


23)Write a program to understand recursion. (Factorial of a number)

SOURCE PROGRAM:

class Factorial
{
// this is a recursive function
int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}

output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120


24)Write a program to Demonstrate equals() and equalsIgnoreCase().

SOURCE PROGRAM:

Demonstrate equals() and equalsIgnoreCase().
class equalsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " ->" +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}

Output:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HEL LO -> true


25)Write a program to Demonstrate append().

SOURCE PROGRAM:

class appendDemo
{
public static void main(String args[])
{
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}


Output:
a = 42!

26)Write a Java program to understand inheritance concepts along with the help of super

SOURCE PROGRAM:

// A complete implementation of BoxWeight.
class Box
{
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box
{
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob)
{ // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight()
{
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m)
{
super(len);
weight = m;
}
}
class DemoSuper
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}

output:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
Volume of mybox3 is -1.0
Weight of mybox3 is -1.0
Volume of myclone is 3000.0
Weight of myclone is 34.3
Volume of mycube is 27.0
Weight of mycube is 2.0


27)Write a Java program to use method overriding

SOURCE PROGRAM:

class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

Output
k: 3


28)Write a Java program to study Dynamic Method Dispatch

SOURCE PROGRAM:

class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}

output
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method


29)Write a Java program to use packages and illustrate with simple account example

SOURCE PROGRAM:

package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}

Output:
K. J. Fielding: $123.23
Will Tell: $157.02
--> Tom Jackson: $-12.33


30)Write a Java program to create a package which will import other packages example testbalance imports previous accountbalance

SOURCE PROGRAM:

package MyPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name = n;
bal = b;
}
public void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class TestBalance
{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}

Output:
J. J. Jaspers: $99.88


31)Write a Java program to extend interfaces

SOURCE PROGRAM:

interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Output
Implement meth1().
Implement meth2().
Implement meth3().


32)Write a Java program to use multiple catch clauses

SOURCE PROGRAM:

class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}

Output:
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.


33)Write a Java program to use throw

SOURCE PROGRAM:

class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}

output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo


34)Write a Java program to use throws

SOURCE PROGRAM:

class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

Output:

inside throwOne
caught java.lang


35)Write a Java program to use finally

SOURCE PROGRAM:

class FinallyDemo
{
// Through an exception out of the method.
static void procA()
{
try
{
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally
{
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB()
{
try
{
System.out.println("inside procB");
return;
}
finally
{
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC()
{
try
{
System.out.println("inside procC");
}
finally
{
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try
{
procA();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();
}

Output:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally


36)Write a Java program to create and use multiple threading concepts

SOURCE PROGRAM:

class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try {
for(int i = 5; i>0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.


36)Write a Java program on thread priorities

SOURCE PROGRAM:

class clicker implements Runnable
{
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p)
{
t = new Thread(this);
t.setPriority(p);
}
public void run()
{
while (running)
{
click++;
}
}
public void stop()
{
running = false;
}
public void start()
{
t.start();
}
}
class HiLoPri
{
public static void main(String 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();
try {
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try
{
hi.t.join();
lo.t.join();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}

Output:
Low-priority thread: 4408112
High-priority thread: 589626904




37)Write a Java program to demonstrate Deadlock

SOURCE PROGRAM:

class A
{
synchronized void foo(B b)
{
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}
synchronized void last()
{
System.out.println("Inside A.last");
}
}
class B
{
synchronized void bar(A a)
{
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try
{
Thread.sleep(1000);
} catch(Exception e)
{
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last()
{
System.out.println("Inside A.last");
}
}
class Deadlock implements Runnable
{
A a = new A();
B b = new B();
Deadlock()
{
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run()
{
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}
public static void main(String args[])
{
new Deadlock();
}
}

Output:
MainThread entered A.foo
RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()



38)Write a program to create an applet using foreground, background colors & outputs a string.

SOURCE PROGRAM:

import java.awt.*;
import java.applet.*;
/* */
public class Sample extends Applet
{
String msg;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
public void start() {
msg += " Inside start( ) --";
}
public void paint(Graphics g)
{
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}

Output:

1 comment: