63
WEEK – 1 (A.) Write a Java program that prints all real solutions to the quadratic equation ax 2 +bx+c= 0. Read in a, b, c and use the quadratic formula. If the discriminant b 2 -4ac is negative, display a message stating that there are no real solutions. Program : import java.io.*; import java.lang.*; import java.util.*; class Quadratic { public static void main(String args[])throws IOException { double x1,x2,disc,a,b,c; InputStreamReader obj=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(obj); System.out.println("enter a,b,c values"); a=Double.parseDouble(br.readLine()); b=Double.parseDouble(br.readLine()); c=Double.parseDouble(br.readLine()); disc=(b*b)-(4*a*c); if(disc==0) { System.out.println("roots are real and equal "); x1=x2=-b/(2*a); System.out.println("roots are "+x1+","+x2); } else if(disc>0) { System.out.println("roots are real and unequal"); x1=(-b+Math.sqrt(disc))/(2*a); x2=(-b+Math.sqrt(disc))/(2*a); System.out.println("roots are "+x1+","+x2); } else { System.out.println("roots are imaginary"); }

Java Programming Lab Programs List

Embed Size (px)

Citation preview

Page 1: Java Programming Lab Programs List

WEEK – 1

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

Program :import java.io.*;import java.lang.*;import java.util.*;class Quadratic{

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

double x1,x2,disc,a,b,c;InputStreamReader obj=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(obj);System.out.println("enter a,b,c values");a=Double.parseDouble(br.readLine());b=Double.parseDouble(br.readLine());c=Double.parseDouble(br.readLine());disc=(b*b)-(4*a*c);if(disc==0)

{System.out.println("roots are real and equal ");x1=x2=-b/(2*a);System.out.println("roots are "+x1+","+x2);

}else if(disc>0)

{System.out.println("roots are real and unequal");x1=(-b+Math.sqrt(disc))/(2*a);x2=(-b+Math.sqrt(disc))/(2*a);System.out.println("roots are "+x1+","+x2);

}else

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

}}

}

Page 2: Java Programming Lab Programs List

Input & Output :

(B.) The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it.Write a Java program that uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence.

Program :/*Non Recursive Solution*/Import java.io.*;import java.util.Scanner;class Fib {

public static void main(String args[ ]) {

Scanner input=new Scanner(System.in);int i,a=1,b=1,c=0,t;System.out.println("Enter value of t:");t=input.nextInt();System.out.print(a);System.out.print(" "+b);for(i=0;i<t-2;i++)

{c=a+b;a=b;b=c;System.out.print(" "+c);

}

System.out.println();System.out.print(t+"th value of the series is: "+c);

}}

Page 3: Java Programming Lab Programs List

Input & Output :

/* Recursive Solution*/import java.io.*;import java.lang.*;class Demo {

int fib(int n) {

if(n==1)return (1);else if(n==2)return (1);elsereturn (fib(n-1)+fib(n-2));

}}

class RecFibDemo {

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

InputStreamReader obj=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(obj);System.out.println("enter last number");int n=Integer.parseInt(br.readLine());Demo ob=new Demo();System.out.println("fibonacci series is as follows");int res=0;for(int i=1;i<=n;i++)

{res=ob.fib(i);System.out.println(" "+res);

}System.out.println();System.out.println(n+"th value of the series is "+res);

}}

Page 4: Java Programming Lab Programs List

Input & Output :

Page 5: Java Programming Lab Programs List

WEEK – 2

(A.) WAJP that prompts the user for an integer and then prints out all the prime numbers up to that Integer.

Program :

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

void check(int num) {

System.out.println ("Prime numbers up to "+num+" are:");for (int i=1;i<=num;i++)for (int j=2;j<i;j++) {

if(i%j==0)break;

else if((i%j!=0)&&(j==i-1))System.out.print(“ “+i);

}}

} //end of class Test

class Prime {

public static void main(String args[ ]) {

Test obj1=new Test();Scanner input=new Scanner(System.in);System.out.println("Enter the value of n:");int n=input.nextInt();obj1.check(n);

}}

Input & Output :

Page 6: Java Programming Lab Programs List

(B.) WAJP to multiply two given matrices

Program :import java.util.*;class Test {

int r1,c1,r2,c2;Test(int r1,int c1,int r2,int c2)

{this.r1=r1;this.c1=c1;this.r2=r2;this.c2=c2;

}int[ ][ ] getArray(int r,int c)

{int arr[][]=new int[r][c];System.out.println("Enter the elements for "+r+"X"+c+" Matrix:");Scanner input=new Scanner(System.in);for(int i=0;i<r;i++)for(int j=0;j<c;j++)

arr[i][j]=input.nextInt();return arr;

}

int[ ][ ] findMul(int a[ ][ ],int b[ ][ ]) {

int c[][]=new int[r1][c2];for (int i=0;i<r1;i++)for (int j=0;j<c2;j++) {

c[i][j]=0;for (int k=0;k<r2;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];}return c;

}void putArray(int res[ ][ ])

{System.out.println ("The resultant "+r1+"X"+c2+" Matrix is:");for (int i=0;i<r1;i++) {

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

}}

} //end of Test class

Page 7: Java Programming Lab Programs List

class MatrixMul {

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

Test obj1=new Test(2,3,3,2);Test obj2=new Test(2,3,3,2);int x[ ][ ],y[ ][ ],z[ ][ ];System.out.println("MATRIX-1:");x=obj1.getArray(2,3); //to get the matrix from userSystem.out.println("MATRIX-2:");y=obj2.getArray(3,2);z=obj1.findMul(x,y); //to perform the multiplicationobj1.putArray(z); // to display the resultant matrix

}}Input & Output :

