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

Oops Lab Record

This document contains examples of Java programs related to solving a quadratic equation, generating Fibonacci series using recursive and non-recursive methods, counting number of objects using static variables, creating student objects using constructors, and demonstrating abstract classes. The document provides the aim, algorithm, program code, output and result for each example.

Uploaded by

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

Oops Lab Record

This document contains examples of Java programs related to solving a quadratic equation, generating Fibonacci series using recursive and non-recursive methods, counting number of objects using static variables, creating student objects using constructors, and demonstrating abstract classes. The document provides the aim, algorithm, program code, output and result for each example.

Uploaded by

SIVA.K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 1 SOLVING QUADRATIC EQUATION


Date:

AIM:
To write a java program that prints all real solutions of a quadratic equation. If there is no
real solution display the same.

ALGORITHM:
Step 1: Start
Step 2: Read a, b, c of a quadratic equation from the user.
Step 3: Compute d = (b*b)-4*a*c
Step 4: If d>=0, display (-b ± √d)/2a
Step 5: Else display no real roots.
Step 6: End

PROGRAM:
import java.util.*;
class Quadratic{
public static void main(String[] args){
double a, b, c, x1, x2, d;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the quadratic equation co-efficient a*x^2 + b*x
+c=0:");
System.out.print("a:"); a = scan.nextInt();
System.out.print("b:"); b = scan.nextInt();
System.out.print("c:"); c = scan.nextInt();
System.out.println("The quadratic equation is "+a+"*x^2+"+b+"*x+"+c+"=0.");
d=(b*b)-4*a*c;
if(d<0) System.out.println("No real Solution.");
else if(d==0){
System.out.println("Identical roots.");
x1= (-b - Math.sqrt(d))/(2*a);
System.out.println("x:"+x1);
}

St. Joseph’s College of Engineering 1


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

else{
System.out.println("Real roots.");
x1= (-b + Math.sqrt(d))/(2*a);
x2= (-b - Math.sqrt(d))/(2*a);
System.out.println("x1:"+x1);
System.out.println("x2:"+x2);
}
}
}

OUTPUT:
Enter the quadratic equation co-efficient a*x^2 + b*x +c =0:
a:1
b:2
c:1
The quadratic equation is 1.0*x^2 + 2.0*x +1.0=0.
Identical roots.
x:-1.0

RESULT:
Thus, a java program to find solution for quadratic equation is written, executed and
verified successfully.

St. Joseph’s College of Engineering 2


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 2A GENERATING FIBONACI SERIES (NON-RECURSIVE)


Date:

AIM:
To write a java program to print the nth Fibonacci number using a non-recursive function.

ALGORITHM:
Step 1: Start
Step 2: Read n from the user.
Step 3: Initialise a=0, b=1, c=1, counter=1.
Step 4: While counter<n
Step 4.1: Set c=a+b
Step 4.2: Set a=b
Step 4.3: Set b=c
Step 4.4: Increment counter
Step 5: Print c.
Step 6: End

PROGRAM:
import java.util.*;

class Fib{
int fib(int n){
int a,b,c,i;
a=0; b=1; c=1;
for(i=1;i<=n; i++){
c=a + b;
a=b; b=c;
}
return c;
}
public static void main(String[] args){
int n;
Scanner scan= new Scanner(System.in);

St. Joseph’s College of Engineering 3


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

System.out.print("Enter n to print nth element of fibonacci


series:");n=scan.nextInt();
System.out.println("The "+n+"th element of fibonacci series is: ");
Fib f=new Fib();
System.out.println(f.fib(n-1));
}
}

OUTPUT:
Enter n to print nth element of fibonacci series:10
The 10th element of fibonacci series is:
55

RESULT:
Thus, a java program to print nth Fibonacci series is written, executed and verified
successfully.

St. Joseph’s College of Engineering 4


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 2B GENERATING FIBONACI SERIES (RECURSIVE)


Date:

AIM:
To write a java program to print the nth Fibonacci number using a recursive function.

ALGORITHM:
Step 1: Start
Step 2: Read n from the user.
Step 3: Compute d = (b*b)-4*a*c
Step 4: Display fib(n)
Step 5: End
fib(n):
Step 1: Start
Step 2: Return 1 if n=1 or n =2
Step 3: Else return fib(n-1) + fib(n-2)
Step 4: Stop

PROGRAM:
import java.util.*;
class Fibonacci{
public static int fib(int n){
if(n==1||n==2) return 1;
else return fib(n-1)+fib(n-2);
}
public static void main(String[] args){
int n;
Scanner scan= new Scanner(System.in);
System.out.print("Enter n to print the nth value of fibonacci series:");
n=scan.nextInt();
System.out.println("The "+n+"th element of fibonacci series is: "+(fib(n)));
}
}

St. Joseph’s College of Engineering 5


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

OUTPUT:
Enter n to print the nth value of fibonacci series:10
The 10th element of fibonacci series is: 55

RESULT:
Thus, a java program to print nth Fibonacci series is written, executed and verified
successfully.

St. Joseph’s College of Engineering 6


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 3 COUNTING OBJECTS


Date:

AIM:
To write a java program that counts the number of objects created by using static variable
ALGORITHM:
Step 1: Start
Step 2: Initialise an integer variable count using static modifier.
Step 3: Create a constructor which increases the count value.
Step 4: In main method create as many objects.
Step 5: Display count.
Step 6: End
PROGRAM:
class ObjectCount{
static int count;
ObjectCount(){
count++;
}
public static void main(String[] args){
ObjectCount ob1= new ObjectCount();
ObjectCount ob2= new ObjectCount();
ObjectCount ob3= new ObjectCount();
ObjectCount ob4= new ObjectCount();
ObjectCount ob6= new ObjectCount();
System.out.println(count);
}
}
OUTPUT:
$ java ObjectCount
5
RESULT:
Thus, a java program to count number of objects is written, executed and verified
successfully.

St. Joseph’s College of Engineering 7


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 4 USING CONSTRUCTORS


Date:

AIM:
To write a java program to create n students with data hall ticket number, name and
department with n passed to constructor

ALGORITHM:
Step 1: Start
Step 2: Define a Student class with halltkt, name, dept, n.
Step 3: Constructor to get n.
Step 4: Create student array.
Step 5: For n students create student object and getDetails.
Step 6: Display details of n students.
Step 7: End

PROGRAM:
import java.util.*;
class Student{
int halltkt;
String name;
String dept;
int n;
Scanner sc = new Scanner(System.in);
Student(){}
Student(int n1){
n=n1;
}
Student[] s= new Student[5];
void getStudent(){
for(int i=0;i<n;i++){
s[i] = new Student();
System.out.println("Enter Hall Ticket Number:");
s[i].halltkt=sc.nextInt();

St. Joseph’s College of Engineering 8


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

System.out.println("Enter Name:");
s[i].name=sc.next();
System.out.println("Enter Department:");
s[i].dept=sc.next();
}
}
void displayStudent(){
for(int i=0;i<n;i++){
System.out.println("Hall Ticket Number:"+s[i].halltkt);
System.out.println("Name:"+s[i].name);
System.out.println("Department:"+s[i].dept);
}
}
}
class StudentRecords{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of Students:");
int N = sc.nextInt();
Student s1= new Student(N);
s1.getStudent();
s1.displayStudent();
}
}

OUTPUT:
Enter number of Students:
2
Enter Hall Ticket Number:
101
Enter Name:
abc
Enter Department:

St. Joseph’s College of Engineering 9


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

cse
Enter Hall Ticket Number:
102
Enter Name:
xyz
Enter Department:
ece
Hall Ticket Number:101
Name:abc
Department:cse
Hall Ticket Number:102
Name:xyz
Department:ece

RESULT:
Thus, a java program to make students class with n students is created, written, executed
and verified successfully.

St. Joseph’s College of Engineering 10


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 5 ABSTRACT CLASS


Date:

AIM:
To write a java program to demonstrate the use of abstract class and print number of sides of
shapes.

ALGORITHM:
Step 1: Start
Step 2: Create an abstract class Shape with abstract method noOfSides.
Step 3: Define class Triangle, Trapezoid, Hexagon extending from shape.
Step 4: Create a class with main method and call noOfSides for every shape to print number
of sides
Step 5: End

PROGRAM:
abstract class Shape{
abstract void numberOfSides();
}
class Triangle extends Shape{
void numberOfSides(){
System.out.println("A Triangle has 3 sides.");
}
}
class Trapezoid extends Shape{
void numberOfSides(){
System.out.println("A Trapezoid has 4 sides.");
}
}
class Hexagon extends Shape{
void numberOfSides(){
System.out.println("A Hexagon has 6 sides.");
}
}

St. Joseph’s College of Engineering 11


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

class ShapeSides{
public static void main(String[] args){
new Triangle().numberOfSides();
new Trapezoid().numberOfSides();
new Hexagon().numberOfSides();
}
}

OUTPUT:
A Triangle has 3 sides.
A Trapezoid has 4 sides.
A Hexagon has 6 sides.

RESULT:
Thus, a java program to implement abstract class is written executed and verified
successfully.

St. Joseph’s College of Engineering 12


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

INTERFACES
Exp.No : 6
Date :

AIM
To write a java program to demonstrate the interfaces.

ALGORITHM

1.Start
2.Create an interface stack with the empty stack operations.
3.Create a class fixed stack to implement the stack interface with fixed length stack.
4.Create a class dynamic to implement the stack interface with dynamic length stack.
5.Create a class to demonstrate the interface and classes.
6.Stop

PROGRAM

import java.util.*;

interface Stack{
void push();
void pop();
void display();
}

class FixedStack implements Stack{


private int top = -1;
int[] fstack = new int[5];
private Scanner sc = new Scanner(System.in);

public void push(){


if(top==fstack.length-1)
System.out.println("Stack Overflow");
else{
System.out.println("Enter Element:");
fstack[++top]=sc.nextInt();
}
}

public void pop(){


if(top==-1)
System.out.println("Stack Underflow");
else

St. Joseph’s College of Engineering 13


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

System.out.println("Deleted Element: "+fstack[top--]);


}

public void display(){


if(top==-1)
System.out.println("Stack Empty");
else{
System.out.println("Stack Elements:");
for(int i=top;i>=0;i--)
System.out.println(fstack[i]);
}
}}

class DynamicStack implements Stack{


private int top = -1;
int[] dstack;
Scanner sc = new Scanner(System.in);

DynamicStack(int size){
dstack = new int[size];
}
public void push(){
if(top==dstack.length-1)
System.out.println("Stack Overflow");
else{
System.out.println("Enter Element:");
dstack[++top]=sc.nextInt();
}
}
public void pop(){
if(top==-1)
System.out.println("Stack Underflow");
else
System.out.println("Deleted Element: "+dstack[top--]);
}

public void display(){


if(top==-1)
System.out.println("Stack Empty");
else{
System.out.println("Stack Elements:");
for(int i=top;i>=0;i--)
System.out.println(dstack[i]);
} }}

St. Joseph’s College of Engineering 14


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

class InterfaceDemo{
public static void main(String[] args){
int ch;
Scanner sc = new Scanner(System.in);

System.out.println("\n1.Fixed Stack\n2.Dynamic Stack");


ch = sc.nextInt();
if(ch==1){
FixedStack fstk = new FixedStack();
System.out.println("\n1.Push\n2.Pop\n3.Display");
while(true){
System.out.println("Enter your choice:");
ch = sc.nextInt();
switch(ch){
case 1: fstk.push();
break;

case 2: fstk.pop();
break;

case 3: fstk.display();
break;

case 4: break;

default: System.out.println("Invalid Input !!");


}

if(ch == 4)
break;
}
}
else{
System.out.println("Enter size:");
DynamicStack dstk = new DynamicStack(sc.nextInt());
System.out.println("\n1.Push\n2.Pop\n3.Display");
while(true){
System.out.println("Enter your choice:");
ch = sc.nextInt();
switch(ch){
case 1: dstk.push();
break;
case 2: dstk.pop();
break;

St. Joseph’s College of Engineering 15


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

case 3: dstk.display();
break;

case 4: break;

default: System.out.println("Invalid Input !!");


}
if(ch == 4)
break;
} } } }

OUTPUT

FIXED STACK

1.Fixed Stack
2.Dynamic Stack1
1.Push
2.Pop
3.Display
Enter your choice:
1
Enter Element:
5
Enter your choice:
1
Enter Element:
6
Enter your choice:
3
Stack Elements:
6
5
Enter your choice:
2
Deleted Element: 6
Enter your choice:
3
Stack Elements:
5
Enter your choice:
4

St. Joseph’s College of Engineering 16


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

DYNAMIC STACK
1.Fixed Stack
2.Dynamic Stack
2
Enter size:
3
1.Push
2.Pop
3.Display
Enter your choice:
1
Enter Element:
6
Enter your choice:
1
Enter Element:
9
Enter your choice:
3
Stack Elements:
9
6
Enter your choice:
1
Enter Element:
6
Enter your choice:
3
Stack Elements:
6
9
6
Enter your choice:
2
Deleted Element: 6
Enter your choice:
3
Stack Elements:
9.
6
Enter your choice:
4
RESULT
Thus the java program was written to demonstrate the interfaces.

St. Joseph’s College of Engineering 17


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 7 PACKAGES CREATION


Date:

AIM:
To demonstrate package creation and usage in java.

ALGORITHM:
Step 1: Start
Step 2: Create Square.java, Triangle.java, Circle.java with getDim() and getArea() methods.
Step 3: Create package shape with square, triangle and circle classes.
Step 4: Make Area.java with class Area to call the classes in package shape to calculate areas.
Step 5: End

PROGRAM:

Area.java
import shape.Square;
import shape.Triangle;
import shape.Circle;

class Area{
public static void main (String[] args){
Square s1 = new Square();
Triangle s2 = new Triangle();
Circle s3 = new Circle();

s1.getDim();
System.out.println("Area of Square = "+ s1.getArea() );

s2.getDim();
System.out.println("Area of Triangle = "+ s2.getArea() );

s3.getDim();
System.out.println("Area of Circle = "+ s3.getArea() );

St. Joseph’s College of Engineering 18


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

}
}

Triangle.java
package shape;
import java.util.Scanner;
public class Triangle{
double base, height;
public void getDim(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter base:");
base = sc.nextDouble();
System.out.print("Enter height:");
height = sc.nextDouble();
}
public double getArea(){
return base * height *0.5;
}
}
Square.java
package shape;
import java.util.Scanner;
public class Square{
double side;
public void getDim(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter side:");
side = sc.nextDouble();
}
public double getArea(){
return side * side;
}
}

St. Joseph’s College of Engineering 19


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Circle.java
package shape;
import java.util.Scanner;

public class Circle{


double radius;
public void getDim(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter radius:");
radius = sc.nextDouble();
}
public double getArea(){
return radius*radius*3.14;
}
}

OUTPUT:
Enter side:5
Area of Square = 25.0
Enter base:2
Enter height:3
Area of Triangle = 3.0
Enter radius:5
Area of Circle = 78.5

RESULT:
Thus, a java program to demonstrate use of packages is written, executed and verified
successfully.

St. Joseph’s College of Engineering 20


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 8 STRING HANDLING


Date:

AIM:
To write a java program to implement usage of String Buffer.

ALGORITHM:
Step 1: Start
Step 2: Create a new StringBuffer Object.
Step 3: Check its capacity using capacity()
Step 4: Get new input string from console.
Step 5: Append input sting after converting it to uppercase to the string buffer.
Step 6: Use reverse() to reverse the string buffer.
Step 7: Get new input string from the console and append to string buffer.
Step 8: Display string buffer.
Step 9: End

PROGRAM:
import java.util.*;
class StrBuffer{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
StringBuffer str = new StringBuffer();
System.out.println("The capacity of StringBuffer is "+str.capacity());
String input = new String();
System.out.println("Enter a string:"); input = sc.next();
str.append(input.toUpperCase());
str.reverse();
System.out.println("Reversed string: "+str);
System.out.println("Enter second string:"); input = sc.next();
str.append(input);
System.out.println("Appended string: "+str);
}
}

St. Joseph’s College of Engineering 21


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

OUTPUT:
The capacity of StringBuffer is 16
Enter a string:
hello
Reversed string: OLLEH
Enter second string:
worLd
Appended string: OLLEHworLd

RESULT:
Thus, a java program to implement String Buffer is written, executed and verified
successfully.

St. Joseph’s College of Engineering 22


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 9 WORD COUNT


Date:

AIM:
To write a java program that prints all real solutions of a quadratic equation. If there is no
real solution display the same.

ALGORITHM:
Step 1: Start
Step 2: Read string from the user.
Step 3: Split the string to list of words.
Step 4: For every word in list that is not null check every word after the word if it is equal. If
it is equal update the word as null and increase count
Step 5: Display the word along with count for every word.
Step 6: End

PROGRAM:

import java.util.*;
public class Frequency{
public static void main(String arg[]){
String now;
int i;
String s = new String();
Scanner sc = new Scanner(System.in);
s = sc.nextLine();
String words[] = s.split("\\s");
for( i=0;i<words.length;i++){
now = words[i];
if(now==null)
continue;
int count = 1;
for(int j=i+1;j<words.length;j++){
if (now.equals(words[j])){

St. Joseph’s College of Engineering 23


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

count= count+1;
words[j] = null;
}
}
System.out.println(now+ " - "+ count);
}
}
}
OUTPUT:
hello this is java java is good
hello - 1
this - 1
is - 2
java - 2
good – 1

RESULT:
Thus, a java program to count the frequency of words is written, executed and verified
successfully.

St. Joseph’s College of Engineering 24


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 10 EXCEPTION HANDLING

Date:

AIM:
To write a java program to implement a Queue using user defined exceptions.

ALGORITHM:
Step 1: Start
Step 2: Declare a queue array.
Step 3: Get choice from user.
Step 4: If insert, get number from user and insert at end of the queue
Step 5: If delete, increase the front value.
Step 6: If display, display the elements of the queue one by one.
Step 7: In case of underflow or overflow throw the custom exception created.
Step 7: End.

PROGRAM:
import java.lang.*;
import java.util.*;
class QueueError extends Exception
{
public QueueError(String msg)
{
super(msg);
}
}
class Que
{
private int size;
private int front = -1;
private int rear = -1;
private Integer[] queArr;
public Que(int size)
{
this.size = size;
queArr = new Integer[size];

St. Joseph’s College of Engineering 25


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

}
public void insert(int item) throws Exception,QueueError
{
try
{
if(rear == size-1)
{
throw new QueueError("Queue Overflow");
}
else if(front==-1)
{
rear++;
queArr[rear] = item;
front = rear;
}
else
{
rear++;
queArr[rear] = item;
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
public void delete() throws Exception,QueueError
{
try
{
if(front == -1)
{
throw new QueueError("Queue Underflow");
}
else if(front==rear)
{
System.out.println("\nRemoved "+queArr[front]+" fromQueue");
queArr[front] = null;
front--;

St. Joseph’s College of Engineering 26


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

rear--;
}
else
{
System.out.println("\nRemoved "+queArr[front]+" fromQueue");
queArr[front] = null;
for(int i=front+1;i<=rear;i++)
{
queArr[i-1]=queArr[i];
}
rear--;
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
public void display() throws Exception,QueueError
{
try
{
if(front==-1)
throw new QueueError("Queue is Empty");
else
{
System.out.print("\nQueue is: ");
for(int i=front;i<=rear;i++)
{
System.out.print(queArr[i]+"\t");
}
System.out.println();
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}

St. Joseph’s College of Engineering 27


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

}
class Main
{
public static void main(String[] args) throws Exception,QueueError
{
System.out.println("\n\n\tQueue test using Array\n\n");
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of Queue array: ");
int size = scan.nextInt();
Que que = new Que(size);
char ch;
try
{
while(true)
{
System.out.println("\n\n\tQueue operations \n");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit\n");
System.out.print("Enter your choice: ");
int choice = scan.nextInt();
switch(choice)
{
case 1: System.out.print("\nEnter integer number to insert:");
que.insert(scan.nextInt());
break;
case 2:que.delete();
break;
case 3:que.display();
break;
case 4:return ;
}
}
}
catch(QueueError qe)
{
qe.printStackTrace();
} }}

St. Joseph’s College of Engineering 28


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

OUTPUT:

RESULT:
Thus, a java program to implement a queue with user defined exceptions is written,
executed and verified successfully.

St. Joseph’s College of Engineering 29


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 11 FILE COPYING

Date:

AIM:
To write a java program to read copy content of one file to other by handling all file related
exceptions.

ALGORITHM:
Step 1: Start
Step 2: Get the source file and destination filenames from the user.
Step 3: Create 2 file objects with the files obtained from the user.
Step 4: Create a method called copyContent with two file objects as the arguments.
Step 5: Inside the method create an FileInputStream for the source file and FileOutputStream
for the destination file.
Step 6: Using a while loop with condition of the read data is not equal to –1 traverse
through the source file and write the data to the destination file.
Step 7: Call the method.
Step 8: End

PROGRAM:
import java.io.*;
import java.util.*;

public class CopyFromFileaToFileb {

public static void copyContent(File a, File b)


throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);

St. Joseph’s College of Engineering 30


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

try {
int n;
while ((n = in.read()) != -1) {
out.write(n);
}
}
finally {
if (in != null) {
in.close();
}

if (out != null) {
out.close();
}
}
System.out.println("File Copied");
}

public static void main(String[] args) throws Exception


{
Scanner sc = new Scanner(System.in);
System.out.println(
"Enter the source filename from where you have to read/copy :");
String a = sc.nextLine();
File x = new File(a);
System.out.println(
"Enter the destination filename where you have to write/paste :");
String b = sc.nextLine();
File y = new File(b);
copyContent(x, y);
} }

St. Joseph’s College of Engineering 31


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

OUTPUT:
Source File : sample.txt

Destination File : sample1.txt

RESULT:
Thus, a java program to copy content of one file to another by handling all file related
exceptions is written, executed and verified successfully.

St. Joseph’s College of Engineering 32


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 12 THREAD CREATION

Date:

AIM:
To write a java program to create 3 threads with the first thread displaying “Good Moring”
every 1 second, second thread displaying “Good Afternoon” every 2 second and third
thread displaying “Welcome” every 3 seconds.

ALGORITHM:
Step 1: Start
Step 2: Create a ChildThread class implementing Runnable.
Step 3: Print different texts when Thread name is given as argument to constructor with
different delays.
Step 4: Create three Threads in the main method.
Step 9: End

PROGRAM:
class ChildThread implements Runnable
{
Thread t;
ChildThread(String name)
{
t = new Thread(this, name);
t.start();
}
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
if(t.getName().equals("First Thread"))
{
Thread.sleep(1000);
System.out.println(t.getName()+": Good Morning");
}
else if(t.getName().equals("Second Thread"))
{
Thread.sleep(2000);
System.out.println(t.getName()+": Hello");
}

St. Joseph’s College of Engineering 33


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

else
{
Thread.sleep(3000);
System.out.println(t.getName()+": Welcome");
}
}
catch(InterruptedException e)
{
System.out.println(t.getName()+" is interrupted");
}
}
}
}
class ThreeThreads
{
public static void main(String args[])
{
ChildThread one = new ChildThread("First Thread");
ChildThread two = new ChildThread("Second Thread");
ChildThread three = new ChildThread("Third Thread");
}
}
OUTPUT:
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
Third Thread: Welcome
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
First Thread: Good Morning
Third Thread: Welcome
Second Thread: Hello
Second Thread: Hello
Third Thread: Welcome
Second Thread: Hello
Third Thread: Welcome
Third Thread: Welcome

RESULT:
Thus, a java program to create 3 threads with the first thread displaying “Good Moring”
every 1 second, second thread displaying “Good Afternoon” every 2 second and third
thread displaying “Welcome” every 3 seconds is written, executed and verified successfully.

St. Joseph’s College of Engineering 34


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

Ex. No: 13 WINDOW PROGRAMMING

Date:

AIM:
To write a java program to display a message on a window using awt package.

ALGORITHM:
Step 1: Start
Step 2: Create a Scanner class and get a character from the user.
Step 3: Create a new frame and a new label using the Frame and the Label class.
Step 4: If the input is ‘m’ or ‘M’ then using the setText method of the label set the
message to Good Morning.
Step 5: If the input is ‘A’ or ‘a’ then using the setText method of the label set the message to
Good Afternoon.
Step 6: If the input is ‘E’ or ‘e’ then using the setText method of the label set the message to
Good Evening.
Step 7: If the input is ‘N’ or ‘n’ then using the setText method of the label set the message to
Good Night.
Step 8: Add the label and set the frame size and set the visibilty to true.
Step 9: End

PROGRAM:
import java.awt.*;
import java.util.*;
public class Testawt{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Character: ");
char ch = sc.next().charAt(0);
Frame fm=new Frame();
Label lb = new Label();
if(ch=='M'|| ch=='m'){
lb.setText("Good Morning");

St. Joseph’s College of Engineering 35


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

}
else if(ch=='A'|| ch=='a'){
lb.setText("Good Afternoon");
}
else if(ch=='E'|| ch=='e'){
lb.setText("Good Evening");
}
else if(ch=='N'|| ch=='n'){
lb.setText("Good Night");
}
fm.add(lb);
fm.setSize(300, 300);
fm.setVisible(true);
}
}
OUTPUT:
Enter a Character: m

RESULT:
Thus, a java program to display a message on a window using awt package is written,
executed and verified successfully.

St. Joseph’s College of Engineering 36


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

SWING PROGRAMMING

Exp.No : 14

Date :

AIM

To write a java program to create a simple GUI program using swing package.

ALGORITHM

1. Start.
2. Create a class GuiDemo that extends the JFrame class from swing with two
JTextField objects t1 and t2, JButton object b1 as their members.
3. Initiate the members in the constructor and set their bounds.
4. Add the members to the JFrame.
5. Add an action listener to button b1.
6. Overload the paint method to draw the text in t1 and t2.
7. Set the frame's layout to null and make the frame visible.
8. Create an object of the class GuiDemo
9. Stop.

PROGRAM

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class GuiDemo extends JFrame {

JTextField t1;

JTextField t2;

JButton b1;

public GuiDemo() {

super("GUI Demo");

St. Joseph’s College of Engineering 37


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

t1 = new JTextField(10);

t2 = new JTextField(10);

b1 = new JButton("Display");

t1.setBounds(50, 50, 150, 20);

t2.setBounds(50, 100, 150, 20);

b1.setBounds(50, 150, 100, 30);

add(t1);

add(t2);

add(b1);

b1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

paint(getGraphics());

});

setLayout(null);

setSize(300, 300);

setVisible(true);

public void paint(Graphics g) {

g.drawString(t1.getText(), 50, 50);

g.drawString(t2.getText(), 50, 75);

public static void main(String[] args) {

new GuiDemo();

St. Joseph’s College of Engineering 38


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

OUTPUT

RESULT

Thus the java program to create a simple GUI program using swing was written and
executed successfully.

St. Joseph’s College of Engineering 39


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

SOCKET PROGRAMMING
Exp.No : 15
Date :

AIM
To write a java program that executes Remote Command using TCP socket.

ALGORITHM

CLIENT SIDE
1. Establish a connection between the Client and Server.
Socket client=new Socket("127.0.0.1",6555);

2. Create instances for input and output streams.


Print Stream ps=new Print Stream(client.getOutputStream());

3. BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));

4. Enter the command in Client Window.


Send themessage to its output
str=br.readLine(); ps.println(str);

SERVER SIDE

1. Accept the connection request by the client.


ServerSocket server=new ServerSocket(6555); Sockets=server.accept();

2. Getthe IPaddressfromitsinputstream.
BufferedReaderbr1=newBufferedReader(newInputStreamReader(s.getInputStream()));
ip=br1.readLine();

3. During runtime execute the process


Runtime r=Runtime.getRuntime();
Process p=r.exec(str);

CLIENT PROGRAM

import java.io.*;
import java.net.*;
class clientRCE
{
public static void main (String args[]) throws IOException
{
try

St. Joseph’s College of Engineering 40


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

{
String str;
Socket client = new Socket ("127.0.0.1", 6555);
PrintStream ps = new PrintStream (client.getOutputStream ());
BufferedReader br =
new BufferedReader (new InputStreamReader (System.in));
System.out.println ("\t\t\t\tCLIENT WINDOW\n\n\t\tEnter TheCommand:");
str = br.readLine ();
ps.println (str);
}
catch (IOException e)
{
System.out.println ("Error" + e);
}
}
}

SERVER PROGRAM

import java.io.*;
import java.net.*;
class serverRCE
{
public static void main (String args[]) throws IOException
{
try
{
String str;
ServerSocket server = new ServerSocket (6555);
Socket s = server.accept ();
BufferedReader br = new BufferedReader (new InputStreamReader (s.getInputStream
()));
str = br.readLine ();
System.out.println ("The Command is : " + str);
Runtime r = Runtime.getRuntime ();
Process p = r.exec(str);
}
catch (IOException e)
{
System.out.println ("Error" + e);
}
}
}

St. Joseph’s College of Engineering 41


CS1308- Object Oriented Programming Laboratory Department of CSE 2022-2023

OUTPUT

C:\NetworkingPrograms>java serverRCE
C:\NetworkingPrograms>java clientRCE

CLIENT WINDOW
EnterTheCommand:
gedit

RESULT
Thus a java program that executes Remote Command using TCP socket was written
and executed successfully.

St. Joseph’s College of Engineering 42

You might also like