Program1: 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 javax.swing.JOptionPane; import java.io.*; class Solution { private int a,b,c,desc; private double r1,r2; public void solve() { desc=b*b-4*a*c; if(desc>0) { r1=(-b+Math.sqrt(desc))/(2*a); r2=(-b-Math.sqrt(desc))/(2*a); JOptionPane.showMessageDialog(null,"roots are"+r1+" "+r2,"Message",JOptionPane.INFORMATION_MESSAGE); } else if(desc==0) { r1=r2=(-b+Math.sqrt(desc))/(2*a); JOptionPane.showMessageDialog(null,"roots are"+r1+" "+r2,"Message",JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null,"there are no real solutions","Message",JOptionPane.INFORMATION_MESSAGE); } } public void input() { String n1,n2,n3; n1=JOptionPane.showInputDialog("enter a value"); n2=JOptionPane.showInputDialog("enter b value"); n3=JOptionPane.showInputDialog("enter c value"); a=Integer.parseInt(n1); b=Integer.parseInt(n2); c=Integer.parseInt(n3); } } class Quadratic { public static void main(String[] args) { Solution s=new Solution(); s.input();

s.solve(); } } Program2: 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 javax.swing.JOptionPane; import java.io.*; class Fibo { public static void main(String[] args) { int x1=1,x2=1,x3=0,n; String N=JOptionPane.showInputDialog("enter n value"); n=Integer.parseInt(N); JOptionPane.showMessageDialog(null,"n` value is"+n,"Message",JOptionPane.INFORMATION_MESSAGE); while((n-2)>0) { x3=x1+x2; x1=x2; x2=x3; n--; } JOptionPane.showMessageDialog(null,"nth value in sequence is"+x3,"Message",JOptionPane.INFORMATION_MESSAGE); } } import java.io.*; class Fibo1 { int x1=1,x2=1,x3,n=8; int sequence(int x1,int x2) { if(n==2) return 0; else { x3=x1+x2; x1=x2;x2=x3; n--; sequence(x1,x2); return x3; } } }

class Fibo { public static void main(String[] args) { Fibo1 f=new Fibo1(); int res=f.sequence(1,1); System.out.println(res); } } Program3: Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer. import javax.swing.JOptionPane; import java.io.*; class Prime1 { public static void main(String[] args) throws IOException { String N; int i,j,count=0,n; String output="prime numbers are"; N=JOptionPane.showInputDialog("enter n value"); n=Integer.parseInt(N); for(i=1;i<=n;i++) { count=0; for(j=1;j<=i;j++) { if(i%j==0) count++; } if(count==2) output=output+" "+i; } JOptionPane.showMessageDialog(null,output,"Message",JOptionPane.INFORMATION_MESSAGE); } } Program4: Write a Java program to multiply two given matrices. class matrixmul { public static void main(String[] args) { int A[][]=new int[10][10];

int B[][]=new int[10][10]; int C[][]=new int[10][10]; int i,j,k; A[0][0]=2; A[0][1]=3; A[1][0]=4; A[1][1]=5; B[0][0]=1; B[0][1]=2; B[1][0]=3; B[1][1]=4; C[0][0]=0; C[0][1]=0; C[1][0]=0; C[1][1]=0; for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { for(k=0;k<=1;k++) { C[i][j]=C[i][k]+(A[i][k]*B[k][j]); } } } for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { System.out.println(C[i][j]); } } } } Program5: 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.*; class sample { public static void main(String[] args) { int i,sum=0; String s=new String("1 2 3 4 5 6 7 8 9"); char A[]=s.toCharArray(); StringTokenizer t=new StringTokenizer(s); System.out.println(t.countTokens()); while(t.hasMoreTokens())

{ System.out.println(t.nextToken()); } for(i=0;i<s.length();i++) { if(A[i]!=' ') sum=sum+(A[i]-'0'); } System.out.println(sum); } } Program6: Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. class samplr { public static void main(String[] args) { int i,j, f=0; char a[]=args[0].toCharArray(); for(i=0,j=args[0].length()-1;i<args[0].length();i++,j--) { if(a[i]!=a[i]) { System.out.println("not palindrome\n"); f=1; break; } } if(f==0) System.out.println("palindrome\n"); } } Program7: Write a Java program for sorting a given list of names in ascending order. class ascending { public static void main(String[] args) { int i,j; string temp; for(i=0;i<4;i++) { for(j=i+1;j<5;j++) { if(args[i].compareTo(args[j])>0)

{ temp=args[i]; args[i]=args[j]; args[j]=temp; } } } for(i=0;i<5;i++) { System.out.println(args[i]); } } } Program8: Write a Java program to make frequency count of words in a given text. class sample5 { public static void main(String[] args) { String s=new String("welcome to all"); int w=1,i; char a[]=s.toCharArray(); for(i=0;i<s.length(); i++) { if(a[i]==' ' && a[i+1]!= ' ') w++; } System.out.println(w); } } Program9: 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 sample11 { public static void main(String[] args) { try { File f=new File(args[0]); System.out.println(f.exists()?"file is exist":"file is not exist"); System.out.println(f.canRead()?"file is readable":"file is not readable"); System.out.println(f.canWrite()?"file is Writable":"file is not writable"); System.out.println(f.isFile()?"it is file":"it is not a file");

System.out.println(f.isDirectory()?"it is directory":"it is not directory"); System.out.println(f.length()); } catch(Exception e) { System.out.println(e.getMessage()); System.out.println("file is not exist"); } } } Program10: 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 sample10 { public static void main(String[] args) { try { FileInputStream f=new FileInputStream(args[0]); int lno=1; char ch; System.out.print(lno++); while(f.available()>0) { ch=(char)f.read(); System.out.print(ch); if(ch=='\n') System.out.print(lno++); } f.close(); } catch(Exception e) { System.out.println("file not found\n"); } } } Program11: Write a Java program that displays the number of characters, lines and words in a text file. import java.io.*; class line { public static void main(String[] args) {

try { FileInputStream f=new FileInputStream(args[0]); int l=1,w=1,c=0; char ch; while(f.available()>0) { ch=(char)f.read(); if(ch=='\n') l++; if(ch==' '&&f.read()!=' ') { c++; w++; } c++; } f.close(); System.out.println(l); System.out.println(w); System.out.println(c); } catch(Exception e) { System.out.println("no file is found\n"); } } } Program12: Write a Java program that: i) Implements stack ADT. ii) Converts infix expression into Postfix form iii) Evaluates the postfix expression i)import java.util.*; class sample6 { public static void main (String[] args) { Stack s= new Stack(); int i; for(i=0;i<5;i++) { s.push(args[i]); } System.out.println(s); while(!s.empty()) { System.out.println(s.pop());

} } } ii) import java .util.*; class sample7 { public static void main(String[] args) { Stack s= new Stack(); int i; char a[]= args[0].toCharArray(); for(i=args[0].length()-1;i>=0; i--) { if(a[i]=='+'|| a[i]=='-'||a[i]=='*'||a[i]=='/') s.push(a[i]); } for(i=args[0].length()-1;i>=0; i--) { if(a[i]>='0' && a[i]<='9') s.push(a[i]); } while(!s.empty()) { System.out.println(s.pop()); } } } iii) import java.util.*; class sample8 { public static void main(String[] args) { Stack s=new Stack(); char a[]=args[0].toCharArray(); int i,m,n; for(i=args[0].length()-1;i>=0;i--) { if(a[i]>='0'&& a[i]<='9') s.push(a[i]); } for(i=args[0].length()-1;i>=0;i--) { if(a[i]=='+') { m=Integer.parseInt(s.pop().toString()); n=Integer.parseInt(s.pop().toString());

s.push(m+n); } else if(a[i]=='-') { m=Integer.parseInt(s.pop().toString()); n=Integer.parseInt(s.pop().toString()); s.push(m-n); } else if(a[i]=='*') { m=Integer.parseInt(s.pop().toString()); n=Integer.parseInt(s.pop().toString()); s.push(m*n); } else if(a[i]=='/') { m=Integer.parseInt(s.pop().toString()); n=Integer.parseInt(s.pop().toString()); s.push(m/n); } else System.out.println("invalid operator"); } System.out.println(s.pop()); } } Program13: Develop an applet that displays a simple message. import java.applet.*; import java.awt.*; /*<applet code="sample17" width=400 height=400> </applet>*/ public class sample17 extends Applet { public void paint(Graphics g) { g.drawString("welcome to Applets",100,200); } } Program14: 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.applet.*; import java.awt.event.*;