Page 8: Java Programming Lab Programs List

(C.) WAJP that reads a line of integers and then displays each integer and the sum of all integers. (use StringTokenizer class)

Program :// Using StringTokenizer class

import java.util.*; import j ava.lang.*;class tokendemo {

public static void main(String args[ ]) {

String s="10,20,30,40,50";int sum=0;StringTokenizer a=new StringTokenizer(s,",",false);System.out.println("integers are ");while(a.hasMoreTokens())

{int b=Integer.parseInt(a.nextToken());sum=sum+b;System.out.println(" "+b);

}System.out.println("sum of integers is "+sum);

}}Input & Output :

Page 9: Java Programming Lab Programs List

// Alternate solution using command line argumentsimport java.util.*; import j ava.lang.*;class Arguments {

public static void main(String args[ ]) {

int sum=0;int n=args.length;System.out.println("length is "+n);int arr[]=new int[n];for(int i=0;i<n;i++)

arr[i]=Integer.parseInt(args[i]);System.out.println("The enterd values are:");for(int i=0;i<n;i++)

System.out.println(arr[i]);System.out.println("sum of enterd integers is:");for(int i=0;i<n;i++)

sum=sum+arr[i];System.out.println(sum);

}}

Input & Output :

Page 10: Java Programming Lab Programs List

WEEK – 3

(A.) WAJP that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome.

Program :

import java.io.*;import java.util.*;import java.lang.*;class Palind {

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

{BufferedReader br=new BufferedReader(newInputStreamReader(System.in));System.out.println("Enter the string to check for palindrome:");String s1=br.readLine();StringBuffer sb=new StringBuffer();sb.append(s1);sb.reverse();String s2=sb.toString();if(s1.equals(s2))

System.out.println("palindrome");else

System.out.println("not palindrome");}

}

Page 11: Java Programming Lab Programs List

(B.) WAJP for sorting a given list of names in ascending order.

Program :import java.io.*;class Test {

int len,i,j;String arr[ ];Test(int n) {

len=n;arr=new String[n];

}

String[ ] getArray() throws IOException {

BufferedReader br=new BufferedReader (new InputStreamReader(System.in));System.out.println ("Enter the strings U want to sort----");for (int i=0;i<len;i++)

arr[i]=br.readLine();return arr;

}

String[ ] check() throws ArrayIndexOutOfBoundsException {

for (i=0;i<len-1;i++) {

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

if ((arr[i].compareTo(arr[j]))>0) {

String s1=arr[i];arr[i]=arr[j];arr[j]=s1;

}}

}return arr;

}

void display()throws ArrayIndexOutOfBoundsException {

System.out.println ("Sorted list is---");for (i=0;i<len;i++)

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

} //end of the Test class

class Ascend {

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

Page 12: Java Programming Lab Programs List

Test obj1=new Test(4);obj1.getArray();obj1.check();obj1.display();

}}

Input & Output :

Page 13: Java Programming Lab Programs List

(C.) Write a java program to make frequency count of words in a given text.

Pending

Page 14: Java Programming Lab Programs List

WEEK – 4

(A.) WAJP that reads on file name from the user, then displays information about whether the file exists, whether the file is readable, wheteher the file is writable,the type of file and the length of the file in bytes.

Program :import java.io.File;class FileDemo {

static void p(String s) {

System.out.println(s);}public static void main(String args[ ]) {

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

}}

Page 15: Java Programming Lab Programs List

(B.) WAJP that reads a file and displays the file on the screen, with a line number before each line.

Program :

import java.io.*;class LineNum{

public static void main(String args[]){

String thisline;for(int i=0;i<args.length;i++){Try

{LineNumberReader br=new LineNumberReader(newFileReader(args[i]));while((thisline=br.readLine())!=null){

System.out.println(br.getLineNumber()+"."+thisline);}

}catch(IOException e){

System.out.println("error:"+e);}

}}

}

Page 16: Java Programming Lab Programs List

(C.) WAJP that displays the number of characters, lines and words in a text file.

Program :import java.io.*;public class FileStat {

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

long nl=0,nw=0,nc=0;String line;BufferedReader br=new BufferedReader(new FileReader(args[0]));while ((line=br.readLine())!=null) {

nl++;nc=nc+line.length();int i=0;boolean pspace=true;while (i<line.length()) {

char c=line.charAt(i++);boolean cspace=Character.isWhitespace(c);if (pspace&&!cspace)

nw++;pspace=cspace;

}}System.out.println("Number of Characters"+nc);System.out.println("Number of Characters"+nw);System.out.println("Number of Characters"+nl);

}}

Page 17: Java Programming Lab Programs List
Page 18: Java Programming Lab Programs List

WEEK – 5

WAJP that:(a) Implements a Stack ADT(b) Converts Infix expression to Postfix expression(c) Evaluates a Postfix expression

(a.)Program :import java.io.*;interface stack{

void push(int item);int pop();

}class Stackimpl{

private int stck[];private int top;

Stackimpl(int size){

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

}

void push(int item){

if(top==stck.length-1)System.out.println("stack is full insertion is not possible");

elsestck[++top]=item;

}

int pop(){

if(top==-1){

System.out.println("stack is empty deletion is not possible");return 0;

}else

return stck[top--];}

}

Page 19: Java Programming Lab Programs List

class Stackdemo{

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

int a[];BufferedReader br=new BufferedReader(newInputStreamReader(System.in));System.out.println("enter the size of the array");int n=Integer.parseInt(br.readLine());Stackimpl obj1=new Stackimpl(n);a=new int[n];System.out.println("enter numbers into the stack");for(int i=0;i<n;i++)a[i]=Integer.parseInt(br.readLine());System.out.println("numbers are inserted");for(int i=0;i<n;i++)

obj1.push(a[i]);System.out.println("The following numbers are poped out.");for(int i=0;i<n;i++)System.out.println(" "+obj1.pop());

}}

Input & Output :

Page 20: Java Programming Lab Programs List

Program Statement :Write an Applet that displays a simple message.Program :import java.awt.*;import java.applet.*;/*<applet code = “HelloJava” width = 200 height = 60 ></applet>*/public class HelloJava extends Applet {public void paint(Graphics g) {g.drawString(“Hello Java”, 10, 100);}}Input & Output :

Program Statement :Write an Applet that computes the payment of a loan based on the amount of theloan, the interest rate and the number of months. It takes one parameter from thebrowser: Monthly rate; if true, the interest rate is per month, otherwise the interestrate is annual.Program :import java.awt.*;import java.awt.event.*;import java.applet.*;/* <applet code = "LoanPayment" width=500 height=300 ><param name = monthlyRate value=true></applet>*/public class LoanPayment extends Applet implements ActionListener {

Page 21: Java Programming Lab Programs List

TextField amt_t, rate_t, period_t;Button compute = new Button("Compute");boolean monthlyRate;public void init() {Label amt_l = new Label("Amount: ");Label rate_l = new Label("Rate: ", Label.CENTER);Label period_l = new Label("Period: ", Label.RIGHT);amt_t = new TextField(10);rate_t = new TextField(10);period_t = new TextField(10);add(amt_l);add(amt_t);add(rate_l);add(rate_t);add(period_l);add(period_t);add(compute);amt_t.setText("0");rate_t.setText("0");period_t.setText("0");monthlyRate = Boolean.valueOf(getParameter("monthlyRate"));amt_t.addActionListener(this);rate_t.addActionListener(this);period_t.addActionListener(this);compute.addActionListener(this);}public void paint(Graphics g) {double amt=0, rate=0, period=0, payment=0;String amt_s, rate_s, period_s, payment_s;g.drawString("Input the Loan Amt, Rate and Period in each box andpress Compute", 50,100);try {amt_s = amt_t.getText();amt = Double.parseDouble(amt_s);rate_s = rate_t.getText();rate = Double.parseDouble(rate_s);period_s = period_t.getText();period = Double.parseDouble(period_s);}catch (Exception e) { }if (monthlyRate)payment = amt * period * rate * 12 / 100;elsepayment = amt * period * rate / 100;payment_s = String.valueOf(payment);g.drawString("The LOAN PAYMENT amount is: ", 50, 150);g.drawString(payment_s, 250, 150);}public void actionPerformed(ActionEvent ae) {repaint();}}Input & Output :

Page 22: Java Programming Lab Programs List

Program Statement :WAJP that works as a simple calculator. Use a grid layout to arrange buttons forthe digits and for the + - x / % operations. Add atext field to display the result.Program :import javax.swing.*;import java.awt.*;import java.awt.event.*;//<applet code=Calculator height=300 width=200></applet>

Page 23: Java Programming Lab Programs List

public class Calculator extends JApplet {public void init() {CalculatorPanel calc=new CalculatorPanel();getContentPane().add(calc);}}class CalculatorPanel extends JPanel implements ActionListener {JButtonn1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;static JTextField result=new JTextField("0",45);static String lastCommand=null;JOptionPane p=new JOptionPane();double preRes=0,secVal=0,res;private static void assign(String no){if((result.getText()).equals("0"))result.setText(no);else if(lastCommand=="="){result.setText(no);lastCommand=null;}elseresult.setText(result.getText()+no);}public CalculatorPanel() {setLayout(new BorderLayout());result.setEditable(false);result.setSize(300,200);add(result,BorderLayout.NORTH);JPanel panel=new JPanel();panel.setLayout(new GridLayout(4,4));n7=new JButton("7");panel.add(n7);n7.addActionListener(this);n8=new JButton("8");panel.add(n8);n8.addActionListener(this);n9=new JButton("9");panel.add(n9);n9.addActionListener(this);div=new JButton("/");panel.add(div);div.addActionListener(this);n4=new JButton("4");panel.add(n4);n4.addActionListener(this);n5=new JButton("5");panel.add(n5);n5.addActionListener(this);n6=new JButton("6");panel.add(n6);n6.addActionListener(this);

Page 24: Java Programming Lab Programs List

mul=new JButton("*");panel.add(mul);mul.addActionListener(this);n1=new JButton("1");panel.add(n1);n1.addActionListener(this);n2=new JButton("2");panel.add(n2);n2.addActionListener(this);n3=new JButton("3");panel.add(n3);n3.addActionListener(this);minus=new JButton("-");panel.add(minus);minus.addActionListener(this);dot=new JButton(".");panel.add(dot);dot.addActionListener(this);n0=new JButton("0");panel.add(n0);n0.addActionListener(this);equal=new JButton("=");panel.add(equal);equal.addActionListener(this);plus=new JButton("+");panel.add(plus);plus.addActionListener(this);add(panel,BorderLayout.CENTER);}public void actionPerformed(ActionEvent ae){if(ae.getSource()==n1) assign("1");else if(ae.getSource()==n2) assign("2");else if(ae.getSource()==n3) assign("3");else if(ae.getSource()==n4) assign("4");else if(ae.getSource()==n5) assign("5");else if(ae.getSource()==n6) assign("6");else if(ae.getSource()==n7) assign("7");else if(ae.getSource()==n8) assign("8");else if(ae.getSource()==n9) assign("9");else if(ae.getSource()==n0) assign("0");else if(ae.getSource()==dot){if(((result.getText()).indexOf("."))==-1)result.setText(result.getText()+".");}else if(ae.getSource()==minus){preRes=Double.parseDouble(result.getText());lastCommand="-";result.setText("0");}else if(ae.getSource()==div)

Page 25: Java Programming Lab Programs List

{preRes=Double.parseDouble(result.getText());lastCommand="/";result.setText("0");}else if(ae.getSource()==equal){secVal=Double.parseDouble(result.getText());if(lastCommand.equals("/"))res=preRes/secVal;else if(lastCommand.equals("*"))res=preRes*secVal;else if(lastCommand.equals("-"))res=preRes-secVal;else if(lastCommand.equals("+"))res=preRes+secVal;result.setText(" "+res);lastCommand="=";}else if(ae.getSource()==mul){preRes=Double.parseDouble(result.getText());lastCommand="*";result.setText("0");}else if(ae.getSource()==plus){preRes=Double.parseDouble(result.getText());lastCommand="+";result.setText("0");}}}

Page 26: Java Programming Lab Programs List

Program Statement :WAJP for handling mouse events.Program :import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="MouseEvents" width=300 height=100></applet>*/public class MouseEvents extends Appletimplements MouseListener, MouseMotionListener {String msg = "";int mouseX = 0, mouseY = 0; // coordinates of mousepublic void init() {addMouseListener(this);addMouseMotionListener(this);}// Handle mouse clicked.public void mouseClicked(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse clicked.";repaint();}// Handle mouse entered.public void mouseEntered(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse entered.";repaint();}// Handle mouse exited.public void mouseExited(MouseEvent me) {// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse exited.";repaint();}// Handle button pressed.public void mousePressed(MouseEvent me) {// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "Down";repaint();}// Handle button released.public void mouseReleased(MouseEvent me) {

Page 27: Java Programming Lab Programs List

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

Page 28: Java Programming Lab Programs List

Program Statement :WAJP for creating multiple threads.Program :class NewThread implements Runnable {String name; // name of threadThread 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 threadsnew NewThread("Two");new NewThread("Three");try {// wait for other threads to endThread.sleep(10000);} catch (InterruptedException e) {System.out.println("Main thread Interrupted");}System.out.println("Main thread exiting.");}}

Page 29: Java Programming Lab Programs List

Program Statement :WAJP that correctly implements Producer-Consumer problem using the concept ofInter Thread Communication.Program :class Q {int n;boolean valueSet = false;synchronized int get() {if (!valueSet)try {wait();} catch (InterruptedException e) { }System.out.println(“Got: “ + n);valueSet = false;notify();return n;}synchronized void put(int n) {if (valueSet)try {wait();} catch (InterruptedException 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, “Producer”).start();}public void run() {int i = 0;while(true) {q.put(i++);}}}class Consumer implements Runnable {Q q;

Page 30: Java Programming Lab Programs List

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 Ctrl-C to stop”);}}

Program Statement :WAJP that lets users create Pie charts. Design your own user interface (withSwings & AWT).Program :import java.awt.*;import java.applet.*;/*<applet code=PiChart.class width=600 height=600></applet>*/public class PiChart extends Applet {public void paint(Graphics g) {setBackground(Color.green);g.drawString("PI CHART",200,40);g.setColor(Color.blue);g.fillOval(50,50,150,150);g.setColor(Color.white);g.drawString("40%",130,160);g.setColor(Color.magenta);g.fillArc(50,50,150,150,0,90);g.setColor(Color.white);g.drawString("25%",140,100);g.setColor(Color.yellow);g.fillArc(50,50,150,150,90,120);g.setColor(Color.black);g.drawString("35%",90,100);g.setColor(Color.yellow);g.fillOval(250,50,150,150);g.setColor(Color.black);g.drawString("15%",350,150);g.setColor(Color.magenta);g.fillArc(250,50,150,150,0,30);g.setColor(Color.black);g.drawString("5%",360,120);g.setColor(Color.blue);g.fillArc(250,50,150,150,30,120);g.setColor(Color.white);

Page 31: Java Programming Lab Programs List

g.drawString("30%",330,100);g.setColor(Color.black);g.fillArc(250,50,150,150,120,180);g.setColor(Color.white);g.drawString("50%",280,160);}}Input & Output :

Program Statement :WAJP that allows user to draw lines, rectangles and ovals.Program :import javax.swing.*;import java.awt.Graphics;public class Choice extends JApplet{int i,ch;public void init(){String input;input=JOptionPane.showInputDialog("enter your choice(1-lines,2-rectangles,3-ovals)");ch=Integer.parseInt(input);}public void paint(Graphics g){switch(ch){case 1:{for(i=1;i<=10;i++){g.drawLine(10,10,250,10*i);}break;}case 2:{for(i=1;i<=10;i++){g.drawRect(10*i,10*i,50+10*i,50+10*i);}break;}case 3:{for(i=1;i<=10;i++){g.drawOval(10*i,10*i,50+10*i,50+10*i);

Page 32: Java Programming Lab Programs List

}break;}}}}Input & Output :

