Upcoming SlideShare
×

# Java Simple Programs

3,411
-1

Published on

These Java Programs will help to understand the java programming.

1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total Views
3,411
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
495
0
Likes
1
Embeds 0
No embeds

No notes for slide

### Java Simple Programs

1. 1. Date: 16-12-2008Week-1a)Aim: Write a java program that print all roots of equation of quadratic a,b,c will be suppliedthrough keyboardCode:import java.lang.*;import java.math.*;class Quad{ public static void main(String arg[]) { int a,b,c; a=Integer.parseInt(arg[0]); b=Integer.parseInt(arg[1]); c=Integer.parseInt(arg[2]); int delta=(b*b)-(4*a*c); if(delta<0) { System.out.println("roots are imaginary,no real values"); } else { double x1=(-b+Math.sqrt(delta))/(2*a); double x2=(-b-Math.sqrt(delta))/(2*a); System.out.println(x1+" "+x2); } } }Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
2. 2. Week-1b)Aim: Write a java program that uses both recursive and non recursive functions to print thenth value in Fibonacci series.Code:import java.lang.*;class Fibo{ public static void main(String arg[ ]) { int f,f1=0,f2=1,n; n=Integer.parseInt(arg [0]); System.out.println(f1); System.out.println(f2); for(int i=0;i<n-1;i++) { f=f1+f2; f1=f2; f2=f; System.out.println(f); } System.out.println("Fibonacci series using recursion"); for(int i=0;i<n;i++) System.out.println(fib(i));} static int fib(int n) { if(n==0||n==1) return 1; else return fib(n-1)+fib(n-2); }} WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
3. 3. Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
4. 4. Date: 23-12-2008Week-2a)Aim: Write a java program that prompts the user for an integer and then prints out allprime numbers upto the integer.Code:import java.lang.*;class Prime{ public static void main(String arg[]) { int n,c,i,j; n=Integer.parseInt(arg[0]); System.out.println("prime numbers are"); for(i=1;i<=n;i++) { c=0; for(j=1;j<=i;j++) { if(i%j==0) c++; } if(c==2) System.out.println(" "+i); } }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
5. 5. Week-2b)Aim: Write a java program to multiply two given matrices.Code:import java.lang.*;import java.io.*;class Matrix{ public static void main(String arg[])throws IOException { DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter The Row Size Of The First Matrix"); int r1=Integer.parseInt(dis.readLine()); System.out.println("Enter The Column Size Of The First Matrix"); int c1=Integer.parseInt(dis.readLine()); System.out.println("Enter The Row Size Of The Second Matrix"); int r2=Integer.parseInt(dis.readLine()); System.out.println("Enter The Column Size Of The Second Matrix"); int c2=Integer.parseInt(dis.readLine()); int a[][]=new int[r1][c1]; int b[][]=new int[r2][c2]; int c[][]=new int[r1][c2]; int i,j,k; System.out.println("Enter The Elements Into The First Matrix"); for(i=0;i<r1;i++) for(j=0;j<c1;j++) { a[i][j]=Integer.parseInt(dis.readLine()); } System.out.println("Enter The Elements Into The Second Matrix"); for(i=0;i<r2;i++) for(j=0;j<c2;j++) { b[i][j]=Integer.parseInt(dis.readLine()); } if(c1!=r2) System.out.println("Multiplication Is Not Possible"); else { for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { c[i][j]=0; for(k=0;k<r2;k++) { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
6. 6. c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } } for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { System.out.println(c[i][j]+" "); } System.out.println(" "); } } }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
7. 7. Week-2c)Aim: Write a program that display each integer and sum of all integers using stringtokenizer.Code:import java.util.*;class Stringtoken{ public static void main(String arg[]) { int sum=0; StringTokenizer sto=new StringTokenizer(arg[0],":"); System.out.println(sto.countTokens()); while(sto.hasMoreTokens()) { int a=Integer.parseInt(sto.nextToken()); sum=sum+a; System.out.println(a); } System.out.println("sum= "+sum); }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
8. 8. Date: 30-12-2008Week-3a)Aim: Write a java program that checks whether a given string is a palindrome ornot.Ex:MADAMCode:import java.lang.*;import java.io.*;import java.util.*;class Palindrome{ public static void main(String arg[ ]) throws IOException { DataInputStream dis=new DataInputStream(System.in); String word=dis.readLine( ); int flag=1; int left=0; int right=word.length( )-1; while(left<right) { if(word.charAt(left)!=word.charAt(right)) { flag=0; //break; } left++; right--;} if(flag==1) System.out.println("palindrome"); else System.out.println("not palindrome"); }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
9. 9. Week-3b)Aim:Write a java program for sorting a given list of name in ascending order.Code:import java.lang.*;import java.io.*;import java.util.*;class Sort{ public static void main(String arg[ ]) throws IOException { DataInputStream dis=new DataInputStream(System.in); System.out.println("enter the size"); int n=Integer.parseInt(dis.readLine()); String array[ ]=new String[n]; System.out.println("enter names"); for(int i=0;i<n;i++) { array[i]=dis.readLine(); } for(int i=0;i<n;i++) { for(int j=0;j<n-1;j++) { if(array[j].compareTo(array[j+i])>0) { String temp=array[j]; array [j]=array[j+1]; array[j+1]=temp; } } } System.out.println("the sorted strings are"); for(int i=0;i<n;i++) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
10. 10. System.out.println(array[i]); }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
11. 11. Week-3c)Aim: Write a java program to make frequency count of words in a given text.Code:import java.util.*;import java.lang.*;import java.io.*;class Fre{ public static void main(String[ ] args) throws IOException { DataInputStream dis=new DataInputStream(System.in); String str=dis.readLine(); String temp; StringTokenizer st=new StringTokenizer(str); int n=st.countTokens( ); String a[ ]=new String[n]; int i=0,count=0; while(st.hasMoreTokens()) { a[i]=st.nextToken(); i++; } for(int x=1;x<n;x++) { for(int y=0;y<n-x;y++) { if(a[y].compareTo(a[y+1])>0) { temp=a[y]; a[y]=a[y+1]; a[y+1]=temp; } } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
12. 12. } System.out.println("the sorted string are:"); for(i=0;i<n;i++) { System.out.println(a[i]+" "); } System.out.println(); for(i=0;i<n;i++) {count=1; if(i<n-1) { while(a[i].compareTo(a[i+1])==0) { count++; i++; if(i>=n-1) { System.out.println(a[i]+" "+count); System.exit(0); } } } System.out.println(a[i]+" "+count); } }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
13. 13. Date: 06-01-2009Week-4a)Aim: Write a java program that reads a filename from user then displays information fromuser then displays information about whether the file exists,whether file is readable,whether file is writable the type of file and length of file in bytes.Code:import java.lang.*;import java.io.*;import java.util.*;class FileOp{ public static void main(String arg[ ])throws IOException { File f=new File("Z:/week 3/Palindrome.java"); System.out.println(f.getName()); System.out.println(f.getPath()); System.out.println(f.getName()); System.out.println(f.canRead()?"Readable":"Not Readable"); System.out.println(f.exists()?"Exist":"Non Exist"); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
14. 14. System.out.println(f.canWrite()?" " :" "); System.out.println(f.length()+"bytes"); }}Output:Week-4b)Aim: Write a java program that reads a file and displays the file on the screen with a linenumber before each line.Code:import java.util.*;import java.io.*;import java.lang.*;class FileNo{ public static void main(String arg[ ])throws IOException { int linenum=0; String line; try{ File f=new File("Z:/f.txt "); if(f.exists()) { Scanner infile=new Scanner(f); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
15. 15. while(infile.hasNext()) { line=infile.nextLine(); System.out.println(++linenum+" "+line); } infile.close(); } } catch(Exception e) { System.out.println(e); } }}Output:Week-4c)Aim: Write a java program that displays the number of characters,lines and words in atextfileimport java.lang.*;import java.io.*;class FileCount{ public static void main(String arg[]) { int ccount=0,lcount=0,wcount=0; try { FileInputStream f=new FileInputStream("Z:/week 3/Palindrome.java"); int i; do{ i=f.read(); if(i!=-1) { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
16. 16. ccount++; if(i==n) lcount++; if((char)i== ||(char)i==n) wcount++; } }while(i!=-1); f.close(); System.out.println("line count is "+lcount); System.out.println("Character count is "+ccount); System.out.println("word count is "+wcount); } catch(Exception e) { System.out.println(e); } }}Output:Date:03-02-2009Week-5a)i)Aim: Write a java program that Implements stack ADT.Code:import java.lang.*;import java.io.*;import java.util.*;interface Mystack{ int n=10; public void pop(); public void push(); public void peek(); public void display();}class Stackimp implements Mystack{ WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
17. 17. int stack[]=new int[n]; int top=-1; public void push() { try{ DataInputStream dis=new DataInputStream(System.in); if(top==(n-1)) { System.out.println("overflow"); return; } else { System.out.println("enter element"); int ele=Integer.parseInt(dis.readLine()); stack[++top]=ele; } } catch(Exception e) { System.out.println("e"); } } public void pop() { if(top<0) { System.out.println("underflow"); return; } else { int popper=stack[top]; top--; System.out.println("popped element" +popper); } } public void peek(){ if(top<0) { System.out.println("underflow"); return: } else { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
18. 18. int popper=stack[top]; System.out.println("popped element" +popper); } } public void display() { if(top<0) { System.out.println("empty"); return; } else { String str=" "; for(int i=0;i<=top;i++) str=str+" "+stack[i]; System.out.println("elements are"+str); } } }class Stackadt{ public static void main(String arg[])throws IOException { DataInputStream dis=new DataInputStream(System.in); Stackimp stk=new Stackimp(); int ch=0; do{ System.out.println("enter ur choice for 1.push 2.pop 3.peek 4.peek 5.display”); ch=Integer.parseInt(dis.readLine()); switch(ch){ case 1:stk.push(); break; case 2:stk.pop(); break; case 3:stk.peek(); break; case 4:stk.display(); break; case 5:System.exit(0); } }while(ch<=5); }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
19. 19. Week-5a)ii)Aim: Write a java program that evaluates the postfix expressionCode:import java.lang.*;import java.io.*;import java.util.*;class IntoPo{ public static void main(String arg[])throws IOException { Stack stk=new Stack(); DataInputStream dis=new DataInputStream(System.in); char input; String output=" "; System.out.println("enter expresion"); String exp=dis.readLine(); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
20. 20. for(int pos=0;pos<exp.length();pos++) { input=exp.charAt(pos); switch(input) { case + : case - : case * : case / : stk.push(input); break; case ) : char ch=((Character)stk.pop()); output=output+ch; break; case ( : break; default : output=output+input; break; } } System.out.println("result is"+output); }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
21. 21. .Week-5a)iii)Aim:Write a java program that evaluates the postfix expression WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
22. 22. import java.lang.*;import java.io.*;import java.util.*;class Evaluation{ static int dooperation(int fo,int so,char op) { int val=0; switch(op){ case + : val=fo+so; break; case - : val=fo-so; break; case * : val=fo*so; break; case / : val=fo/so; break; } return val; } public static void main(String arg[])throws IOException { Stack stk=new Stack(); DataInputStream dis=new DataInputStream(System.in); String str=dis.readLine(); char ch; for(int pos=0;pos<str.length();pos++) { ch=str.charAt(pos); switch(ch){ case 0 : case 1 : case 2 : case 3 : case 4 : case 5 : case 6 : case 7 : case 8 : case 9 : stk.push(new Integer((Character.digit(ch,10)))); break; case +: case -: case /: case *: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
23. 23. int fo=((Integer)stk.pop()).intValue(); int so=((Integer)stk.pop()).intValue(); int result=dooperation(fo,so,ch); stk.push(new Integer(result)); break; } } System.out.println("result is" +stk.pop()); }}Date: 10-02-2009Week-6a)Aim:Develop an applet that receives an integer in one text field, and computes as factorialvalue and returns it in another text field,when the button named “Compute” is clicked WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
24. 24. import java.io.*;import java.awt.*;import java.applet.Applet;/*<applet code="appletTest.class" height=100 width=500></applet>*/public class appletTest extends Applet{ public void paint(Graphics g) { g.drawString("This is IT IInd Year IInd sem",50,60); setForeground(Color.blue); }}Output:Week-6b)Aim:Develop an applet that displays a simple messageCode: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
25. 25. import java.awt.*;import java.awt.event.*;import java.applet.Applet;/*<applet code="AddEvent.class" height=100 width=500></applet>*/public class AddEvent extends Applet implements ActionListener{ TextField tf1; TextField tf2; Button b; Label l; public void init() { l=new Label("Enter the number & press the button"); tf1=new TextField("",5); tf2=new TextField("",10); b=new Button("press me"); add(l); add(tf1); add(tf2); add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str=ae.getActionCommand(); String str1; int fact=1; if(str=="press me") { int n=Integer.parseInt(tf1.getText()); for(int i=1;i<=n;i++) fact=fact*i; str1=""+fact; tf2.setText(str1); } }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
26. 26. Date: 24-02-2009Week-7) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
27. 27. Aim: Write a java program that works as a simple calculator.Use a grid layout to arrangebuttons for the digits +,-,*,/,% operations.Adda text field to display the result.import java.awt.*;import java.applet.*;import java.awt.event.*;public class Calculator extends Applet implements ActionListener{ TextField t1; String a="",b; String oper="",s="",p=""; int first=0,second=0,result=0; Panel p1; Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9; Button add,sub,mul,div,mod,res,space; public void init() { Panel p2,p3; p1=new Panel(); p2=new Panel(); p3=new Panel(); t1=new TextField(a,20); p1.setLayout(new BorderLayout()); p2.add(t1); b0=new Button("0"); b1=new Button("1"); b2=new Button("2"); b3=new Button("3"); b4=new Button("4"); b5=new Button("5"); b6=new Button("6"); b7=new Button("7"); b8=new Button("8"); b9=new Button("9"); add=new Button("+"); sub=new Button("-"); mul=new Button("*"); div=new Button("/"); mod=new Button("%"); res=new Button("="); space=new Button("c"); p3.setLayout(new GridLayout(4,4)); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
29. 29. } if(a=="=") { if(oper=="+") result=first+Integer.parseInt(t1.getText()); if(oper=="-") result=first-Integer.parseInt(t1.getText()); if(oper=="*") result=first*Integer.parseInt(t1.getText()); if(oper=="/") result=first/Integer.parseInt(t1.getText()); if(oper=="%") result=first%Integer.parseInt(t1.getText()); t1.setText(result+""); } if(a=="c") t1.setText(""); }}/*<applet code=Calculator width=200 height=200></applet>*/Output:Date: 10-02-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
30. 30. Week-8Aim: Write a java program for handling mouse events.Code:import java.io.*;import java.applet.Applet;import java.awt.*;import java.awt.event.*;/*<applet code=Mouse height=400 width=400></applet>*/public class Mouse extends Applet implements MouseListener,MouseMotionListener{ String txt=""; int x=10,y=30; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { txt="Mouse Clicked"; setForeground(Color.pink); repaint(); } public void mouseEntered(MouseEvent me) { txt="Mouse Entered"; repaint(); } public void mouseExited(MouseEvent me) { txt="Mouse Exited"; setForeground(Color.blue); repaint(); } public void mousePressed(MouseEvent me) { txt="Mouse Pressed"; setForeground(Color.blue); repaint(); } public void mouseMoved(MouseEvent me) { txt="Mouse Moved"; setForeground(Color.red); repaint(); } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
31. 31. public void mouseDragged(MouseEvent me) { txt="Mouse Dragged"; setForeground(Color.green); repaint(); } public void mouseReleased(MouseEvent me) { txt="Mouse Released"; setForeground(Color.yellow); repaint(); } public void paint(Graphics g) { g.drawString(txt,30,40); showStatus("Mouse events Handling"); }}Output:Date: 24-02-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
32. 32. Week-9a)Aim: 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 threaddisplays “Welcome” every three seconds.Code:class Frst implements Runnable{ Thread t; Frst() { t=new Thread(this); System.out.println("Good Morning"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("Good Morning"+i); try{ t.sleep(1000); } catch(Exception e) { System.out.println(e); } } }}class sec implements Runnable{ Thread t; sec() { t=new Thread(this); System.out.println("hello"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("hello"+i); try{ t.sleep(2000); } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
33. 33. catch(Exception e) { System.out.println(e); } } }}class third implements Runnable{ Thread t; third() { t=new Thread(this); System.out.println("welcome"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("welcome"+i); try{ t.sleep(3000); } catch(Exception e) { System.out.println(e); } } }}public class Multithread{ public static void main(String arg[]) { new Frst(); new sec(); new third(); }} WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
34. 34. Output:Week-9b) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
35. 35. Aim: Write a java program that correctly implements producer consumer problem using theconcept of inter thread communication.Code:import java.lang.*;import java.lang.Thread;class Q{ int n; boolean valueSet=false; synchronized int get() { if(!valueSet) try{ wait(); } catch(InterruptedException e) { System.out.println("InterruptedException catch"); } System.out.println("got:"+n); valueSet=false; notify(); return n; } synchronized void put(int n) { if(valueSet) try{ wait(); } catch(InterruptedException e) { System.out.println("InterruptedException catch"); } this.n=n; valueSet=true; System.out.println("put:"+n); notify(); }}class Producer implements Runnable{ Q q; Producer(Q q) { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
36. 36. 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; Consumer(Q q) { this.q=q; new Thread(this,"consumer").start(); } public void run() { while(true) { q.get(); } }}class PCFixed{ public static void main(String args[]) { Q q=new Q(); new Producer(q); new Consumer(q); }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
37. 37. Date: 03-03-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
38. 38. Week-10 )Aim: Write a program that creates a user interface to perform integer divisions.The userenters two numbers int the textfields,Num1 and Num2.The divison of Num1 and Num2 isdisplayed in the Result field when the Divide button is clicked.If Num1 or Num2 were not aninteger,the program would throw a NumberFormatException.If Num2 were Zero,the programwould throw an ArithmeticException Display the exception in a message dialog box.Code:import java.awt.*;import java.awt.event.*;import java.applet.Applet;import javax.swing.*;/*<applet code="AddEvent.class" height=100 width=500></applet>*/public class AddEvent extends Applet implements ActionListener{ TextField tf1; TextField tf2; Button b; TextField tf3; Label l; public void init() { l=new Label("enter the numbers and press divide button"); tf1=new TextField("",5); tf2=new TextField("",5); tf3=new TextField("",5); b=new Button("Divide"); add(l); add(tf1); add(tf2); add(b); add(tf3); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand()=="Divide") { try{ int n1=Integer.parseInt(tf1.getText()); int n2=Integer.parseInt(tf2.getText()); int n=n1/n2; tf3.setText(""+n); } catch(ArithmeticException e1) { JOptionPane.showMessageDialog(null,"Arthimetic Exception"); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
39. 39. } catch(NumberFormatException e2) { JOptionPane.showMessageDialog(null,"NumberFormatException"); } } }}Output:Date: 03-03-2009Week-11) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
40. 40. Aim: Write a java program that implements a simple client/server application. The clientsends a data to a server. The server receives the data uses it to produce a result, and thensends the result 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 the server isthe area of the circle,(Use java.net)Code:import java.io.*;import java.net.*;class Client{ public static void main(String ar[])throws Exception { Socket s=new Socket(InetAddress.getLocalHost(),10000); System.out.println("enter the radius of the circle "); DataInputStream dis=new DataInputStream(System.in); int n=Integer.parseInt(dis.readLine()); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(n); DataInputStream dis1=new DataInputStream(s.getInputStream()); System.out.println("area of the circle from server:"+dis1.readLine()); }}import java.io.*;import java.net.*;class Server{ public static void main(String ar[])throws Exception { ServerSocket ss=new ServerSocket(10000); Socket s=ss.accept(); DataInputStream dis=new DataInputStream(s.getInputStream()); int n=Integer.parseInt(dis.readLine()); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(3.14*n*n); }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
41. 41. Date: 10-03-2009Week-12a) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
42. 42. Aim: Write a java program that stimulates a traffic light. The program lets the user selectone of three lights: red, yellow, or green. When a radio button is selected, the light isturned on, and only one light can be on at a time No light is on when the program starts.Code:import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="CBGroup" width=250 height=200></applet>*/public class CBGroup extends Applet implements ItemListener{ String msg=""; Checkbox Red,Green,Yellow; CheckboxGroup cbg; public void init() { cbg=new CheckboxGroup(); Red=new Checkbox("RED",cbg,false); Green=new Checkbox("GREEN",cbg,false); Yellow=new Checkbox("YELLOW",cbg,false); add(Red); add(Yellow); add(Green); Red.addItemListener(this); Green.addItemListener(this); Yellow.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { //g.drawOval(10,10,50,50); if(cbg.getSelectedCheckbox().getLabel()=="RED") { g.setColor(Color.red); g.fillOval(10,10,50,50); } if(cbg.getSelectedCheckbox().getLabel()=="YELLOW") { g.setColor(Color.yellow); g.fillOval(10,10,50,50); } if(cbg.getSelectedCheckbox().getLabel()=="GREEN") { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
43. 43. g.setColor(Color.green); g.fillOval(10,10,50,50); } }}Output:Week-12b) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
44. 44. Aim: Write a java program that allows the user to draw lines,rectangles and ovals.Code:import java.awt.*;import java.applet.*;public class Draw extends Applet{ public void paint(Graphics g) { g.setColor(Color.BLUE); g.drawLine(3,4,10,23); g.drawOval(195,100,90,55); g.drawRect(100,40,90,5); g.drawRoundRect(140,30,90,90,60,30); }}/*<applet code="Draw.class" width=300 height=300></applet>*/Output:Date: 17-03-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
45. 45. Week-13a)Aim: Write a java program to create an abstract class named Shape that contains an emptymethod name numberOfSides().Provide three classes named Trapezoid,Traingle and Hexagonsuch that each of the classes extends the class Shape. Each one of the classes contains onlythe method numberOfSides() that shows the number of sides in the given geometricalfigures.Code:import java.lang.*;abstract class Shape{ abstract void numberOfSides();}class Traingle extends Shape{ public void numberOfSides() { System.out.println("three"); }}class Trapezoid extends Shape{ public void numberOfSides() { System.out.println("four"); }}class Hexagon extends Shape{ public void numberOfSides() { System.out.println("six"); }}public class Sides{ public static void main(String arg[]) { Traingle T=new Traingle(); Trapezoid Ta=new Trapezoid(); Hexagon H=new Hexagon(); T.numberOfSides(); Ta.numberOfSides(); H.numberOfSides(); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
46. 46. Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
47. 47. Week-13b)Aim: Suppose that a table named Table.txt is stored in a text file. The first line in the file isthe header, and the remaining lines corresponding to rows in the table. The elements areseparated by commas. Write a java program to display the tabe using JTable Component.Code:import javax.swing.*;import java.awt.*;import java.io.*;import java.util.*;public class JTableEx extends JPanel{ public JTableEx() { super(new GridLayout(1, 0)); File file = new File("I:/Table.txt"); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; String initData[] = new String[100]; String[] columnNames = null; Object[][] data = null; int rows = 0; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while (dis.available() != 0) { initData[rows++] = dis.readLine(); } StringTokenizer st = new StringTokenizer(initData[0],","); columnNames = new String[st.countTokens()]; data = new Object[rows - 1][st.countTokens()]; for (int i = 0; i < rows; i++) { if (i != 0) { int k = 0; StringTokenizer st1 = new StringTokenizer(initData[i],","); while (st1.hasMoreTokens()) { data[i - 1][k++] = st1.nextToken(); } } else WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
48. 48. { int j = 0; while (st.hasMoreTokens()) { columnNames[j++] = st.nextToken(); } } } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } final JTable table = new JTable(data, columnNames); table.setPreferredScrollableViewportSize(new Dimension(500, 100)); //table.setFillsViewportHeight(true); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane);}private static void createAndShowGUI(){ JFrame frame = new JFrame("SimpleTableDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTableEx newContentPane = new JTableEx(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true);}public static void main(String[] args){ javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
49. 49. }}Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR