0% found this document useful (0 votes)
8 views

JAVA_LAB_MANUAL

Uploaded by

ak99379762
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

JAVA_LAB_MANUAL

Uploaded by

ak99379762
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

OOPS JAVA

LAB MANNUAL

Department of
Computer Science and Engineering

Department of Computer Science Engineering

NM INSTITUTE OF ENGINEERING & TECHNOLOGY

Dept of CSE 1 JAVA LAB


1. STANDARD OPERATING PROCEDURE
a) Explanation on today’s experiment by the concerned faculty using PPT/White Board
covering the following aspects:

1) Name of the experiment/Aim


2) Software/Hardware required
3) Algorithm/Source code
4) Test Data
I/P: data set
O/P:Result
b) Writing of source program bythe students.
c) Compiling and execution ofthe program

Writing of the experiment in the Observation Book:


The students will write the today’s experiment in the Observation book as per the
following format:

a) Name of the experiment/Aim


b) Software/Hardware required
c) Algorithm/Source Program
d) Test Data/Results for different data sets
I/P: dataset
O/P:
e) Signature of theFaculty

Dept of CSE 2 JAVA LAB


2. LABOBJECTIVE

1) Introduction to object oriented programming concepts- java as an object oriented


programming language. Introduction to java application and applets-control structures-
methods-arrays.
2) Object based and objects oriented programming creating packages-using overloaded
constructors-static class variables-data abstraction and information hiding-relation between
super class objects and subclass objects composition verses inheritance-polymorphism-
dynamic method binding abstract super classes and concrete super classes –inheriting
interface-use of inner classes and wrapperclasses.
3) Role of object oriented programming in designing GUI –Graphs and Java20overview of
swing- event handling, adapter classes and layout managers. Advance GUI components-
JPopup Menus- JDesktopPane- advance layoutmanagers.
4) Exception handling and multithreading in object oriented programming- When exception
handling should be used-java exception handling – exceptions and inheritance-multithreading
in java-thread synchronization-daemon threads Runnable interface- Files and streams injava
5) Network and Database handling through object oriented programming –using JOSC –
processing queries-overview of servlet –introduction to networking –establishing a simple
server and a client – introduction to RMI – implementing the remoteinterface.

Dept of CSE 3 JAVA LAB


3. List of LabExercises

Week 1 NAME OF THE PROGRAM Page. No

1 Write a Java program to find simple Interest. 9


2 Write a java program to convert numbers to words. 10

3 Write a java program to find sum of digits of the given numbers. 11


Week-2
4 Write a Java program to find the factorial of a given number. 12
5 Write Java Program to Accept two Integers and Check if they are Equal 13
6 Write a Java program to print number in sorting order. 14
Week-3
7 Write a Java program to print the given number is Armstrong or not. 15
8 Write a Program to find the Roots of a Quadratic Equation for the 16
given values.
9 Write a Program To print the Fibonacci series up to given numbers. 18
Week -4
10 Write a Program To print the Prime Numbers upto given numbers 19

11 Write a Program To check whether the given string is Palindrome or 20


not.
12 Java program to sort a string alphabetically 21
Week-5
13 Write a Program To find the product of matrices 22
14 Write java program display the file is exists and number of bytes in
the given file.
Week-6
15 Write a Java program that reads on file name from the user then displays 25
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.

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

Dept of CSE 4 JAVA LAB


Week-8
18 Write an applet that displays a simple message
19 Write an applet that computes the payment of a loan on the
amount of the loan, the interest rate and the number of months.it
takes one parameter from the browser: monthlyrate, iftrue, the
interest rate is per month otherwise the interest rate is per annual.

Week-9
20 Write a java program that works as a simple calculator 32

21 Write an applet To handling the mouse events

22 33
Write a java program on interthread communication

Week-10
23 Write a Program That lets the user to create ellipse.

Write a Program That allow user to draw polygon, rectangle. 35

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.

Dept of CSE 5 JAVA LAB


Process of building and running java application programs:

Text Editor

Java Source HTML


Code Javadoc files

Javac

Java Class Header


File Javah Files

Java (only file name) Jdb (database)

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.

Dept of CSE 6 JAVA LAB


INTRODUCTION, COMPILING & EXECUTING A JAVA ROGRAM.
Step1: Open notepad.

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)

Dept of CSE 7 JAVA LAB


AIM:
Name of the Experiment No1:
1. Write a java program to find the simpleinterest.
HW/SW requirements:
Processor : AMD Athelon ™ 1.67GHz
RAM : 256 MB
HardDisk : 40 GB
JDK is required, with compilers.
Algorithm:
1. Start the program .

2. Declare the variables and assume values

3. Interest To pay=principle*time*rate/100;

4. Print the values .

5. End of class and main method.

6. stop the process

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);
}

Dept of CSE 8 JAVA LAB


}

Output-$ javac Simple_Interest.java


$ java Simple_Interest

Enter the Principal : 20202


Enter the Rate of interest : 2.5
Enter the Time period : 3
The Simple Interest is : 1515.15

Dept of CSE 9 JAVA LAB


AIM:
Name of the Experiment No-2:
Program to convert the number entered in digits to its word representation is given below .
Software/Hardware Requirements:

S/W: JDK1.5(JAVA), Office XP, Windows NT Server with ServicePack


H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM

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{

publicstaticvoid main(String[] args){


int number =0;
Scanner scanner=newScanner(System.in);
System.out.println("Please type a number(max upto 9 digits)");
try{
// read the number
number=scanner.nextInt();
if(number ==0){
System.out.print("Number in words: Zero");
}else{
System.out.print("Number in words: "+numberToWord(number));
}
}catch(Exception e){
System.out.println("Please enter a valid number");
}
// close the reader
scanner.close();
}

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];
}
}
}

Dept of CSE 11 JAVA LAB


return words;
}
}

Output-

Please type a number(max upto 9 digits)


45673
Number in words: forty-five thousand six hundred seventy-three

Please type a number(max upto 9 digits)


-3424
Number in words: minus three thousand four hundred twenty-fou

Dept of CSE 12 JAVA LAB


AIM:
Name of the Experiment No3:
Write a java program to find sum of digits of the given numbers.
Software/Hardware Requirements:

S/W: JDK1.5(JAVA), Office XP, Windows NT Server with ServicePack


H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM
ALGORITHM:
Step1:start
Step2:input n,r,s
Step3:s=0
Step4:d=n%10
Step5:s=s+d
Step6:n=n/10
Step7: is n!=0
Step8: repeat step 4 to step 6 till step 7 is true
Step9:when step 7 falls
Step10:print s
Step11:stop

Prog- import java.util.Scanner;


public class Digit_Sum
{
public static void main(String args[])
{
int m, n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
m = s.nextInt();
while(m > 0)
{
n = m % 10;
sum = sum + n;
m = m / 10;
}
System.out.println("Sum of Digits:"+sum);
}
}

Output- $ javac Digit_Sum.java


Dept of CSE 13 JAVA LAB
AIM:
$ javaDigit_Sum

Enter the number:456


Sum of Digits:15

Dept of CSE 14 JAVA LAB


AIM:
Name of the Experiment No-4:

Write a java program to find the given factorial numbers.


Software/Hardware Requirements:

S/W: JDK1.5 (JAVA), Office XP, Windows NT Server with ServicePack


H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM

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);
}
}

output-Factorial of 5 is: 120

Dept of CSE 15 JAVA LAB


AIM:
Name of the Experiment No-5:
Java Program to Accept two Integers and Check if they are Equal

Software/Hardware Requirements:

S/W: JDK1.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.

2. Read a string withinputstreamReader(System.in).

3. Convert the string into Integer.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-
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

Enter the first number:5


Enter the second number:7
5 and 7 are not equal

Enter the first number:6


Enter the second number:6
6 and 6 are equal

Dept of CSE 17 JAVA LAB


AIM:
Name of the Experiment No-6:

Write a java program to check given numbers in a sorting order.

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.

2. Create a class and variables with datatypes.

3. Read a string withDatainputstreamReader(System.in).

4. convert the string intoInteger.parseInt(stdin.readLine());

5. for (inti = (ar.length - 1); i>= 0;i--)


6. {
7. for (int j = 1; j ≤ i; j++)
8. {
9. if (ar[j-1] >ar[j])
10. {
11. int temp =ar[j-1];
12. ar[j-1] =ar[j];
13. ar[j] = temp;
14. } } } }
15. Print the concatenation ofarrays.

16. Stop 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

Enter no. of elements you want in array:5


Enter all the elements:
4
3
2
6
1
Ascending Order:1,2,3,4,6

Dept of CSE 19 JAVA LAB


Enter 10 Elements intoArray
2
3
4
1
5
7
8
6
3
1
Required Order is
1
1
2
3
4
5
6
7
8

Dept of CSE 20 JAVA LAB


AIM:
Name of the Experiment No-7:

Write a java program to generate the Armstrong number.


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.

2. Create a class and variables with datatypes.

3. Declaration of the mainclass.

4. Read a string withDatainputstreamReader(System.in).

Dept of CSE 21 JAVA LAB


5. convert the string intoInteger.parseInt(stdin.readLine());

6. while N >0 repeat step 7 ,8 &9

7.r=N%10

8. sum=sum+r*r*r formula.

9.N=N/10

10. using if else statement check Sum== given Number or not.

11. Stop theprogram.


Prog-
classArmstrongWhile
{
public static void main(String[] arg)
{
inti=100,arm;
System.out.println("Armstrong numbers between 100 to 999");
while(i<1000)
{
arm=armstrongOrNot(i);
if(arm==i)
System.out.println(i);
i++;
}
}
staticintarmstrongOrNot(intnum)
{
intx,a=0;
while(num!=0)
{
x=num%10;
a=a+(x*x*x);
num/=10 ;
}
return a;
}
}
Output-
1 Armstrong numbers between 100 to 999
2 153
3 370
4 371
5 407

Dept of CSE 22 JAVA LAB


AIM:
Name of the Experiment No-8:

Write a java program to generate the quadratic equation.

Software/Hardware Requirements:

S/W: JDK1.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 the program. Import thepackages.

2. Create a class and variables with datatypes.

3. Declaration of the mainclass.

4. Read a string withinputstreamReader(System.in).

5. convert the string intoInteger.parseInt(stdin.readLine());

6. By using if(d==0) “Roots are Equal”.

7. if(d>0) “Roots are Real” otherwise ("Roots areImaginary");

8. End of class and mainmethod.

9. Stop theprogram.

Prog-
public class Quadratic {

public static void main(String[] args) {

double a = 2.3, b = 4, c = 5.6;


double root1, root2;

double determinant = b * b - 4 * a * c;

// condition for real and different roots


if(determinant > 0) {
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);

System.out.format("root1 = %.2f and root2 = %.2f", root1 , root2);


}
Dept of CSE 23 JAVA LAB
// Condition for real and equal roots
else if(determinant == 0) {
root1 = root2 = -b / (2 * a);

System.out.format("root1 = root2 = %.2f;", root1);


}
// If roots are not real
else {
doublerealPart = -b / (2 *a);
doubleimaginaryPart = Math.sqrt(-determinant) / (2 * a);

System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart,


imaginaryPart);
}
}
}

Output- root1 = -0.87+1.30i and root2 = -0.87-1.30i

Dept of CSE 24 JAVA LAB


AIM:
Name of the Experiment No-9:

Write a java program to generate the Fibonacci series, given number of n values.

Software/Hardware Requirements:

S/W: JDK1.5(JAVA), Office XP, Windows NT Server with ServicePack


H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM
ALGORITHM:

Step1: start

Step2: read I,x,f,f1,f2

Step3: f=0,f1=1,f2=1

Step4: do

I++

F1=f2

F2=f

F=f1+f2

While
Step5: print f

Step6: stop

Prog- import java.util.Scanner;


public class Fibonacci
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter value of n:");
n = s.nextInt();
System.out.print("Fibonacci Series:");
for(inti = 1; i<= n; i++)
{
a = b;
b = c;
Dept of CSE 25 JAVA LAB
c = a + b;
System.out.print(a+" ");
}
}

Output- $ javac Fibonacci.java


$ java Fibonacci

Enter value of n:5


Fibonacci Series:0 1 1 2

Dept of CSE 26 JAVA LAB


AIM:
Name of the Experiment No-10:
Write a java program to find the prime numbers up to given number.
Software/Hardware Requirements:
S/W: JDK1.5 (JAVA), Office XP, Windows NT Server with ServicePack
H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM
ALGORITHM:
Step1: start
Step2: read n value
Step3: for i=1 i<=n
Step4: repeat a b c de
a) fact equal to0
b) for j=1,j<=1 repeatc,d
c)if i percentage j equal tozero
d) fact equal to factorial added withone
e) if factorial equal to2print as prime number
step5: display the prime no till nthnum
6: stop
Prog-public class PrimeExample2{
static void checkPrime(int n){
int i,m=0,flag=0;
1. m=n/2;
2. if(n==0||n==1){
3. System.out.println(n+" is not prime number");
4. }else{
5. for(i=2;i<=m;i++){
6. if(n%i==0){
7. System.out.println(n+" is not prime number");
8. flag=1;
9. break;
}
}
10. if(flag==0) { System.out.println(n+" is prime number"); }
11. }//end of else
12. }
13. public static void main(String args[]){
14. checkPrime(1);
15. checkPrime(3);
16. checkPrime(17);
17. checkPrime(20);
18. }
19. }
Dept of CSE 27 JAVA LAB
Output-1 is not prime number
3 is prime number
17 is prime number
20 is not prime number

Dept of CSE 28 JAVA LAB


AIM:
Name of the Experiment No-11:

Write java program display the given string is palindrome or not


Software/Hardware Requirements:

S/W: JDK1.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 the program. Import thepackages.

2. Read a string withinputStreamReader(System.in).

3. reverse the string and store into anotherstring

4. if both the strings are equal

writepalandrom

else

write not a palindrom

5. End of class and mainmethod.

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();

int length =str.length();

for(inti= length -1;i>=0;i--)


rev= rev +str.charAt(i);

if(str.equals(rev))

Dept of CSE 29 JAVA LAB


System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");

}
}

Output-

Enter a string:
radar

radar is a palindrome

Dept of CSE 30 JAVA LAB


AIM:
Name of the Experiment No-12:

Java program to sort a string alphabetically

Software/Hardware Requirements:

S/W: JDK1.5(JAVA), Office XP, Windows NT Server with ServicePack


H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MB RAM
ALGORITHM:
1. Start theprogram.

2. Create a class and variables with datatypes.

3. Read a string withDatainputstreamReader(System.in).

4. convert n value tointeger

5. repeate „6‟ until I<n

6. repeate „7‟ until j<n-i

7. if a[j]<a[j+1] then

change value from a[j] to a[j+1]


8. Print thearray

9. Stop theprogram.

Prog-
import java.util.Arrays;

public class GFG


{
// Method to sort a string alphabetically
public static String sortString(String inputString)
{
// convert input string to char array
chartempArray[] = inputString.toCharArray();

// sort tempArray
Arrays.sort(tempArray);

// return new sorted string


return new String(tempArray);
}
Dept of CSE 31 JAVA LAB
// Driver method
public static void main(String[] args)
{
String inputString = "computerscience";
String outputString = sortString(inputString);

System.out.println("Input String : " + inputString);


System.out.println("Output String : " + outputString);
}
}
Output-
Input String :computerscience
Output String :ccceeeimoprstu

Dept of CSE 32 JAVA LAB


AIM:
Name of the Experiment No-13:
Write a java program to find the product of the matrices .

Software/Hardware Requirements:

S/W: JDK1.5(JAVA), Office XP, Windows NT Server with ServicePack


H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MBRAM

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

Dept of CSE 34 JAVA LAB


AIM:
Name of the Experiment No-14:
Write java program display the file is exists and number of bytes in the given file
Software/Hardware Requirements:

S/W: JDK1.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 the program, import the packages.

2. create an object of „fi‟ using fileinputstreamclass

3. if check the file exit then

print „file isexit‟

else

print „file does not exit

4. Print the number of bytes of given files is using fi.avail()function

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;

public class TemporaryFileExample


{
public static void main(String[] args)
{
File temp;
try
{
temp = File.createTempFile("myTempFile", ".txt");

Dept of CSE 35 JAVA LAB


boolean exists = temp.exists();

System.out.println("Temp file exists : " + exists);


} catch (IOException e)
{
e.printStackTrace();
}
}
}
Output-
Console
Temp file exists : true

Dept of CSE 36 JAVA LAB


AIM:
Name of the Experiment No-15:

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:

S/W: JDK1.5(JAVA), Office XP, Windows NT Server with ServicePack


H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MB RAM
ALGORITHM:
1) Start the program, import the packages.

2) create an object of „fi‟ using fileinputstreamclass

3) computecount=0,word=0,line=1,space=0

4) repeate „4‟ until file isempty

5) if fi.read() equal to new linethen

line++

else

fi.read() equal to space then

word++

else

char++

6) printword,line,char

7) Stop theprogram

8) Start the program, import the packages.

9) create an object of „fi‟ using fileinputstreamclass

10) computecount=0,word=0,line=1,space=0

11) repeate „4‟ until file isempty

12) if fi.read() equal to new linethen

Dept of CSE 37 JAVA LAB


line++
else
fi.read() equal to space then
word++
else
char++

13) printword,line,char

14) Stop theprogram

Dept of CSE 38 JAVA LAB


Prog-import java.util.Scanner;
importjava.io.File;
classFileDemo
{
publicstaticvoid main(String[] args)
{
Scanner input=newScanner(System.in);
String s=input.nextLine();
File f1=new File(s);
System.out.println("File Name:"+f1.getName());
System.out.println("Path:"+f1.getPath());
System.out.println("Abs Path:"+f1.getAbsolutePath());
System.out.println("Parent:"+f1.getParent());
System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists"));
System.out.println("Is file:"+f1.isFile());
System.out.println("Is Directory:"+f1.isDirectory());
System.out.println("Is Readable:"+f1.canRead());
System.out.println("IS Writable:"+f1.canWrite());
System.out.println("Is Absolute:"+f1.isAbsolute());
System.out.println("File Last Modified:"+f1.lastModified());
System.out.println("File Size:"+f1.length()+"bytes");
System.out.println("Is Hidden:"+f1.isHidden());
}
}

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

Dept of CSE 39 JAVA LAB


AIM:
Name of the Experiment No-16:

Creating thread by implementing Runnable interface

1. Let your class implement “Runnable”interface.

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

1. Create an object of the aboveclass

2. Allocate a thread object for ourthread

3. Call the method “start” on the allocated thread object

publicclassFirstThread implementsRunnable
{

//This method will be executed when this thread is executed


publicvoidrun()
{

//Looping from 1 to 10 to display numbers from 1 to 10 for( inti=1;


i<=10; i++)
{
//Displaying the numbers from this thread System.out.println( "Messag
from First Thread : "+i);

/*taking a delay of one second before displaying next number


*
* "Thread.sleep(1000);" - when this statement isexecuted,
* this thread will sleep for 1000 milliseconds (1second)
* before executing the nextstatement.
*
* Since we are making this thread to sleep for onesecond,
* we need to handle "InterruptedException". Ourthread
* may throw this exception if it is interrupted whileit
* issleeping.
*
*/
try
{
Thread.sleep (1000);
}
catch (InterruptedExceptioninterruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
*thread is interrupted.
*/
Dept of CSE 40 JAVA LAB
System.out.println( "First Thread is interrupted when it is
sleeping"+interruptedException);
}
}
}
}
publicclassSecondThread implementsRunnable
{

//This method will be executed when this thread is executed


publicvoidrun()

//Looping from 1 to 10 to display numbers from 1 to 10 for( inti=1;


i<=10; i++)
{
System.out.println( "Messag from Second Thread : "+i);

/*taking a delay of one second before displaying next number


*
* "Thread.sleep(1000);" - when this statement isexecuted,
* this thread will sleep for 1000 milliseconds (1second)
* before executing the nextstatement.
*
* Since we are making this thread to sleep for onesecond,
* we need to handle "InterruptedException". Ourthread
* may throw this exception if it is interrupted whileit
* issleeping.
*/
try
{
Thread.sleep(1000);
}
catch (InterruptedExceptioninterruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
* thread is interrupted.
*/
System.out.println( "Second Thread is interrupted when it is
sleeping"+interruptedException);
}
}
}
}

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();

//Starting the first thread


Thread thread1 = newThread(firstThread);
thread1.start();

//Starting the second thread


Thread thread2 = newThread(secondThread);
thread2.start();
}
}

Dept of CSE 42 JAVA LAB


AIM:
Name of the Experiment No-17:

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+": ");

}
}
}

Output-Enter File name: raj.txt

Contents of the file are :

1: kotireddy
2: Santhosh

3: Vamsi

Dept of CSE 43 JAVA LAB


AIM:
Name of the Experiment No-18:
Write a java applet to display simple message
Software/Hardware Requirements:

S/W: JDK1.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
2: take applets
2 :display
3 Endapplet
Prog-importjava.awt.*;
importjava.applet.*;
/*
<applet code="sim" width=300 height=300>
</applet>
*/
publicclasssimextendsApplet
{
Stringmsg=" ";
publicvoidinit()
{
msg+="init()--->";
setBackground(Color.orange);
}
publicvoid start()
{
msg+="start()--->";
setForeground(Color.blue);

}
publicvoid paint(Graphics g)
{
msg+="paint()--->";
g.drawString(msg,200,50);
}
}

Output-

Dept of CSE 44 JAVA LAB


Dept of CSE 45 JAVA LAB
AIM:
Name of the Experiment No-19:
Write an applet that computes the payment of a loan on the amount of the loan,the interest rate
and the number of months.it takes one parameter from the browser:monthlyrate,iftrue,the
interest rate is per month otherwise the interest rate is per annual.
Software/Hardware Requirements:
S/W: JDK1.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
2 takeapplet
3 add(newLabel("selectmonths/years"));
4 actionPerformed(ActionEvente)
5else
6 stop

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(" ");

Dept of CSE 47 JAVA LAB


t3.setText(" ");
t4.setText(" ");
}
}
}
Output-

Dept of CSE 48 JAVA LAB


AIM:
Name of the Experiment No-20:
Write a java program that works as a simple calculator
Software/Hardware Requirements:

S/W: JDK1.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
2 takeapplet
3 add(new Labels)
4 actionPerformed(ActionEvente)
5else
6 prnilni=Integer.parseInt(s2)/Integer.parseInt(s1);
7stop tf.setText(String.valueOf(i));

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;

public void init()


{
t1=new TextField(10);
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");
b0=new Button("0");
add=new Button("+");
Dept of CSE 49 JAVA LAB
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
eq=new Button("=");
cl=new Button("Clear");

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();

Dept of CSE 50 JAVA LAB


//t1.addTextListener(this);
}
public void paint()
{
setBackground(Color.green);
}

public void actionPerformed(ActionEvent e)


{
s=e.getActionCommand();
if(s.equals("0")||s.equals("1")||s.equals("2")||
s.equals("3")||s.equals("4")||s.equals("5")||s.equals("6")||s.equals("7")||s.equals("8")||
s.equals("9")||s.equals("0"))
{
s1=t1.getText()+s;
t1.setText(s1);
}
if(s.equals("+"))
{
s2=t1.getText();
t1.setText("");
s3="+";
}
if(s.equals("-"))
{
s2=t1.getText();
t1.setText("");
s3="-";
}
if(s.equals("*"))
{
s2=t1.getText();
t1.setText("");
s3="*";
}
if(s.equals("*"))
{
s2=t1.getText();
t1.setText("");
s3="*";
}
if(s.equals("="))
{
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals("+"))

Dept of CSE 51 JAVA LAB


c=a+b;
if(s3.equals("-"))
c=a-b;

t1.setText(String.valueOf(c));
}
if(s.equals("Clear"))
{
t1.setText("");
}
}
public void textValueChanged(TextEvent e)
{

}
}

output-

Dept of CSE 52 JAVA LAB


AIM:
Name of the Experiment No21:

Write a java program to implement the APPLET PACKAGES, draw Mouse event handler
programs.

Software/Hardware Requirements:

S/W: JDK1.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.

2. Import the packages of applet, awt,awt.event.

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.

6. while rotating mouse eventargs.

7. The mouse event argumentsexecution.

8. Printing in the separated Applet viewerwindow.

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";

Dept of CSE 54 JAVA LAB


67 setBackground(Color.pink);
68 showStatus("Mouse Clicked");
69 repaint();
70 }
71 public void paint(Graphics g)
72 {
73 g.drawString(msg,X,Y);
74 }
75 }
Output-

Dept of CSE 55 JAVA LAB


AIM:
Name of the Experiment No22:

Write a java program on interthread communication

Software/Hardware Requirements:

S/W: JDK1.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
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

Dept of CSE 57 JAVA LAB


AIM:
Name of the Experiment No23:

Write a java program to implement the APPLET PACKAGES, ellipse,Rectangles, Rounded


Rectangles, filled Polygons programs.

Software/Hardware Requirements:

S/W: JDK1.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.

2. Import the packages of applet,awt,awt.event.

3. Create a classes: public void paint(Graphicsg).

4. Assume the values of string, color andfont.

5. g.drawString() application of Graphical User Interface.

6. Printing in the separated Applet viewerwindow.

7. Stop theprogram.

Prog-// java program to draw a ellipse


// using drawOval function.
importjava.awt.*;
importjavax.swing.*;

public class ellipse extends JApplet {

public void init()


{
// set size
setSize(400, 400);

repaint();
}

Dept of CSE 58 JAVA LAB


// paint the applet
public void paint(Graphics g)
{
// set Color for rectangle
g.setColor(Color.red);

// draw a ellipse
g.drawOval(100, 100, 150, 100);
}
}
Output-

Prog-// Java Program Draw a rectangle


// using drawLine(int x, int y, int x1, int y1)
importjava.awt.*;
importjavax.swing.*;

public class rectangle extends JApplet {

public void init()


{
// set size
setSize(400, 400);

repaint();
}

// paint the applet


public void paint(Graphics g)
Dept of CSE 59 JAVA LAB
{
// set Color for rectangle
g.setColor(Color.red);

// draw a rectangle by drawing four lines


g.drawLine(100, 100, 100, 300);
g.drawLine(100, 300, 300, 300);
g.drawLine(300, 300, 300, 100);
g.drawLine(300, 100, 100, 100);
}
}

Output-

- JJJJ

Dept of CSE 60 JAVA LAB


JJJ
// Java program to draw polygon using
// drawPolygon(int[] x, int[] y, intnumberofpoints)
// function
importjava.awt.*;
importjavax.swing.*;

public class poly extends JApplet {

// called when applet is started


public void init()
{
// set the size of applet to 300, 300
setSize(200, 200);
show();
}

// invoked when applet is started


public void start()
{
}

// invoked when applet is closed


public void stop()
{
}

public void paint(Graphics g)


{
// x coordinates of vertices
int x[] = { 10, 30, 40, 50, 110, 140 };

// y coordinates of vertices
int y[] = { 140, 110, 50, 40, 30, 10 };

// number of vertices
intnumberofpoints = 6;

// set the color of line drawn to blue


g.setColor(Color.blue);

// draw the polygon using drawPolygon function


g.drawPolygon(x, y, numberofpoints);
}
}

Dept of CSE 61 JAVA LAB


Output-

Dept of CSE 62 JAVA LAB


AIM:
Name of the Experiment No-24:

Write a java program that implements the client/server program

Software/Hardware Requirements:

S/W: JDK1.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.

2 Import the packages of applet, awt, awt.event.

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:

1. Programming in Java. Second Edition. OXFORD HIGHER EDUCATION.(SACHIN


MALHOTRA/SAURAV CHOUDHARY).
2. JAVA Complete Reference (9th Edition) HerbaltSchelidt.
3. Just Java 1.2- Peter van derlinder

Dept of CSE 64 JAVA LAB

You might also like