/*<applet code="sample19" width=800 height=800> </applet>*/ public class sample19 extends Applet implements ActionListener { TextField t, t1; int n, fact=1,i; Button b; public void init() { t=new TextField("5"); t1=new TextField(); b=new Button("compute"); add(t); add(t1); add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b) { n=Integer.parseInt(t.getText()); for(i=1;i<=n;i++) { fact=fact*i; } t1.setText(fact+" "); } } } Program15: Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result. import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="calculator" width=800 height=800> </applet>*/ public class calculator extends Applet implements ActionListener { GridLayout g; TextField t; Button b,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15; int j,k=0; String str="",Flag=""; public void init() {

g=new GridLayout(4,4); setLayout(g); t=new TextField(); b=new Button("1"); b1=new Button("2"); b2=new Button("3"); b3=new Button("+"); b4=new Button("4"); b5=new Button("5"); b6=new Button("6"); b7=new Button("-"); b8=new Button("7"); b9=new Button("8"); b10=new Button("9"); b11=new Button("*"); b12=new Button("0"); b13=new Button("c"); b14=new Button("="); b15=new Button("/"); add(t); add(b); 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); b.addActionListener(this); 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); } public void actionPerformed(ActionEvent ae) { str=ae.getActionCommand(); if(str.equals("1")) { k=(k*10)+1; t.setText(k+""); } if(str.equals("2")) { k=(k*10)+2; t.setText(k+""); } if(str.equals("3")) { k=(k*10)+3; t.setText(k+""); } if(str.equals("4")) { k=(k*10)+4; t.setText(k+""); } if(str.equals("5")) { k=(k*10)+5; t.setText(k+""); } if(str.equals("6")) { k=(k*10)+6; t.setText(k+""); } if(str.equals("7")) { k=(k*10)+7; t.setText(k+""); } if(str.equals("8")) { k=(k*10)+8; t.setText(k+""); } if(str.equals("9")) { k=(k*10)+9; t.setText(k+"");

} if(str.equals("0")) { k=(k*10)+0; t.setText(k+""); } if(str.equals("+")) { t.setText("+"); if(Flag.equals("+")) { j=j+k; } else if(Flag.equals("-")) { j=j-k; } else if(Flag.equals("*")) { j=j*k; } else if(Flag.equals("/")) { j=j/k; } else if(Flag.equals("=")) { j=j; } else { j=k; Flag="+"; } k=0; Flag="+"; } if(str.equals("-")) { t.setText("-"); if(Flag.equals("+")) { j=j+k; } else if(Flag.equals("-")) { j=j-k; } else if(Flag.equals("*")) {

j=j*k; } else if(Flag.equals("/")) { j=j/k; } else if(Flag.equals("=")) { j=j; } else { j=k; Flag="-"; } k=0; Flag="-"; } if(str.equals("*")) { t.setText("*"); if(Flag.equals("+")) { j=j+k; } else if(Flag.equals("-")) { j=j-k; } else if(Flag.equals("*")) { j=j*k; } else if(Flag.equals("/")) { j=j/k; } else if(Flag.equals("=")) { j=j; } else { j=k; Flag="*"; } k=0; Flag="*"; } if(str.equals("/"))

{ t.setText("/"); if(Flag.equals("+")) { j=j+k; } else if(Flag.equals("-")) { j=j-k; } else if(Flag.equals("*")) { j=j*k; } else if(Flag.equals("/")) { j=j/k; } else if(Flag.equals("=")) { j=j; } else { j=k; Flag="/"; } k=0; Flag="/"; } if(str.equals("c")) { k=0; j=0; Flag=""; t.setText(""); } if(str.equals("=")) { t.setText("="); if(Flag.equals("+")) { j=j+k; t.setText(j+""); } if(Flag.equals("-")) { j=j-k; t.setText(j+""); }

if(Flag.equals("*")) { j=j*k; t.setText(j+""); } if(Flag.equals("/")) { j=j/k; t.setText(j+""); } k=0; Flag="="; } repaint(); } } Program16: Write a Java program for handling mouse events import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code="sample20" width=800 height=800> </applet>*/ public class sample20 extends Applet implements MouseListener { public void init() { addMouseListener(this); } public void mouseClicked(MouseEvent me) { setBackground(Color.red); } public void mousePressed(MouseEvent me) { setBackground(Color.green); } public void mouseEntered(MouseEvent me) { setBackground(Color.blue); } public void mouseExited(MouseEvent me) { setBackground(Color.pink); } public void mouseReleased(MouseEvent me) {

setBackground(Color.yellow); } } Program17: Write a Java program that creates three threads. First thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds. class sample18 implements Runnable { try { Thread t; public sample18(String name) { t=new Thread(this,name); t.start(); } public void run() { int i; if(t.getName().compareTo("demo")==0) { for(i=1;i<=10;i++) { System.out.println("good morning:"); t.sleep(1000); } } if(t.getName().compareTo("demo1"==0) { for(i=1;i<=10;i++) { System.out.println("hello:"); t.sleep(2000); } } } } catch(Exception e) { System.out.println(e.getMessage()); } public static void main(String[] args) { try { sample18 s=new sample18("demo");

sample18 s1=new sample18("demo1"); int i; for(i=1;i<=10;i++) { System.out.println("welcome"); Thread.sleep(3000); } } catch(Exception e) System.out.println(e.getMessage()); } } } Program18: Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. class comm { int num; synchronized void produce() { num=1; System.out.println("produced data:"+num); try { wait(); } catch(Exception e) { } } synchronized void consumer() { System.out.println("consumed data:"+num); notify(); } } class sample extends Thread { comm c1; public sample(comm c,String name) { super(name); c1=c; start(); }

public void run() { c1.produce(); } } class consumer extends Thread { comm c1; public consumer(comm c,String name) { super(name); c1=c; start(); } public void run() { c1.consumer(); } public static void main(String[] args) { comm c2=new comm(); sample s=new sample(c2,"producer"); consumer c5=new consumer(c2,"consumer"); } } Program19: 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.*; /*<applet code="messagedb" width=800 height=800> </applet>*/ public class messagedb extends JApplet implements ActionListener { JTextField t1,t2,t3; JLabel l1,l2,l3; JButton b; Container c; public void init() { l1=new JLabel("Num1"); l2=new JLabel("Num2");

l3=new JLabel("result"); t1=new JTextField(10); t2=new JTextField(10); t3=new JTextField(10); b=new JButton("Divide"); c=getContentPane(); setLayout(new FlowLayout(FlowLayout.LEFT)); c.add(l1); c.add(l2); c.add(l3); c.add(t1); c.add(t2); c.add(t3); c.add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { try { String s=ae.getActionCommand(); int x,y; double z; if(s.equals("Divide")) { x=Integer.parseInt(t1.getText()); y=Integer.parseInt(t2.getText()); z=x/y; t3.setText(z+""); } } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null,e.getMessage()); } catch(ArithmeticException e) { JOptionPane.showMessageDialog(null,e.getMessage()); } } } Program20: 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 the radius of a circle, and the result produced by the server is the area of the circle. (Use java.net)

import java.net.*; import java.io.*; import java.util.*; class client { public static void main(String[] args)throws Exception { InetAddress a=InetAddress.getLocalHost(); Socket s=new Socket(a,1080); System.out.println("enter the radius\n"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(br.readLine()); BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream())); System.out.println(br1.readLine()); br1.close(); ps.close(); br.close(); s.close(); } } import java.net.*; import java.io.*; class server { public static void main(String[] args)throws Exception { ServerSocket ss=new ServerSocket(1080); Socket s=ss.accept(); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String str=br.readLine(); System.out.println(str); double r=Double.parseDouble(str); double a=3.14*r*r; PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(String.valueOf(a)); ps.close(); br.close(); s.close(); ss.close(); } } Program21: 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 javax.swing.*; import java.awt.*; import java.awt.event.*; /*<applet code="trafficlight" width=800 height=800> </applet>*/ public class trafficlight extends JApplet implements ActionListener { JRadioButton b1,b2,b3; JTextField t1,t2,t3; Container c; public void init() { c=getContentPane(); setLayout(new FlowLayout()); b1=new JRadioButton("green"); b2=new JRadioButton("yellow"); b3=new JRadioButton("red"); t1=new JTextField(10); t2=new JTextField(10); t3=new JTextField(10); add(b1); add(b2); add(b3); add(t1); add(t2); add(t3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str=ae.getActionCommand(); if(str.equals("green")) { t1.setBackground(Color.green); t2.setBackground(Color.white); t3.setBackground(Color.white); } if(str.equals("yellow")) { t1.setBackground(Color.white); t2.setBackground(Color.yellow); t3.setBackground(Color.white); } if(str.equals("red")) { t1.setBackground(Color.white); t2.setBackground(Color.white); t3.setBackground(Color.red);

} } }

Program22: Write a Java program that allows the user to draw lines, rectangles and ovals import java.applet.*; import java.awt.*; /*<applet code="sample18" width=400 height=400> </applet>*/ public class sample18 extends Applet { public void paint(Graphics g) { g.drawLine(100,100,200,100); g.drawRect(100,200,10,10); g.drawOval(100,300,10,10); } } Program23: 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 shows the number of sides in the given geometrical figures. import javax.swing.*; import java.awt.*; import java.awt.event.*; /*<applet code="geometrical" width=800 height=800> </applet>*/ abstract class shape { double n; public abstract double numberOfSides(); } class Trapezoid extends shape { public double numberOfSides() { n=4.000000; return(n); } } class Triangle extends shape { public double numberOfSides()

{ n=3.000000; return(n); } } class Hexagon extends shape { public double numberOfSides() { n=6.000000; return(n); } } public class geometrical extends JApplet { public void init() { Trapezoid tp=new Trapezoid(); Triangle t=new Triangle(); Hexagon h=new Hexagon(); JOptionPane.showMessageDialog(null,"no of sides in Trapezoid="+tp.numberOfSides()); JOptionPane.showMessageDialog(null,"no of sides in Triangle="+ t.numberOfSides()); JOptionPane.showMessageDialog(null, "no of sides in Hexagon="+ h.numberOfSides()); } } Program24: 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 25eparated by commas. Write a java program to display the table using Jtable component import javax.swing.*; import java.util.*; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; import javax.swing.table.*; class DataFileTableModel extends AbstractTableModel { String datafile,aLine; Vector colNames,dataNames; public DataFileTableModel(String f) { datafile=f; initVectors(); } public void initVectors() {

try { FileInputStream fis=new FileInputStream(datafile); BufferedReader br=new BufferedReader(new InputStreamReader(fis)); StringTokenizer st=new StringTokenizer(br.readLine(),","); colNames=new Vector(); dataNames=new Vector(); while(st.hasMoreTokens()) { colNames.addElement(st.nextToken()); } while((aLine=br.readLine())!=null) { StringTokenizer st1=new StringTokenizer(aLine,","); while(st1.hasMoreTokens()) { dataNames.addElement(st1.nextToken()); } } } catch(Exception e) { } } public int getColumnCount() { return colNames.size(); } public int getRowCount() { return dataNames.size()/getColumnCount(); } public String getColumnName(int columnindex) { String column=""; if(columnindex<=getColumnCount()) column=(String)colNames.elementAt(columnindex); return column; } public String getValueAt(int rowindex,int columnindex) { String rowName=""; rowName=(String)dataNames.elementAt((rowindex*getColumnCount())+columnindex); return rowName; } } public class DataTableModel extends JApplet { JTable t; Container c; public void init()

{ Font f=new Font("sanserif",Font.PLAIN,24); setFont(f); setLayout(new FlowLayout()); c=getContentPane(); DataFileTableModel model =new DataFileTableModel("c:/program Files/java/jdk1.5.0/bin/Table.txt"); t=new JTable(); t.setModel(model); t.createDefaultColumnsFromModel(); JScrollPane sp= new JScrollPane(t); c.add(sp); } } /*<applet code="DataTableModel" width=800 height=800> </applet>*/

Sign up to vote on this title
UsefulNot useful