0% found this document useful (0 votes)
191 views13 pages

Java Lab

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 13

JAVA LAB PROGRAM - 1 // W.P.

For Read two values from keyboard and calculate sum of those 2 numbers import java.lang.*; import java.io.*; class add { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter first number"); int a=Integer.parseInt(br.readLine()); System.out.println("enter second number"); int b=Integer.parseInt(br.readLine()); int c = a+b; System.out.println("Addition = " + c); } } PROGRAM - 2 // W.P. For Read name from keyboard and print the name import java.io.*; public class name { public static void main (String[] args) { System.out.print("Enter your name and press Enter: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String name = null; try { name = br.readLine(); } catch (IOException e) { System.out.println("Error!"); System.exit(1); } System.out.println("Your name is " + name); } } PROGRAM - 3 // W.P. For print a statement using Command line arguments public class cmdln 1

{ public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args[0]); System.out.println(". How are you?"); } } Exe: java cmdln monika Out put: Hi, monika. How are you? PROGRAM - 4 // W.P. For finding given year is leap year or not using Command line arguments public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; isLeapYear = (year % 4 == 0);// divisible by 4 isLeapYear = isLeapYear && (year % 100 != 0); // divisible by 4 and not 100 isLeapYear = isLeapYear || (year % 400 == 0); // divisible by 4 and not 100 unless divisible by 400 System.out.println(isLeapYear); } } Exe: 1. java LeapYear 2004 true 2. java LeapYear 1900 false 3. java LeapYear 2000 true PROGRAM - 5 // W.P. For generating random number using Command line arguments public class RandomInt { public static void main(String[] args) { int N = Integer.parseInt(args[0]); // a pseudo-random real between 0.0 and 1.0 double r = Math.random(); 2

// a pseudo-random integer between 0 and N-1 int n = (int) (r * N); System.out.println("Your random integer is: " + n); } } Exe: java RandomInt 6 Your random integer is: 5 java RandomInt 6 Your random integer is: 0 java RandomInt 1000 Your random integer is: 129

Examples:System.out.println(2 + "bc"); prints: 2bc System.out.println(2 + 3 + "bc"); prints: 5bc System.out.println((2+3) + "bc"); prints: 5bc System.out.println("bc" + (2+3)); prints: bc5 System.out.println("bc" + 2 + 3); prints: bc23 PROGRAM - 6 // W.P for swapping of two values import java.lang.*; import java.io.*; class swap { int a,b; void set(int x,int y) { a=x; b=y; } void interchange() { int t=a; a=b; b=t; } void disp() { System.out.println("Value of a="+a); System.out.println("Value of b="+b); } } class swapdemo { 3

public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter two numbers: "); int x=Integer.parseInt(br.readLine()); int y=Integer.parseInt(br.readLine()); System.out.println("Original Values: "); System.out.println("Value of a="+x); System.out.println("Value of b="+y); swap s=new swap(); s.set(x,y); System.out.println("After swapping Values: "); s.interchange(); s.disp(); } } PROGRAM - 7 // W.P for print a ruler formate public class Ruler { public static void main(String[] args) { String ruler1 = " 1 "; String ruler2 = ruler1 + "2" + ruler1; String ruler3 = ruler2 + "3" + ruler2; String ruler4 = ruler3 + "4" + ruler3; String ruler5 = ruler4 + "5" + ruler4; System.out.println(ruler1); System.out.println(ruler2); System.out.println(ruler3); System.out.println(ruler4); System.out.println(ruler5); } } Compilation: javac Ruler.java Exe: java Ruler 1 121 1213121 121312141213121 1213121412131215121312141213121 PROGRAM - 8 //W.P for calculate the Square root for given value public class Sqrt 4

{ public static void main(String[] args) { // read in the command-line argument double c = Double.parseDouble(args[0]); double epsilon = 1e-15; // relative error tolerance double t = c; // estimate of the square root of c // repeatedly apply Newton update step until desired precision is achieved while (Math.abs(t - c/t) > epsilon*t) { t = (c/t + t) / 2.0; } System.out.println(t); // print out the estimate of the square root of c } } PROGRAM - 9 //W.P for print ten hellos public class TenHellos { public static void main(String[] args) { // print out special cases whose ordinal doesn't end in th System.out.println("1st Hello"); System.out.println("2nd Hello"); System.out.println("3rd Hello"); // count from i = 4 to 10 int i = 4; while (i <= 10) { System.out.println(i + "th Hello"); i = i + 1; } } } Exe: java TenHellos 1st Hello 2nd Hello 3rd Hello 4th Hello 5th Hello 6th Hello 7th Hello 8th Hello 9th Hello 10th Hello PROGRAM - 10 //W.P for print given values with DivisorPattern as a * mark 5

public class DivisorPattern { public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (i % j == 0 || j % i == 0) { System.out.print("* "); } else { System.out.print(" "); } } System.out.println(i); } } } Exe: java DivisorPattern 10 ********************1 ** * * * * * * * * *2 * * * * * * * 3 ** * * * * *4 * * * * *5 *** * * * 6 * * * 7 ** * * * 8 * * * * 9 ** * * * 10 write a java program to implement stack using adt import java.io.*; //stack capable to store 4 elements class Stack { int max,top; int no[]; public Stack() { no=new int[5]; top=-1; max=5; 6

} public void push(int n) { if(top<max-1) { no[++top]=n; } else System.out.println("Stack full.."); } public int pop() { int val; if(top==-1) { System.out.println("Stack is Empty..."); return -1; } else { val=no[top--]; } return val; } public void print() { System.out.println("Stack elements are.."); for(int i=0;i<top;i++) System.out.println(no[i]); } } class StackTest { public static void main(String arg[]) throws IOException { Stack s=new Stack(); s.push(11); s.push(12); s.push(13); s.push(14); s.push(15); s.push(16); s.print(); System.out.println("Pop ival="+s.pop()); s.print(); System.out.println("Pop ival="+s.pop()); s.print(); } } 7

Changing the Cursor in Java import java.awt.*; import java.awt.event.*; public class ChangeCursor { public static void main(String[] args) { Frame f = new Frame("Change cursor"); Panel panel = new Panel(); Button comp1 = new Button("Ok"); Button comp2 = new Button("Cancel"); panel.add(comp1); panel.add(comp2); f.add(panel,BorderLayout.CENTER); f.setSize(200,200); f.setVisible(true); Cursor cur = comp1.getCursor(); Cursor cur1 = comp2.getCursor(); comp1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); comp2.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } Button Pressed Event import java.awt.*; import java.awt.event.*; public class bp { public static void main(String[] args) { Button b; ActionListener a = new MyActionListener(); Frame f = new Frame("Java Applet"); f.add(b = new Button("Bonjour"), BorderLayout.NORTH); b.setActionCommand("Good Morning"); b.addActionListener(a); f.add(b = new Button("Good Day"), BorderLayout.CENTER); b.addActionListener(a); f.add(b = new Button("ABCD"), BorderLayout.SOUTH); b.setActionCommand("Exit"); 8

b.addActionListener(a); f.pack(); f.show(); } } class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent ae) { String s = ae.getActionCommand(); if (s.equals("Exit")) { System.exit(0); } else if (s.equals("Bonjour")) { System.out.println("Good Morning"); } else { System.out.println(s + " clicked"); } } } Reading a File //import io package// import java.io.*; class fileread { public static void main(String args[]) throws IOException { int ch,ctr=1;String fname; DataInputStream in=new DataInputStream(System.in); System.out.print("Enter a file name?"); fname=in.readLine(); //opening file FileInputStream f=new FileInputStream(fname); System.out.print(ctr+" "); while((ch=f.read())!=-1) { System.out.print((char)ch); if(ch=='\n') { ctr++; System.out.print(ctr+" "); } } } } 9

Sorting a list of names in ascending or descending order import java.io.*; class strsort { public static void main(String arg[]) throws IOException { int i,j,len; String s[]=new String[5],swp; DataInputStream in=new DataInputStream(System.in); System.out.println("Enter 5 strings ? "); for(i=0;i<=4;i++) s[i]=in.readLine(); for(i=0;i<=3;i++) { for(j=i+1;j<=4;j++) if(s[i].compareTo(s[j])>0) { swp=s[i];s[i]=s[j]; s[j]=swp; } } System.out.println("After sort...."); for(i=0;i<=4;i++) System.out.println(s[i]); } } Write a java program to count frequency of words import java.io.*; import java.util.*; class wordcount { public static void main(String arg[]) throws IOException { int ctr=0; String s,s1,s2; DataInputStream in=new DataInputStream(System.in); System.out.println("Enter a string with Words: "); s=in.readLine(); StringTokenizer token1=new StringTokenizer(s); StringTokenizer token2; while(token1.hasMoreTokens()) { token2=new StringTokenizer(s); s1=token1.nextToken(); ctr=0; while(token2.hasMoreTokens()) { 10

s2=token2.nextToken(); if(s1.equals(s2)) ctr++; } System.out.println("'"+s1+"' Frequency "+ctr+"Times"); } } }

Program to read a file and check whether the file exists, readable, writable and also print the length of the File import java.io.*; class filetest { public static void main(String args[]) throws IOException { String fname; DataInputStream in=new DataInputStream(System.in); System.out.print("Enter a file name?"); fname=in.readLine(); //opening file File f=new File(fname); if(f.exists()) System.out.println("File exists.."); else System.out.println("File not exists.."); if(f.canRead()) System.out.println("File is readable.."); elseSystem.out.println("File is not readable.."); if(f.canWrite()) System.out.println("File is writable.."); elseSystem.out.println("File is not Writable.."); System.out.println("File length :"+f.length()); } }

Program to read a file and print char count,word count,line count. import java.io.*; class filestat { public static void main(String args[]) throws IOException { int pre=' ' , ch , ctr=0 , L=0 , w=1; String fname; 11

DataInputStream in=new DataInputStream(System.in); System.out.print("Enter a file name?"); fname=in.readLine(); //opening file FileInputStream f=new FileInputStream(fname); while((ch=f.read())!=-1) { if(ch!=' ' && ch!='\n') //char count ctr++; if(ch=='\n') //line count L++; if(ch==' ' && pre!= ' ') //word count w++; pre=ch; } System.out.println("Char Count= "+ctr); System.out.println("Word Count= "+(w+(L-1))); System.out.println("Line Count= "+L); } }

Sample applet program //Here is the Java File: import java.applet.*; import java.awt.*; public class Myapplet extends Applet { String str; public void init() { str = "This is my first applet"; } public void paint(Graphics g) { g.drawString(str, 50,50); } } // Here is the HTML File: // save file with Myapplet.html <HTML> <BODY> <applet code="Myapplet",height="200" width="200"> </applet> </BODY> </HTML> Compilation: javac Myapplet.java 12 // save file with Myapplet.java

Execution: appletviewer Myapplet.html Write a java program to draw a line,ellipse and rectangle import java.awt.*; // save file with appltdraw.java import java.applet.*; public class appltdraw extends java.applet.Applet { public void init() { resize(250,250); } public void paint(Graphics g) { //orange rect g.drawRect(100,100,300,450); g.setColor(Color.orange); g.fillRect(100,100,30,50); //red line g.setColor(Color.red); g.drawLine(0,0,120,120); //blue rect g.setColor(Color.blue); g.drawRect(100,100,30,50); g.setColor(Color.green); g.fillRect(150,150,30,50); //gray oval g.setColor(Color.gray); g.drawOval(0,0,50,100); } } \\applet code\\ // save file with appltdraw.html /* <applet code=appltdraw.class height=300 width=400> </applet> */ Compilation: javac appltdraw.java Execution: appletviewer appltdraw.html

13

You might also like