JAVA_LAB_MANUAL
JAVA_LAB_MANUAL
LAB MANNUAL
Department of
Computer Science and Engineering
16 27
Write a program for creating thread by implementing Runnable
interface
Week-7
17 Write java Program to print the contents of the file along with line
number
Week-9
20 Write a java program that works as a simple calculator 32
22 33
Write a java program on interthread communication
Week-10
23 Write a Program That lets the user to create ellipse.
Week-11
24 Write a Program That implements the client/server application. The 37
client sends the data to the server; the client 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.
Text Editor
Javac
Java
program
Output
The way these tools are applied to build and run application programs is create a program. We
need create a source code file using a text editor. The source code is then compiled using the java
compiler javac and executed using the java interpreter java. The java debugger jdb is used to find
errors. A complied java program can be converted into a source code.
Compilation steps
Step2: Create new file and write your java program.
Step3: Save the file as classname.jave for example if your class name is test then your file
name should be test.java
Step4: Open command prompt (Go to start menu->run->type cmd then enter key press)
Step5: Type javac filename and press enter.
If everything is ok the compiler creates a file called fliname.class which contains byte
code.
Step6: To run /to see the output type java class name. (This step is the Executing java
program)
3. Interest To pay=principle*time*rate/100;
prog-import java.util.Scanner;
public class Simple_Interest
{
public static void main(String args[])
{
float p, r, t;
Scanner s = new Scanner(System.in);
System.out.print("Enter the Principal : ");
p = s.nextFloat();
System.out.print("Enter the Rate of interest : ");
r = s.nextFloat();
System.out.print("Enter the Time period : ");
t = s.nextFloat();
floatsi;
si = (r * t * p) / 100;
System.out.print("The Simple Interest is : " + si);
}
ALGORITHM:
Algorithm:
1. Start theprogram.
2. Read a string withinputstream0 Reader(System.in).
3. convert the string intoInteger.parseInt(stdin.readLine());
4. By using switch case (multi way decision statement) when a match is found, that caseis
executed.
5. Default it is a break statement exit the switchstatement.
6. Stop theprogram.
Prog-importjava.util.Scanner;
importjava.util.Scanner;
publicclassNumberToWordConverter{
privatestaticStringnumberToWord(int number){
// variable to hold string representation of number
String words ="";
Dept of CSE 10 JAVA LAB
StringunitsArray[]={"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"};
StringtensArray[]={"zero", "ten", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};
if(number ==0){
return"zero";
}
// add minus before conversion if the number is less than 0
if(number <0){// convert the number to a string
StringnumberStr=""+ number;
// remove minus before the number
numberStr=numberStr.substring(1);
// add minus before the number and convert the rest of number
return"minus "+numberToWord(Integer.parseInt(numberStr));
}
// check if number is divisible by 1 million
if((number /1000000)>0){
words+=numberToWord(number /1000000)+" million ";
number%=1000000;
}
// check if number is divisible by 1 thousand
if((number /1000)>0){
words+=numberToWord(number /1000)+" thousand ";
number%=1000;
}
// check if number is divisible by 1 hundred
if((number /100)>0){
words+=numberToWord(number /100)+" hundred ";
number%=100;
}
if(number >0){
// check if number is within teens
if(number <20){
// fetch the appropriate value from unit array
words+=unitsArray[number];
}else{
// fetch the appropriate value from tens array
words+=tensArray[number /10];
if((number %10)>0){
words+="-"+unitsArray[number %10];
}
}
}
Output-
ALGORITHM:
Step1: start
Step2: input n,I,f
Step3: f=i=1
Step4: if(i<=n)
Step5: f=f*i
Step6: i=i+1
Step7: repeat from step5 to step6 till steps true
Step8: print f
tep9: stop
prog-
class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Software/Hardware Requirements:
ALGORITHM:
1. Start theprogram.
4. By using switch case (multi way decision statement) when a match is found, that caseis
executed.
6. stop theprogram.
Prog-
import java.util.Scanner;
public class Equal_Integer
{
public static void main(String[] args)
{
int m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
m = s.nextInt();
System.out.print("Enter the second number:");
n = s.nextInt();
if(m == n)
{
System.out.println(m+" and "+n+" are equal ");
}
else
{
System.out.println(m+" and "+n+" are not equal ");
}
}
}
Dept of CSE 16 JAVA LAB
Output-$ javac Equal_Integer.java
$ javaEqual_Integer
Software/Hardware Requirements:
S/W: JDK 1.5 (JAVA), Office XP, Windows NT Server with ServicePack
H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM
ALGORITHM:
1. Start theprogram.
Prog-
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (inti = 0; i< n; i++)
Dept of CSE 18 JAVA LAB
{
a[i] = s.nextInt();
}
for (inti = 0; i< n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (inti = 0; i< n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output-
$ javac Ascending _Order.java
$ java Ascending _Order
S/W: JDK 1.5 (JAVA), Office XP, Windows NT Server with ServicePack
H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM
ALGORITHM:
1. Start theprogram.
7.r=N%10
8. sum=sum+r*r*r formula.
9.N=N/10
Software/Hardware Requirements:
ALGORITHM:
9. Stop theprogram.
Prog-
public class Quadratic {
double determinant = b * b - 4 * a * c;
Write a java program to generate the Fibonacci series, given number of n values.
Software/Hardware Requirements:
Step1: start
Step3: f=0,f1=1,f2=1
Step4: do
I++
F1=f2
F2=f
F=f1+f2
While
Step5: print f
Step6: stop
writepalandrom
else
6. stop theprogram.
Prog-import java.util.Scanner;
classChkPalindrome
{
publicstaticvoid main(String args[])
{
Stringstr, rev ="";
Scannersc=newScanner(System.in);
System.out.println("Enter a string:");
str=sc.nextLine();
if(str.equals(rev))
}
}
Output-
Enter a string:
radar
radar is a palindrome
Software/Hardware Requirements:
7. if a[j]<a[j+1] then
9. Stop theprogram.
Prog-
import java.util.Arrays;
// sort tempArray
Arrays.sort(tempArray);
Software/Hardware Requirements:
ALGORITHM:
Step1: start
Step2:read I,j,k,a[3][3],b[3][2],c[3][2]
Step3: read a[3][3] & b[3][2]
Step 4:i=0,j=0,k=0
Step5: if i<3 then i++ else goto 1
Step6: if j<3 then j++ else goto 5
Step7: if k<3 then k++ else goto 6
Step8: c[i][j]=c[i][j]+a[k][j]*b[i][k]
Step9: print a[i][j],b[i][j],c[i][j]
Step 10: stop
Prog-
public class MatrixMultiplicationExample{
1. public static void main(String args[]){
2. //creating two matrices
3. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
4. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
5.
6. //creating another matrix to store the multiplication of two matrices
7. int c[][]=new int[3][3]; //3 rows and 3 columns
8.
9. //multiplying and printing multiplication of 2 matrices
10. for(int i=0;i<3;i++){
11. for(int j=0;j<3;j++){
12. c[i][j]=0;
13. for(int k=0;k<3;k++)
14. {
15. c[i][j]+=a[i][k]*b[k][j];
16. }//end of k loop
17. System.out.print(c[i][j]+" "); //printing matrix element
18. }//end of j loop
19. System.out.println();//new line
20. }
21. }}
Dept of CSE 33 JAVA LAB
Output-
666
12 12 12
18 18 18
else
5. Stop theprogram
To test to see if a file or directory exists, use the “exists()” method of the Java java.io.File class, as
shown here:
File tempFile = new File("c:/temp/temp.txt");
boolean exists = tempFile.exists();
If above method returns true then file or directory does exist, and otherwise does not exists.
Check file exist with exists() method
Prog-import java.io.File;
importjava.io.IOException;
Write a Java program that reads on 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 the file and the
length of the file in bytes.
Software/Hardware Requirements:
3) computecount=0,word=0,line=1,space=0
line++
else
word++
else
char++
6) printword,line,char
7) Stop theprogram
10) computecount=0,word=0,line=1,space=0
13) printword,line,char
Output-Fibonacci.java
File Name:Fibonacci.java
Path: Fibonacci.java
Abs Path: c:\sameer\Fibonacci.java
Parent: Null
This file is:Exists
Is file:true
Is Directory:false
Is Readable:true
Is Writable:true
Is Absolute:false
File Last Modified:1206324301937
File Size: 406 bytes
Is Hidden:false
2. Now override the “public void run()” method and write your logic there (This is themethod
which will be executed when this thread isstarted.
That‟s it, now you can start this thread as given below
publicclassFirstThread implementsRunnable
{
publicclassThreadDemo
{
publicstaticvoidmain(String args[])
{
//Creating an object of the first thread FirstThread
firstThread = newFirstThread();
Dept of CSE 41 JAVA LAB
//Creating an object of the Second thread SecondThread
secondThread = newSecondThread();
Program to print the contents of the file along with line number
Prog-import java.util.*;
import java.io.*;
classRfile
{
public static void main(String args[])throws IOException
{
int j=1;
charch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.next();
FileInputStream f=new FileInputStream(str);
System.out.println("\nContents of the file are");
int n=f.available();
System.out.print(j+": ");
for(inti=0;i<n;i++)
{
ch=(char)f.read();
System.out.print(ch);
if(ch=='\n')
{
System.out.print(++j+": ");
}
}
}
1: kotireddy
2: Santhosh
3: Vamsi
}
publicvoid paint(Graphics g)
{
msg+="paint()--->";
g.drawString(msg,200,50);
}
}
Output-
Prog-importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
/*
<applet code="Loan" width=300 height=300>
</applet>
*/
publicclass Loan extends Applet
implementsActionListener,ItemListener
{
doublep,r,n,total,i;
String param1;
boolean month;
Label l1,l2,l3,l4;
TextField t1,t2,t3,t4;
Button b1,b2;
CheckboxGroupcbg;
Checkbox c1,c2;
String str;
publicvoidinit()
{
l1=newLabel("Balance Amount",Label.LEFT);
l2=newLabel("Number of Months",Label.LEFT);
l3=newLabel("Interest Rate",Label.LEFT);
l4=newLabel("Total Payment",Label.LEFT);
t1=newTextField(5);
t2=newTextField(5);
t3=newTextField(15);
t4=newTextField(20);
b1=newButton("OK");
b2=newButton("Delete");
Dept of CSE 46 JAVA LAB
cbg=newCheckboxGroup();
c1=newCheckbox("Month Rate",cbg,true);
c2=newCheckbox("Annual Rate",cbg,true);
t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
t4.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(t4);
add(c1);
add(c2);
add(b1);
add(b2);
}
publicvoiditemStateChanged(ItemEventie)
{
}
publicvoidactionPerformed(ActionEventae)
{
str=ae.getActionCommand();
if(str.equals("OK"))
{
p=Double.parseDouble(t1.getText());
n=Double.parseDouble(t2.getText());
r=Double.parseDouble(t3.getText());
if(c2.getState())
{
n=n/12;
}
i=(p*n*r)/100;
total=p+i;
t4.setText(" "+total);
}
elseif(str.equals("Delete"))
{
t1.setText(" ");
t2.setText(" ");
Prog-
import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;;
public class calculator extends Applet implements ActionListener, TextListener
{
String s,s1,s2,s3,s4;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,eq,cl,mul,div;
TextField t1;
inta,b,c;
GridLayoutgb=new GridLayout(4,5);
setLayout(gb);
add(t1);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
add(b0);
add(add);
add(sub);
add(mul);
add(div);
add(eq);
add(cl);
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);
b0.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
eq.addActionListener(this);
cl.addActionListener(this);
paint();
t1.setText(String.valueOf(c));
}
if(s.equals("Clear"))
{
t1.setText("");
}
}
public void textValueChanged(TextEvent e)
{
}
}
output-
Write a java program to implement the APPLET PACKAGES, draw Mouse event handler
programs.
Software/Hardware Requirements:
ALGORITHM:
1. Start theprogram.
3. Create a classes,methods.
4. Mouse moments, mouse Clicked, mouse Pressed, mouse Released, mouse Entered, mouse
Exited, mouse Dragged events args.
5. g.drawString() application of Graphical User Interface.
9. Stop theprogram.
Prog-
1 importjava.awt.*;
2 importjava.awt.event.*;
3 importjava.applet.*;
4 /*
5 <applet code="Mouse" width=500 height=500>
6 </applet>
7 */
8 public class Mouse extends Applet
9 implements MouseListener,MouseMotionListener
10 {
11 int X=0,Y=20;
12 String msg="MouseEvents";
13 public void init()
14 {
15 addMouseListener(this);
Dept of CSE 53 JAVA LAB
16 addMouseMotionListener(this);
17 setBackground(Color.black);
18 setForeground(Color.red);
19 }
20 public void mouseEntered(MouseEvent m)
21 {
22 setBackground(Color.magenta);
23 showStatus("Mouse Entered");
24 repaint();
25 }
26 public void mouseExited(MouseEvent m)
27 {
28 setBackground(Color.black);
29 showStatus("Mouse Exited");
30 repaint();
31 }
32 public void mousePressed(MouseEvent m)
33 {
34 X=10;
35 Y=20;
36 msg="NEC";
37 setBackground(Color.green);
38 repaint();
39 }
40 public void mouseReleased(MouseEvent m)
41 {
42 X=10;
43 Y=20;
44 msg="Engineering";
45 setBackground(Color.blue);
46 repaint();
47 }
48 public void mouseMoved(MouseEvent m)
49 {
50 X=m.getX();
51 Y=m.getY();
52 msg="College";
53 setBackground(Color.white);
54 showStatus("Mouse Moved");
55 repaint();
56 }
57 public void mouseDragged(MouseEvent m)
58 {
59 msg="CSE";
60 setBackground(Color.yellow);
61 showStatus("Mouse Moved"+m.getX()+" "+m.getY());
62 repaint();
63 }
64 public void mouseClicked(MouseEvent m)
65 {
66 msg="Students";
Software/Hardware Requirements:
ALGORITHM:
1 Start
2 takeclass
3 for singalwait
4 true 0rfalse
5 println new InterThread(job)
6 stop
1. prog-class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
Dept of CSE 56 JAVA LAB
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Output-going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Software/Hardware Requirements:
ALGORITHM:
1. Start theprogram.
7. Stop theprogram.
repaint();
}
// draw a ellipse
g.drawOval(100, 100, 150, 100);
}
}
Output-
repaint();
}
Output-
- JJJJ
// y coordinates of vertices
int y[] = { 140, 110, 50, 40, 30, 10 };
// number of vertices
intnumberofpoints = 6;
Software/Hardware Requirements:
3 Create a classes,methods.
4 take ServerSocketssoc=new ServerSocket
5 defalt throws Exception
6 display byte[]data=msg.getBytes();
7 printlni=3.14*Float.parseFloat(str)*Float.parseFloat(str);
6 stop program
Prog-
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());
PrintStreamps=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
{
ServerSocketss=new ServerSocket(10000);
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
int n=Integer.parseInt(dis.readLine());
PrintStreamps=new PrintStream(s.getOutputStream());
Dept of CSE 63 JAVA LAB
ps.println(3.14*n*n);
}
}
BOOKS: