0% found this document useful (0 votes)
14 views52 pages

Java Lab Manual

The document discusses installing Java Development Kit (JDK) and writing a simple Java program to output 'Hello World'. It includes steps to download and install JDK, set environment variables, compile and run a basic Java program from the command line. Several code examples of simple Java programs are provided.

Uploaded by

lotadey535
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views52 pages

Java Lab Manual

The document discusses installing Java Development Kit (JDK) and writing a simple Java program to output 'Hello World'. It includes steps to download and install JDK, set environment variables, compile and run a basic Java program from the command line. Several code examples of simple Java programs are provided.

Uploaded by

lotadey535
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

3350703_Java Programming Enrollment No

Practical – 1
Aim: Install JDK, Write a simple “Hello World” or similar java program,
compilation, debugging, executing using java compiler and interface.
Ans:
➢ The java Software Development Kit is an application created by Sun
Microsystems to create and modify java programs.
➢ This is where to start if you would like to start programming in java.
➢ Step 1: Download JDK.

➢ Step 2: Install JDK and JRE.

1
3350703_Java Programming Enrollment No

➢ Step 3: Include JDK’s “bin” directory in the path

2
3350703_Java Programming Enrollment No

Step 4: Verify the JDK installation

➢ HelloWorld.java
class Demo{

public static void main(String args[]) {

System.out.println(“Hello World”);

➢ Compiling

• To compile the source code “HelloWorld.java”

• Start a cmd shell (click “Start” button → select “run..” → Enter “cmd” )

• Set the current Drive to the drive where you saved your source file
“HelloWorld.java”.

• For eg., suppose that our source file is saved at desktop.

Prompt> C:

3
3350703_Java Programming Enrollment No

C:\users>

C:\users> cd Desktop

C:\users\Desktop>

C:\users\Desktop> javac HelloWorld.java

➢ Running the program


• To run the program
C:\users\Desktop> java Demo

➢ Output
Hello World

4
3350703_Java Programming Enrollment No

Practical – 2
Aim: Write a program in Java to generate first n prime numbers.
Ans:
import java.util.*;
public class p2 {
public static void main(String[] args) {
int n, status = 1, num = 3, count, j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of prime numbers you want : ");
n = in.nextInt();
if (n >= 1){
System.out.println("First "+n+" prime numbers are : ");
System.out.println(2);
}
for (count = 2; count <=n;){
for (j = 2; j <= Math.sqrt(num); j++){
if (num%j == 0){
status = 0;
break;
}
}
if (status != 0){
System.out.println(num);
count++;
}
status = 1;
num++;
}
in.close();
}
}

5
3350703_Java Programming Enrollment No

Output:

6
3350703_Java Programming Enrollment No

Practical – 3
Aim: Write a program in Java to find maximum of three numbers using
conditional operator.
Ans:
import java.util.*;
public class p3{
public static void main(String[] args) {
int a, b, c, d;
Scanner s = new Scanner(System.in);
System.out.println("Enter all three numbers:");
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
d = c > (a > b ? a : b) ? c : ((a > b) ? a : b);
System.out.println("Largest Number:"+d);
s.close();
}
}
Output:

7
3350703_Java Programming Enrollment No

Practical – 4
Aim: Write a program in Java to find second maximum of n numbers
without using arrays.
Ans:
import java.util.*;
public class p4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int max1=0,max2=0,c=0,n=0;
System.out.println("> How many numbers ? ");
n = s.nextInt();
System.out.println("\n");
for(int i=0;i<n;i++){
c = s.nextInt();
if(c > max1){
max2 = max1;
max1 = c;
}
else if(c>max2){
max2 = c;
}
}
System.out.println("\n\n> Second max number is : "+max2);
s.close();
}
}

8
3350703_Java Programming Enrollment No

Output:

9
3350703_Java Programming Enrollment No

Practical – 5
Aim: Write a program in Java to reverse the digits of a number using while
loop.
Ans:
import java.util.*;
import java.util.Scanner;
public class p5{
public static void main(String[] args) {
Scanner s;
s = new Scanner(System.in);
int n=0,rev=0;
System.out.println("> Enter number : ");
n = s.nextInt();
int temp = n;
while(temp>0){
rev = (rev*10) + (temp%10);
temp = temp/10;
}
System.out.println("\n\n> Reverce number : "+rev);
s.close();
}
}
Output:

10
3350703_Java Programming Enrollment No

Practical – 6
Aim: Write a program in Java to convert number into words & print it.
Ans:
import java.util.Scanner;
public class p6 {
public String to100(int n){
String str = "";
while(n!=0){
if(n==1){
str = str + " one";
n=0;
}
else if(n==2){
str = str + " two";
n=0;
}
else if(n==3){
str = str + " three";
n=0;
}
else if(n==4){
str = str + " four";
n=0;
}
else if(n==5){
str = str + " five";
n=0;
}
else if(n==6){
str = str + " six";
n=0;
}

11
3350703_Java Programming Enrollment No

else if(n==7){
str = str + " seven";
n=0;
}
else if(n==8){
str = str + " eight";
n=0;
}
else if(n==9){
str = str + " nine";
n=0;
}
else if(n==10){
str = str + " ten";
n=0;
}
else if(n==11){
str = str + " eleven";
n=0;
}
else if(n==12){
str = str + " twelve";
n=0;
}
else if(n==13){
str = str + " thirteen";
n=0;
}
else if(n==14){
str = str + " forteen";
n=0;
}

12
3350703_Java Programming Enrollment No

else if(n==15){
str = str + " fifteen";
n=0;
}
else if(n==16){
str = str + " sixteen";
n=0;
}
else if(n==17){
str = str + " seventeen";
n=0;
}
else if(n==18){
str = str + " eighteen";
n=0;
}
else if(n==19){
str = str + " nineteen";
n=0;
}
else if(n>=20 && n<30){
str = str + " twenty";
n = n - 20;
}
else if(n>=30 && n<40){
str = str + " thirty";
n = n - 30;
}
else if(n>=40 && n<50){
str = str + " forty";
n = n - 40;
}

13
3350703_Java Programming Enrollment No

else if(n>=50 && n<60){


str = str + " fifty";
n = n - 50;
}
else if(n>=60 && n<70){
str = str + " sixty";
n = n - 60;
}
else if(n>=70 && n<80){
str = str + " seventy";
n = n - 70;
}
else if(n>=80 && n<90){
str = str + " eighty";
n = n - 80;
}
else if(n>=90 && n<100){
str = str + " ninety";
n = n - 90;
}
}
return str;
}
public String toWord(int n)
{
String str = "";
while(n!=0){
if(n>=1 && n<100){
str = str + to100(n);
n=0;
}
else if(n>=100 && n<1000){

14
3350703_Java Programming Enrollment No

str = str + to100(n/100);


str = str + " hundred and";
n = n % 100;
}
else if(n>=1000 && n<100000){
str = str + to100(n/1000);
str = str + " thousand,";
n = n % 1000;
}
else if(n>=10000 && n<10000000){
str = str + to100(n/100000);
str = str + " lakh,";
n = n % 100000;
}
else if(n==10000000){
str = "one crore";
n=0;
}
else{
str = "\n\n> Please enter a number between 1 to 1 crore ...";
n=0;
}
}
return str;
}
public static void main(String[] args){
Scanner s;
s = new Scanner(System.in);
int n=0;
String str;
p6 obj = new p6();
System.out.println("> Enter the number : ");

15
3350703_Java Programming Enrollment No

n = s.nextInt();
str = obj.toWord(n);
System.out.println("\n\n> "+str);
s.close();
}
}
Output:

16
3350703_Java Programming Enrollment No

Practical – 7
Aim: Write programs in Java to use Wrapper class of each primitive data
types.
Ans:
class p7{
public static void main(String args[]){
// byte data type
byte a = 1;
// wrapping around Byte object
Byte byteobj = new Byte(a);
// int data type
int b = 10;
//wrapping around Integer object
Integer intobj = new Integer(b);
// float data type
float c = 18.6f;
// wrapping around Float object
Float floatobj = new Float(c);
// double data type
double d = 250.5;
// Wrapping around Double object
Double doubleobj = new Double(d);
// char data type
char e='a';
// wrapping around Character object
Character charobj=e;
// printing the values from objects
System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object byteobj: " + byteobj);
System.out.println("Integer object intobj: " + intobj);
System.out.println("Float object floatobj: " + floatobj);
System.out.println("Double object doubleobj: " + doubleobj);

17
3350703_Java Programming Enrollment No

System.out.println("Character object charobj: " + charobj);


// objects to data types (retrieving data types from objects)
// unwrapping objects to primitive data types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;
// printing the values from data types
System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
System.out.println("char value, cv: " + cv);
}
}
Output:

18
3350703_Java Programming Enrollment No

Practical – 8
Aim: Write a program in Java to multiply two matrix.
Ans:
import java.util.*;
class p8{
public static void main(String args[]){
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter elements of first matrix");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
first[c][d] = in.nextInt();
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();
if (n != p)
System.out.println("The matrices can't be multiplied with each other.");
else{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter elements of second matrix");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
second[c][d] = in.nextInt();
for (c = 0; c < m; c++){
for (d = 0; d < q; d++){
for (k = 0; k < p; k++){
sum = sum + first[c][k]*second[k][d];

19
3350703_Java Programming Enrollment No

}
multiply[c][d] = sum;
sum = 0;
}
}
System.out.println("Product of the matrices:");
for (c = 0; c < m; c++){
for (d = 0; d < q; d++)
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
}
}
}
Output:

20
3350703_Java Programming Enrollment No

Practical – 9
Aim: Write a static block which will be executed before main( ) method in a
class.
Ans:
class p9 {
static {
System.out.println("Static block called ... Before Main Method.");
}
public static void main(String args[]) {
System.out.println("This is Main Method ...");
}
}
Output:

21
3350703_Java Programming Enrollment No

Practical – 10
Aim: Write a program in Java to demonstrate use of this keyword. Check
whether this can access the private members of the class or not.
Ans:
class p10{
int a;
int b;
public void setData(int a ,int b){
this.a = a;
this.b = b;
}
public void showData(){
System.out.println("Value of A ="+a);
System.out.println("Value of B ="+b);
}
public static void main(String args[]){
Account obj = new Account();
obj.setData(2,3);
obj.showData();
}
}
Output:

22
3350703_Java Programming Enrollment No

Practical – 11
Aim: Write a program in Java to develop overloaded constructor. Also
develop the copy constructor to create a new object with the state of the
existing object.
Ans:
class Box{
double width, height, depth;
// constructor used when all dimensions
// specified
Box(double w, double h, double d){
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions
// specified
Box(){
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len){
width = height = depth = len;
}
// constructor to copy object
Box(Box b1){
this.width = b1.width;
this.height = b1.height;
this.depth = b1.depth;
}
// compute and return volume
double volume(){
return width * height * depth;

23
3350703_Java Programming Enrollment No

}
public static void main(String args[]){
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box mybox1copy = new Box(mybox1);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
// get volume of Copied box
vol = mybox1copy.volume();
System.out.println(" Volume of mybox1copy is " + vol);
}
}
Output:

24
3350703_Java Programming Enrollment No

Practical – 12
Aim: Write a program in Java to demonstrate the use of private
constructor and also write a method which will count the number of
instances created using default constructor only.
Ans:
class PrivateCon {
int val;
public static int count;
private PrivateCon() {
val = 1;
count();
}
private PrivateCon(int val) {
this.val = val;
}
void count() {
count = count + 1;
}
public static void main(String Args[]){
PrivateCon obj1 = new PrivateCon();
PrivateCon obj2 = new PrivateCon();
PrivateCon obj3 = new PrivateCon();
PrivateCon obj4 = new PrivateCon(5);
System.out.println("Instances Created By Default Cunstructor : " + count);
}
}
Output:

25
3350703_Java Programming Enrollment No

Practical – 13
Aim: Write a program in Java to demonstrate the use of 'final' keyword in
the field declaration. How it is accessed using the objects.
Ans:
class Bike {
final static int speed_limit = 90;
void run() {
System.out.println("Current Speed Limit of Bike is : " + speed_limit);
}
public static void main(String Args[]) {
Bike obj = new Bike();
obj.run();
System.out.println("Final Int Accessed By Object : obj.Speed_limit = " +
obj.speed_limit);
}
}
Output:

26
3350703_Java Programming Enrollment No

Practical – 14
Aim: Develop minimum 4 program based on variation in methods i.e.
passing by value, passing by reference, returning values and returning
objects from methods.
Ans:
• Passing by value
class p14_1 {
int data = 50;
void change(int data) {
this.data=data;
}
public static void main(String Args[]) {
p14_1 obj = new p14_1();
System.out.println("Before Change : " + obj.data);
obj.change(500);
System.out.println("After Change : " + obj.data);
}
}
• Passing by reference
class p14_2 {
int data = 50;
void change(p14_2 obj) {
this.data=this.data+1000;
}
public static void main(String Args[]) {
p14_2 obj = new p14_2();
System.out.println("Before Change : " + obj.data);
obj.change(obj);
System.out.println("After Change : " + obj.data);
}
}

27
3350703_Java Programming Enrollment No

• Returning values
class p14_3 {
int data = 50;
void set_data(int data) {
this.data=data;
}
int get_data() {
return this.data;
}
public static void main(String Args[]) {
p14_3 obj = new p14_3();
int data;
obj.set_data(500);
data = obj.get_data();
System.out.println("Returned Data : " + data);
}
}
• Returning objects from methods
class p14_4 {
int data = 50;
void set_data(int data) {
this.data=data;
}
p14_4 get_obj() {
p14_4 obj = new p14_4();
obj.set_data(450);
return obj;
}
public static void main(String Args[]) {
p14_4 obj = new p14_4();
p14_4 obj2;
obj2 = obj.get_obj();

28
3350703_Java Programming Enrollment No

System.out.println("Object 2's data : " + obj2.data);


}
}
Output:

29
3350703_Java Programming Enrollment No

Practical – 15
Aim: Write a program in Java to demonstrate single inheritance, multilevel
inheritance and hierarchical inheritance.
Ans:

• Single inheritance
class A {
public void methodA() {
System.out.println("Base Class Method.");
}
}
class B extends A {
public void methodB() {
System.out.println("Child Class Method.");
}
public static void main( String Args[] ) {
B obj = new B();
obj.methodA();
obj.methodB();
}
}

• Multilevel inheritance
class X {
public void methodX() {
System.out.println("Base Class X Method.");
}
}
class Y extends X {
public void methodY() {
System.out.println("Child Class Y Derived From X");
}
}
class Z extends Y {

30
3350703_Java Programming Enrollment No

public void methodZ() {


System.out.println("Child Class Z Derived From Y");
}
public static void main( String Args[] ) {
Z obj = new Z();
obj.methodX();
obj.methodY();
obj.methodZ();
}
}

• Hierarchical inheritance
class P{
public void methodP(){
System.out.println("Base Class Created...");
}
}
class Q extends P{
public void methodQ(){
System.out.println("Class Q Derived From Main Class P");
}
}
class R extends P{
public void methodR(){
System.out.println("Class R Derived From Main Class P");
}
}
class S extends Q{
public void methodS() {
System.out.println("Class S Derived from derived class Q");
}
}
class T extends Q {

31
3350703_Java Programming Enrollment No

public void methodT() {


System.out.println("Class T Derived from derived class Q");
}
}
class Test {
public static void main( String Args[] ) {
R robj = new R();
S sobj = new S();
T tobj = new T();
robj.methodP();
robj.methodR();
sobj.methodQ();
sobj.methodS();
tobj.methodT();
}
}

Output:

32
3350703_Java Programming Enrollment No

Practical – 16
Aim: Create a class to find out whether the given year is leap year or not.
(Use inheritance for this program)
Ans:
import java.util.Scanner;
class A {
boolean is_leap=false;
String str="";
String Check_Year(int year){
if(year % 400 == 0){
is_leap = true;
}
else if (year % 100 == 0){
is_leap = false;
}
else if(year % 4 == 0){
is_leap = true;
}
else{
is_leap = false;
}
if(is_leap==true)
str="Leap Year.";
else
str="Non Leap Year.";
return str;
}
}
class Test extends A {
public static void main(String Args[]){
Scanner s = new Scanner(System.in);
Test obj = new Test();

33
3350703_Java Programming Enrollment No

String str="";
int year;
System.out.println("Enter Year : ");
year = s.nextInt();
str = obj.Check_Year(year);
System.out.println(str);
}
}
Output:

34
3350703_Java Programming Enrollment No

Practical – 17
Aim: Write a program in Java in which a subclass constructor invokes the
constructor of the super class and instantiate the values.
Ans:
class Base{
int val1,val2;
Base() {
val1=10;
val2=20;
}
void display() {
System.out.println("val 1 = " + val1);
System.out.println("val 2 = " + val2);
}
}
class Sub extends Base{
int val3;
Sub(){
super();
val3=30;
}
void display() {
super.display();
System.out.println("val 3 = " + val3);
}
}
class Test {
public static void main(String Args[]) {
Sub sub_obj = new Sub();
sub_obj.display();
}
}

35
3350703_Java Programming Enrollment No

Output:

36
3350703_Java Programming Enrollment No

Practical – 18
Aim: Write an application that illustrates method overriding in the same
package and different packages. Also demonstrate accessibility rules in
inside and outside packages.
Ans:

• MainClass.java
import java.util.*;
package p1;
public class MainClass {
protected int pro = 10;
int def = 20;
public void demo() {
System.out.println("Main Class Method Called...");
System.out.println(pro);
System.out.println(def);
}
public static void main(String Args[]) {
MainClass m1 = new MainClass();
m1.demo();
}
}

• p18_2.java
package p1;
class SamePkgSubClass extends MainClass {
public void demo() {
System.out.println("Same Package Sub Class Method Called...");
System.out.println(pro);
System.out.println(def);
}
public static void main(String Args[]) {
MainClass m1 = new SamePkgSubClass();
m1.demo();

37
3350703_Java Programming Enrollment No

}
}

• p18_3.java
package p2;
import p1.MainClass;
class OtherPkgSubClass extends MainClass {
public void demo() {
System.out.println("Package 2 Other Package Sub Class Method Called...");
System.out.println(pro);
//System.out.println(def); can not be accessed
}
public static void main(String Args[]) {
MainClass m1 = new OtherPkgSubClass();
m1.demo();
}
}
Output:

38
3350703_Java Programming Enrollment No

Practical – 19
Aim: Describe abstract class called Shape which has three subclasses say
Triangle, Rectangle, Circle. Define one method area()in the abstract class
and override this area() in these three subclasses to calculate for specific
object i.e. area() of Triangle subclass should calculate area of triangle etc.
Same for Rectangle and Circle.
Ans:

• Shape.java
package shape;
public abstract class Shape {
abstract public void area();
}

• Circle.java
package shape;
public class Circle extends Shape {
int r;
public Circle() {
r = 14;
}
public void area() {
double area;
area = 3.14 * (r*r);
System.out.println("Area of Circle = " + area);
}
}

• Triangle.java
package shape;
public class Triangle extends Shape {
int l,b;
public Triangle() {
l = b = 10;
}

39
3350703_Java Programming Enrollment No

public void area() {


double area;
area = (l * b) / 2;
System.out.println("Area of Triangle = " + area);
}
}

• Rectangle.java
package shape;
public class Rectangle extends Shape {
int l,b;
public Rectangle() {
l = b = 10;
}
public void area() {
double area;
area = l * b;
System.out.println("Area of Rectangle = " + area);
}
}

• p19.java
import shape.Circle;
import shape.Triangle;
import shape.Rectangle;
class Test{
public static void main(String Args[]) {
Circle c = new Circle();
Triangle t = new Triangle();
Rectangle r = new Rectangle();
c.area();
t.area();
r.area();

40
3350703_Java Programming Enrollment No

}
}
Output:

41
3350703_Java Programming Enrollment No

Practical – 20
Aim: Write a program in Java to demonstrate implementation of multiple
inheritance using interfaces.
Ans:
interface Parent1{
public void show();
}
interface Parent2{
public void show();
}
class Test implements Parent1, Parent2{
public void show(){
System.out.println("Hello Bro...");
}
public static void main(String Args[]) {
Test t = new Test();
t.show();
}
}
Output:

42
3350703_Java Programming Enrollment No

Practical – 21
Aim: Write a program in Java to demonstrate use of final class.
Ans:
final class FinalTest {
public void show() {
System.out.println("Hi, Brother...");
}
}
// To prevent Inheritance. So It’s an error
class Test extends FinalTest {
public static void main(String Args[]) {
Test t = new Test();
t.show();
}
}
Output:

43
3350703_Java Programming Enrollment No

Practical – 22
Aim: Write a program in Java to develop user defined exception for
'Divide by Zero' error.
Ans:
class MyCreatedException extends Exception {
MyCreatedException() {
toString();
}
public String toString() {
return "Hey, b is zero !!!"+" You Can Not Divide By Zero...";
}
}
class Test {
static void divide(int a, int b) throws MyCreatedException {
if(b==0) {
throw new MyCreatedException();
}
else {
System.out.println("Ans = " + a/b);
}
}
public static void main(String[] Args) {
try {
divide(Integer.parseInt(Args[0]), Integer.parseInt(Args[1]));
}
catch(MyCreatedException e) {
System.out.println(e);
}
}
}

44
3350703_Java Programming Enrollment No

Output:

45
3350703_Java Programming Enrollment No

Practical – 23
Aim: Write a program in Java to demonstrate multiple try block and
multiple catch exception.
Ans:

• MultipleTry.java
import java.util.*;
class MultipleTry {
public static void main(String Args[]) {
try {
try {
System.out.println("Going to Divide By Zero...");
int b = 20 / 0;
}
catch(ArithmeticException e) {
System.out.println("Ooops !!! " + e);
}
try {
System.out.println("Going to Overflow an Array...");
int a[] = new int[5];
a[5] = 10;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Ooops !!! " + e);
}
}
catch(Exception e) {
System.out.println("All Exceptions Handled...");
}
System.out.println("End.");
}
}

46
3350703_Java Programming Enrollment No

• MultipleCatch.java
class MultipleCatch {
public static void main(String Args[]) {
int num1 = 20;
int num2 = 0;
int ans = 0;
int a[] = new int[5];
try {
a[5] = 10;
ans = num1 / num2;
System.out.println("Ans : " + ans);
}
catch(ArithmeticException e) {
System.out.println("Ooops !! Error : Divid By Zero...");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Ooops !! Error : Array Out of Bound...");
}
System.out.println("End.");
}
}
Output:

47
3350703_Java Programming Enrollment No

Practical – 24
Aim: Write a program that executes two threads. One thread displays
“Thread1” every 2,000 milliseconds, and the other displays “Thread2”
every 4,000 milliseconds. Create the threads by extending the Thread class.
Ans:
class ThreadTest extends Thread {
ThreadTest(String s) {
super(s);
start();
}
public void run(){
for(int i=0; i<6; i++){
System.out.println(Thread.currentThread().getName());
try{
if(Thread.currentThread().getName() == "Thread1")
Thread.sleep(2000);
else
Thread.sleep(4000);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
class Test{
public static void main(String Args[]){
ThreadTest t1 = new ThreadTest("Thread1");
ThreadTest t2 = new ThreadTest("Thread2");
}
}

48
3350703_Java Programming Enrollment No

Output:

49
3350703_Java Programming Enrollment No

Practical – 25
Aim: Write a program in Java to create, write, modify, read operations on
a Text file.
Ans:
import java.util.*;
import java.io.*;
class FileTest{
public static void main(String Args[]){
File f = null;
boolean bool = false;
// File Creation...
{
try {
f = new File("D:\\Practicles\\test.txt");
bool = f.createNewFile();
System.out.println("File Created = " + bool);
f.delete();
bool = f.createNewFile();
System.out.println("File Created = " + bool);
}
catch(Exception e){
e.printStackTrace();
}
}
// Write to File...
{
try{
FileOutputStream fout = new FileOutputStream("test.txt");
String str = "Writing... Hey...";
byte b[] = str.getBytes();
fout.write(b);
fout.close();

50
3350703_Java Programming Enrollment No

System.out.println("Writting Complete !");


}
catch(Exception e){
System.out.println(e);
}
}
// Read From File...
{
try{
FileInputStream fin = new FileInputStream("test.txt");
int i;
while( (i=fin.read()) != -1)
System.out.print((char)i);
fin.close();
System.out.println("Reading Complete !");
}
catch(Exception e){
System.out.println(e);
}
}
// Modify the File...
{
try{
FileOutputStream fout = new FileOutputStream("test.txt");
String str = "Modifying... Bye...";
byte b[] = str.getBytes();
fout.write(b);
fout.close();
System.out.println("Modification Complete !");
}
catch(Exception e){
System.out.println(e);

51
3350703_Java Programming Enrollment No

}
}
System.out.println(" ");
System.out.println("End.");
}
}
Output:

Sign:

Date:

52

You might also like