Program Statement :WAJP that implements a simple client/server application. The client sends data to aserver. The server receives the data, uses it to produce a result and then sends theresult back to the client. The client displays the result on the console. For ex: Thedata sent from the client is the radius of a circle and the result produced by theserver is the area of the circle.Program :// Server Programimport java.io.*;import java.net.*;import java.util.*;public class Server {public void static main (String args [ ] ) {try {// create a server socketServerSocket s = new ServerSocket(8000);// start listening for connections on srver socketSocket connectToClient = s.accept();// create a buffered reader stream to get data from clientBufferedReader isFromClient = new BufferedReader(newInputStreamReader (connectToClient.getInputStream()));// create a buffer reader to send result to clientPrintWriter osToClient = newPrintWriter(connectToClient.getOutputStream(), true);// continuously read from client, process, send backwhile (true) {// read a line and create string tokenizerStringTokenizer st = newStringTokenizer(isFromClient.readLine());//convert string to doubledouble radius = newDouble(st.nextToken()).doubleValue();// display radius on consoleSystem.out.println(“Radius received from client: “ +

Page 33: Java Programming Lab Programs List

radius);// comput areadouble area = radius * radius *Math.PI;// send result to clientosToClient.println(area);// print result on consoleSystem.out.println(“Area found: “ +area);}} catch (IOException e) {System.err.println(e);}}}// Client Programimport java.io.*;import java.net.*;import java.util.*;public class Client {public void static main (String args [ ] ) {try {// create a socket to connect to serverSocket connectToServer = new Socket(“local host”, 8000);// create a buffered input stream to get result from serverBufferedReader isFromServer = new BufferedReader(newInputStreamReader (connectToServer.getInputStream()));// create a buffer output stream to send data to serverPrintWriter osToServer = newPrintWriter(connectToServer.getOutputStream(), true);// continuously send radius and get areawhile (true) {Scanner input=new Scanner(System.in);System.out.print(“Please enter a radius: “);double radius =input.nextDouble();// display radius on consoleosToServer.println(radius);// get area from serverStringTokenizer st = newStringTokenizer(isFromServer.readLine());// convert string to doubleDouble area = newDouble(st.nextToken()).doubleValue();// print result on consoleSystem.out.println(“Area received from the server is: “+area);}} catch (IOException e) {System.err.println(e);}}}

Page 34: Java Programming Lab Programs List

Program Statement :WAJP that illustrates how runtime polymorphism is achieved.Program :class Figure {double dim1;double dim2;Figure(double a, double b) {dim1 = a;dim2 = b;}double area() {System.out.println("Area for Figure is undefined.");return 0;}}class Rectangle extends Figure {Rectangle(double a, double b) {super(a, b);}// override area for rectangledouble area() {System.out.println("Inside Area for Rectangle.");return dim1 * dim2;}}class Triangle extends Figure {Triangle(double a, double b) {super(a, b);

Page 35: Java Programming Lab Programs List

}// override area for right triangledouble area() {System.out.println("Inside Area for Triangle.");return dim1 * dim2 / 2;}}class FindAreas {public static void main(String args[]) {Figure f = new Figure(10, 10);Rectangle r = new Rectangle(9, 5);Triangle t = new Triangle(10, 8);Figure figref;figref = r;System.out.println("Area is " + figref.area());figref = t;System.out.println("Area is " + figref.area());figref = f;System.out.println("Area is " + figref.area());}}

Program Statement :WAJP to create an abstract class named Shape, that contains an empty methodnamed numberOfSides(). Provide three classes named Trapezoid, Triangle andHexagon, such that each one of the classes contains only the methodnumberOfSides(), that contains the number of sides in the given geometricalfigure.Program :abstract class Shape{abstract void numberOfSides();}class Trapezoid extends Shape{void numberOfSides() {System.out.println(" Trapezoidal has four sides");}}class Triangle extends Shape {void numberOfSides(){System.out.println("Triangle has three sides");}}class Hexagon extends Shape {void numberOfSides(){

Page 36: Java Programming Lab Programs List

System.out.println("Hexagon has six sides");}}class ShapeDemo {public static void main(String args[ ]) {Trapezoid t=new Trapezoid();Triangle r=new Triangle();Hexagon h=new Hexagon();Shape s;s=t;s.numberOfSides();s=r;s.numberOfSides();s=h;s.numberOfSides();}}Input & Output

Program Statement :WAJP to implement a Queue, using user defined Exception Handling (also makeuse of throw, throws).Program :import java.util.Scanner;class ExcQueue extends Exception {ExcQueue(String s) {super(s);}}class Queue {int front,rear;int q[ ]=new int[10];Queue() {rear=-1;front=-1;}void enqueue(int n) throws ExcQueue {if (rear==9)throw new ExcQueue("Queue is full");rear++;q[rear]=n;

Page 37: Java Programming Lab Programs List

if (front==-1)front=0;}int dequeue() throws ExcQueue {if (front==-1)throw new ExcQueue("Queue is empty");int temp=q[front];if (front==rear)front=rear=-1;elsefront++;return(temp);}}class UseQueue {public static void main(String args[ ]) {Queue a=new Queue();try {a.enqueue(5);a.enqueue(20);} catch (ExcQueue e) {System.out.println(e.getMessage());}try {System.out.println(a.dequeue());System.out.println(a.dequeue());System.out.println(a.dequeue());} catch(ExcQueue e) {System.out.println(e.getMessage());}}}Input & Output :Program Statement :WAJP that creates 3 threads by extending Thread class. First thread displays“Good Morning” every 1 sec, the second thread displays “Hello” every 2 secondsand the third displays “Welcome” every 3 seconds. (Repeat the same byimplementing Runnable)Program :// Using Thread classclass One extends Thread {public void run() {for ( ; ; ) {try{sleep(1000);}catch(InterruptedException e){}System.out.println("Good Morning");}}}class Two extends Thread {public void run() {for ( ; ; ) {

Page 38: Java Programming Lab Programs List

try{sleep(2000);}catch(InterruptedException e){}System.out.println("Hello");}}}class Three extends Thread {public void run() {for ( ; ; ) {try{sleep(3000);}catch(InterruptedException e){}System.out.println("Welcome");}}}class MyThread {public static void main(String args[ ]) {Thread t = new Thread();One obj1=new One();Two obj2=new Two();Three obj3=new Three();Thread t1=new Thread(obj1);Thread t2=new Thread(obj2);Thread t3=new Thread(obj3);t1.start();try{t.sleep(1000);}catch(InterruptedException e){}t2.start();try{t.sleep(2000);}catch(InterruptedException e){}t3.start();try{t.sleep(3000);}catch(InterruptedException e){}}}// Using Runnable interfaceclass One implements Runnable {One( ) {new Thread(this, "One").start();try{Thread.sleep(1000);}catch(InterruptedException e){}}public void run() {for ( ; ; ) {try{Thread.sleep(1000);}catch(InterruptedException e){}

Page 39: Java Programming Lab Programs List

System.out.println("Good Morning");}}}class Two implements Runnable {Two( ) {new Thread(this, "Two").start();try{Thread.sleep(2000);}catch(InterruptedException e){}}public void run() {for ( ; ; ) {try{Thread.sleep(2000);}catch(InterruptedException e){}System.out.println("Hello");}}}class Three implements Runnable {Three( ) {new Thread(this, "Three").start();try{Thread.sleep(3000);}catch(InterruptedException e){}}public void run() {for ( ; ; ) {try{Thread.sleep(3000);}catch(InterruptedException e){}System.out.println("Welcome");}}}class MyThread {public static void main(String args[ ]) {One obj1=new One();Two obj2=new Two();Three obj3=new Three();}}Input & Output :

WAJP that will compute the following series:(a) 1 + 1/2 + 1/3+ …….+ 1/n(b) 1 + 1/2 + 1/ 22 + 1/ 23 + … … + 1/ 2n(c) ex = 1 + x/1! + x2/2! + x3/3! + … …Program :// (a) 1 + 1/2 + 1/3+ …….+ 1/nimport java.util.Scanner;

Page 40: Java Programming Lab Programs List

class Series1 {public static void main(String arg[ ]) {int n;double sum=0,i;Scanner input= new Scanner(System.in);System.out.println("enter value of n:");n=input.nextInt();for(i=1;i<=n;i++)sum=sum+(double)(1/i);System.out.println("Result:"+sum);}}Input & Output :

// (b) 1 + 1/2 + 1/ 22 + 1/ 23 + … … + 1/ 2nimport java.util.Scanner;class Series2 {public static void main(String arg[ ]) {int n;double sum=0,i;Scanner input= new Scanner(System.in);System.out.println("enter value of n:");n=input.nextInt();for(i=1;i<=n;i++)sum=sum+(double)(1/Math.pow(2,i-1));System.out.println("Result:"+sum);}}Input & Output :

// (c) ex = 1 + x/1! + x2/2! + x3/3! + … …import java.util.*;class Series3{public static void main(String arg[ ]) {int n,x;double sum=0,i,d=1;Scanner input= new Scanner(System.in);System.out.println("enter value of n:");n=input.nextInt();System.out.println("enter value of x:");x=input.nextInt();for (i=1;i<=n;i++) {sum=sum+(double)((Math.pow(x,i-1)/d));d=d*i;}System.out.println("Result :"+sum);}}Input & Output :

Page 41: Java Programming Lab Programs List

Program Statement :WAJP to do the following:(a) To output the question “Who is the inventor of Java?”(b) To accept an answer(c) To printout “GOOD” and then stop if the answer is correct(d) To output the message “TRY AGAIN”, if the answer is wrong(e) To display the correct answer, when the answer is wrong even at the thirdattemptProgram :import java.io.*;class Ask {public static void main(String a[ ])throws Exception {String str1,str2;int count=0;str1="James Gosling";BufferedReader br=new BufferedReader(newInputStreamReader(System.in));System.out.println("Who is the inventor of Java ?");while(count!=3) {str2=br.readLine();if(str1.equalsIgnoreCase(str2)) {System.out.println("!!! GOOD !!!");break;}else {if(count<2)System.out.println("TRY AGAIN !");count++;}}if(count==3)System.out.println("Correct Answer is : "+str1);}}

Program Statement :WAJP to transpose a matrix using ‘arraycopy’ command.Program :class TransMatrix {public static void main(string args[ ]) {int i,j,k=0;int rows,cols,r,c;

Page 42: Java Programming Lab Programs List

int a[ ][ ]={{1,2,3,4},{5,6,7,8}};rows=a.length;cols=a[0].length;int b[ ][ ]=new int[rows*cols];int s[ ]=new int[rows*cols];int d[ ]=new int[rows*cols];for (i=0;i<rows;i++)for (j=0;j<cols;j++,k++)s[k]=a[i][j];i=j=k=r=c=0;while(r<rows) {while(c<cols) {System.arraycopy(s,i,d,i,l);b[j++][k]=d[i++];c++;}j=c=0;k++;t++;}System.out.println("a matrix:");for (i=0;i<rows;i++) {for(j=0;j<cols;j++)System.out.print(" "+a[i][j]);System.out.println();}System.out.println("\nb matrix:");for(i=0;i<cols;i++) {for(j=0;j<rows;j++)System.out.print(" "+b[i][j]);System.out.println();}}}Input & Output :

Program Statement :Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster etc. In the baseclass provide methods that are common to all Rodents and override these in thederived classes to perform different behaviors, depending on the specific type of

Page 43: Java Programming Lab Programs List

Rodent. Create an array of Rodent, fill it with different specific types of Rodentsand call your base class methods.Program :import java.util.Random;class Rodent{void place() {}void tail() {}void eat() {}public static Rodent randRodent(){Random rr=new Random();switch (rr.nextInt(4)) {case 0: return new Mouse();case 1: return new Gerbil ();case 2: return new Hamster ();case 3: return new Beaver ();}return new Rodent();}}class Mouse extends Rodent {void place() {System.out.println(“Mice are found all over the world”);}void tail() {System.out.println(“Mice have long and hairless tail”);}void eat() {System.out.println(“Mice eat cardboards, papers,clothes”);}}class Gerbil extends Rodent {void place() {System.out.println(“Gerbils are found in arid parts ofAfrica and Asia”);}void tail() {System.out.println(“Gerbils have long tail”);}void eat() {System.out.println(“Gerbils eat seeds, roots, insects, partsof plants”);}}class Hamster extends Rodent {void place() {System.out.println(“Hamsters are found in WesternEurope to China – Dry regions only”);}void tail() {System.out.println(“Hamsters have short tail”);}void eat() {

Page 44: Java Programming Lab Programs List

System.out.println(“Hamsters eat cereals”);}}class Beaver extends Rodent {void place() {System.out.println(“Beavers are found in NorthernEurope and North America”);}void tail() {System.out.println(“Beavers have broad tail”);}void eat() {System.out.println(“Beavers eat bark”);}}public class Rodents{public static void main(String args[ ]) {Rodent r[] = new Rodent[6];for (int i=0; i<r.length; i++)r[i] = Rodent.randRodent();for (int i=0; i<r.length; i++) {r[i].place();r[i].tail();r[i].eat();}}}

Page 45: Java Programming Lab Programs List

Program Statement :WAJP to print a chessboard pattern.Program :import java.awt.*;import java.applet.*;public class ChessBoard extends Applet {/* This applet draws a red-and-black checkerboard.It is assumed that the size of the applet is 160by 160 pixels.*//* <applet code="ChessBoard.class" width=200 height=160></applet> */public void paint(Graphics g) {int row; // Row number, from 0 to 7int col; // Column number, from 0 to 7int x,y; // Top-left corner of squarefor ( row = 0; row < 8; row++ ) {for ( col = 0; col < 8; col++) {x = col * 40;y = row * 40;if ( (row % 2) == (col % 2) )g.setColor(Color.white);elseg.setColor(Color.black);g.fillRect(x, y, 40, 40);}} // end for row} // end paint()} // end class

Page 46: Java Programming Lab Programs List

VIVA VOCE QUESTIONS1) What is a method? And What is OOPS?2) What is the signature of a method?3) What is the difference between an instance variable and a classvariable?4) What is an abstract method?5) What is an abstract class?6)What is an object reference?7) What is an exception?8) Why does the compiler complain about Interrupted Exception when Itry to use Thread's sleep method?9) Why do methods have to declare the exceptions they can throw?10) What's the difference between a runtime exception and a plainexception-why don't you runtime exceptions have to be declared?11) What is an applet?12) . How do applets differ from applications?13) . Can I write Java code that works both as an applet and as a standaloneapplication?14). What is the difference between an application, an applet, and aservlet?15) Several applet methods seem special, in that I need to define themeven if my own code doesn't invoke them--what are the methods, andwhen (and by whom) are they invoked?16). Should applets have constructors?17) . How can my applet tell when a user leaves or returns to the webpage containing my applet?18) . How do I read number information from my applet's parameters, given that Applet's getParameter method returns a String?19) . When I subclass Applet, why should I put setup code in the init()method? Why not just a constructor for my class?20). Can I use an http URL to write to a file on the server from anapplet?21) . Can applets launch programs on the server?22) . Can applets launch programs on the client?23) . How do you do file I/O from an applet?24) . How do I access remote machine's file system through JavaApplet?25) What is a thread?26) . How do I create a thread and start it running?27) . How many threads can I create?28) . How does Thread's stop method work--can I restart a stoppedthread?29) . If I create a thread, and then null out the reference to it, whathappens to the thread? Does it get interrupted or what?30) . How should I stop a thread so that I can start a new thread later inits place?31) .How do I specify pause times in my program?

Page 47: Java Programming Lab Programs List

32) Why is thread synchronization important for multithreadedprograms?33) . What is a monitor?34) . How does the synchronized keyword work?35) . What objects do static synchronized methods use for locking?36) . How do the wait and notifyAll/notify methods enable cooperation between threads?

37) . How do I achieve the effect of condition variables if the Javaplatform provides me with only wait and notifyAll/notify methods?38) . How do I make one thread wait for one or more other threads tofinish?39) . What do I use the yield method for?40) . Does the Java Virtual Machine protect me against deadlocks?41) . I have several worker threads. I want my main thread to wait forany of them to complete, and take action as soon as any of themcompletes. I don't know which will complete soonest, so I can't just callThread.join on that one. How do I do it?42) How do I do keyboard (interactive) I/O in Java?43) . Is there a way to read a char from the keyboard without having totype carriage-return?44). How do I read a line of input at a time?45) . How do I read input from the user (or send output) analogous tousing standard input and standard output in C or C++?46) . Is there a standard way to read in int, long, float, and double valuesfrom a string representation?47) . How do I read a String/int/boolean/etc from the keyboard?48) . I try to use "int i = System.in.read();" to read in an int from thestandard input stream. It doesn't work. Why?49) . I use the following to read an int. It does not work. Why?50). I'm trying to read in a character from a text file using theDataInputStream's readChar() method. However, when I print it out, Iget?’s.51) . Why do I get garbage results when I use DataInputStream's readIntor readFloat methods to read in a number from an input string?52). How do I read data from a file?53) . How do I write data to a file?54). How do I append data to a file?55). When do I need to flush an output stream?56) . Why do I see no output when I run a simple process, such asr.exec("/usr/bin/ls")?57) . Can I write objects to and read objects from a file or otherstream?58) . How do I format numbers like C's printf()?59). How do I do file I/O in an applet?60) . How do I do I/O to the serial port on my computer61) . How do I do formatted I/O like printf and scanf in C/C++?62). How do I read a file containing ASCII numbers?63) . Why do I have trouble with System.out.println()?64). How do I write to the serial port on my PC using Java?65) . Is it possible to lock a file using Java ?66) . How do I make the keyboard beep in Java?67). How do I make I/O faster? My file copy program is slow.

Page 48: Java Programming Lab Programs List

68). How do I do formatted I/O of floating point numbers?69). How do I read numbers in exponential format in Java?70) . How do I delete a directory in Java? 71). How do I tell how muchdisk space is free in Java?71) . How do I get a directory listing of the root directory C:\ on a PC?72). I did a read from a Buffered stream, and I got fewer bytes than Ispecified73) . How do I redirect the System.err stream to a file?74) . What are the values for the Unicode encoding schemes?75) . How do I print from a Java program?76) . What are the properties that can be used in a PrintJob?77) . How do I get Java talking to a Microsoft Access database?78). How do I do I/O redirection in Java using exec()?79) What is the signature of a method?81) How do I create an instance of a class? 82) . Why do I get thejava.lang.UnsatisfiedLinkError when I run my Java program containingNative Method invocations?83) Given a method that doesn't declare any exceptions, can I overridethat method in a subclass to throw an exception?84) What's the difference between a runtime exception and a plainexception-why don't runtime exceptions have to be declared?85) Why do methods have to declare the exceptions they can throw?86) Why does the compiler complain about Interrupted Exception whenI try to use Thread's sleep method?87) What is an exception?88) I can't seem to change the value of an Integer object once created.89) How can I safely store particular types in general containers?90) Why is the String class final? I often want to override it.91) . How do static methods interact with inheritance?92) Where can I find examples of the use of the Java class libraries?93) How can I find the format of a .class file/any file?94) What are "class literals"?95) What is an object reference?96) What does it mean that a method or class is abstract?97) What is an abstract class?98) What is an abstract method?99) How do I create an instance of a class?100) What is an object reference?101) What are "class literals"?102) What are the values for the Unicode encoding schemes?103) How do I print from a Java program?104) How do I get a directory listing of the root directory C:\ on a PC?105) How do I delete a directory in Java?106) How do I read numbers in exponential format in Java?107) How do I do formatted I/O of floating point numbers?108) How do I make I/O faster? My file copy program is slow.109) Is it possible to lock a file using Java ?110) How do I write to the serial port on my PC using Java? .111) Why do I have trouble with System.out.println()?112) How do I read a file containing ASCII numbers?113) How do I do formatted I/O like printf and scanf in C/C++?114) How do I do I/O to the serial port on my computer?115) How do I do file I/O in an applet?

Page 49: Java Programming Lab Programs List

116) Can I write objects to and read objects from a file or other stream?117) Why do I see no output when I run a simple process, such asr.exec("/usr/bin/ls")?118) When do I need to flush an output stream?119) How do I append data to a file?120) How do I write data to a file?121) How do I read data from a file?122) Explain the Polymorphism principle.123) Why do methods have to declare the exceptions they can throw?124) Explain the different forms of Polymorphism.125) Describe the principles of OOPS126) What is the difference between encapsulation anddatahiding.explain with example127) What is the use/advantage of function overloading128) Explain the Inheritance Principle129) Can we inherit private members of class ?130) Why do you need abstraction?131) How macro execution is faster than function ?132) What is size of class having no variable & 1 function which returnsint133) Difference between object-oriented programming and procedureoriented programming134) What do you mean by realization in oops, what ispresistent,transient object.135)What is the use of procedure overriding136) What are enumerators? and what are in-line functions? giv ans witheg.137) Is it possible to change the address of an array?138) What is the race condition?139) What are the advantages of Object Oriented Modeling?

REFERENCES:BOOKS:1. Thinking in Java – Bruce Eckel2. Beginning Java 2- Ivbor horton3. Just Java 1.2- Peter van der linder4. Big Java 2-Cay Horstmann5. Introduction to java programming-Y.Daniel LiangWEBSITES:1. www.java.com2. www.java.sun.com3. www.roseindia.net4. www.javalobby.org5. www.javabeat.net

Page 50: Java Programming Lab Programs List

PROCEDURE FOR INSTALLING JAVA 1.5/1.6 VERSIONSTEP 1:_ First install the java version (1.5/1.6) Ur having..!STEP 2:_ GO TO MY COMPUTER

_ THEN go to the drive where u have installed java…For e.g.:

1. Go to c:drive

Page 51: Java Programming Lab Programs List

2. In PROGRAM FILES

3. GO TO JAVA