Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

MUTHAYAMMAL ENGINEERING COLLEGE

(An Autonomous Institution)


(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna
University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu

DEPARTMENT OF INFORMATION TECHNOLOGY

LAB MANUAL

21ITC08 OBJECT ORIENTED PROGRAMMING


USING JAVA LABORATORY

NAME: _________________________________

YEAR/SEM/BRANCH: __________________

ROLL NUMBER: _______________________


Institution Vision and Mission
Vision

To be a Centre of Excellence in Engineering, Technology and Management on par


with International Standards.

Mission
 To prepare the students with high professional skills and ethical values
 To impart knowledge through best practices
 To instill a spirit of innovation through Training, Research and Development
 To undertake continuous assessment and remedial measures
 To achieve academic excellence through intellectual, emotional and social
stimulation

Department Vision and Mission

Vision

Excellence in Information Technology by offering quality technical education


providing to research and development

Mission

M1: Equip the students with high quality education and carrying out research in
emerging technologies in Information Technology
M2: Expose the students, faculty and staff to a globally competitive learning
experience
M3: Motivate the students to realize the responsibility of being professionally
proficient information technocrats to serve the society by inculcating Ethical and
Environmental aspects.
Program Educational Objectives (PEOs):

PEO1: Graduates will have successful career in IT and related industries or


pursue higher education and research or evolve as entrepreneurs.
PEO2: Graduates will have the ability and attitude to adapt emerging
technological changes in Information Technology.
PEO3: Graduates will excel as socially committed engineers with high ethical
values, leadership qualities and empathy for the needs of society.

Program Outcomes (POs):

PO1: Engineering Knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems
PO2: Problem Analysis: Identify, formulate, review research literature, and
analyze complex engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering sciences.
PO3: Design / Development Solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
PO4: Conduct Investigations of Complex Problems: Use research-based
knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid
conclusions
PO5: Modern Tool Usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate
the knowledge of, and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO9: Individual and Team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such as,
being able to comprehend and write effective reports and design documentation,
make effective presentations, and give and receive clear instructions.
PO11: Project Management and Finance Demonstrate knowledge and
understanding of the engineering and management principles and apply these to
one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
PO12: Lifelong Learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.

Program Specific Outcomes (PSOs):

PSO1: Excel in software development including mobile technologies to solve


complex computation task with soft skills.

PSO2: Apply appreciable knowledge of IoT, Cloud Computing and Cyber


Security to develop reliable IT solutions.

PSO3: Exhibit proficiency in Artificial Intelligence and Big Data Analytics for
providing solutions to real world problems in Industry and Research
establishments
Do’s and Dont’s in the Laboratory:

DO’s
 Know the location of the fire extinguisher and the first aid box and how to use
them in case of an emergency.
 Read and understand how to carry out an activity thoroughly before coming
to the laboratory.
 Report fires or accidents to your lecturer/laboratory technician immediately.
 Report any broken plugs or exposed electrical wires to your
lecturer/laboratory technician immediately.
 Shut down your computer, when you leave from the laboratory.

DON’Ts
 Do not eat or drink in the laboratory.
 Avoid stepping on electrical wires or any other computer cables.
 Do not open the system unit casing or monitor casing
 Do not insert metal objects such as clips, pins and needles into the computer
casings.
 Do not remove anything from the computer laboratory without permission.
 Do not touch, connect or disconnect any plug or cable without your
lecturer/laboratory technician’s permission.
 Do not misbehave in the computer laboratory
.
LIST OF EXPERIMENTS

PAGE
S.NO. DATE EXPERIMENT NAME SIGNATURE
NUMBER
EX. NO: 1(a)
SUM OF INTEGER ARGUMENTS USING COMMAND
DATE: LINE ARGUMENTS

AIM:

To write a Java program to compute all the sum of its integer arguments.

ALGORITHM:

1. Start the program.


2. Declare the array.
3. Read the integer values.
4. Calculate sum of all integers.
5. Display the sum.
6. Stop the program.

PROGRAM:

import java.io.*;
public class Sum
{
public static void main(String args[ ])
{
int a[]=new int[20];
int sum=0;
int j,temp,i;
for(i=0;i<args.length;i++)
{
a[i]=Integer.valueOf(args[i]);
}
for(i=0;i<args.length;i++)
{
sum=sum+a[i];
}
System.out.print(“Sum is:”+sum);
}
OUTPUT:

RESULT:
EX. NO: 1(b)
SORTING N INTEGERS USING
DATE: COMMAND LINE ARGUMENTS

AIM:

To write a Java program to input n integers and perform sorting between them.

ALGORITHM:

1. Start the program.


2. Declare the array of numbers.
3. Declare a temp variable.
4. Sort all the given numbers and display the sorted list.
5. Stop the program.

PROGRAM:
import java.io.*;
public class Sort
{
public static void main(String args[ ])
{
int a[]=new int[20];
int j,temp,i;
for(i=0;i<args.length;i++)
{
a[i]=Integer.valueOf(args[i]);
}
for(i=0;i<args.length;i++)
{
for(j=0;j<args.length-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("Sorted values:");

for(i=0;i<args.length;i++)
{
System.out.print(a[i]+” “);
}
}
}
OUTPUT:

RESULT:
EX. NO: 2(a)
PRINTING Nth VALUE OF FIBONACCI SERIES
DATE:

AIM:

To write a Java program to print the nth value of Fibonacci series.

ALGORITHM:

1. Start the program.


2. Initialize i,a=0,b=1,c=0,t.
3. Read the nth value.
4. Calculate and print the nth value of the series.
5. Stop the program.

PROGRAM:
import java.io.*;
import java.util.Scanner;
public class fib
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int i,a=0,b=1,c=0,t;
System.out.println("Enter value of t:");
t=input.nextInt();
System.out.print(a+" ");
System.out.print(b+" ");
for(i=0;i<t-2;i++)
{
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
}
System.out.println();
System.out.print(t+"th value of the series: "+c);
}
}
OUTPUT:

RESULT:
EX. NO: 2(b)
SUM OF INTEGER, DOUBLE VALUES AND
DATE: SUM OF FOUR INTEGERS

AIM:

To write a Java program to read test overloaded methods to find sum of three integers,
sum of three double values and sum of four integers.

ALGORITHM:

1. Start the program.


2. Declare a public class OverloadedSum().
3. Calculate the sum of a,b,c in sum(int a,int b,int c).
4. Calculate the double values double sum(double a,double b,double c).
5. Calculate the sum of four integers.
6. Stop the program.

PROGRAM:

public class OverloadedSum {


public static int sum(int a, int b, int c) {
return a + b + c;
}
public static double sum(double a, double b, double c) {
return a + b + c;
}
public static int sum(int a, int b, int c, int d) {
return a + b + c + d;
}
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
int d = Integer.parseInt(args[3]);
double x = Double.parseDouble(args[4]);
double y = Double.parseDouble(args[5]);
double z = Double.parseDouble(args[6]);
System.out.println("Sum of three integers: " + sum(a, b, c));
System.out.println("Sum of three doubles: " + sum(x, y, z));
}}
OUTPUT:

RESULT:
EX. NO: 2(c)
DISPLAY MARKS OF A STUDENT USING
DATE: CONSTRUCTOR

AIM:

To write a Java program to define a class student with name, reg number, marks of three
subjects and to print all the values.

ALGORITHM:

1. Start
2. Define a class Student(String name, int reg no, int mark1,int mark2,int mark3).
3. Describe a constructor to initialize them.
4. Define a method display() to print all the values.
5. Stop.

PROGRAM:
public class Student {
String name;
int regNo;
int marks1;
int marks2;
int marks3;
public Student(String name, int regNo, int marks1, int marks2, int marks3) {
this.name = name;
this.regNo = regNo;
this.marks1 = marks1;
this.marks2 = marks2;
this.marks3 = marks3;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Registration Number: " + regNo);
System.out.println("Marks in Subject 1: " + marks1);
System.out.println("Marks in Subject 2: " + marks2);
System.out.println("Marks in Subject 3: " + marks3);
}
OUTPUT:

RESULT:
EX. NO: 3
FIND REPETITION OF A NUMBER IN AN ARRAY
DATE:

AIM:

To write a Java program to print the element of an array that has occurred highest
number of times.

ALGORITHM:
1. Start the program.
2. Create an array of values.
3. Compare and find the most common elements in the array.
4. Print the most frequently occurred element.
5. Stop.

PROGRAM :

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class MostFrequentElement {
public static int mostFrequent(int[] arr) {
// Create a hash map to store the frequency of each element
Map<Integer, Integer> freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
// Find the most common element(s)
int maxFreq = 0;
int mostCommon = Integer.MAX_VALUE;
for (int num : arr) {
int currFreq = freq.get(num);
if (currFreq > maxFreq) {
maxFreq = currFreq;
mostCommon = num;
}}
return mostCommon;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 1, 2, 3, 4, 4, 4, 4};
int mostFrequent = mostFrequent(arr);
System.out.println("Most frequent element: " + mostFrequent);}}
OUTPUT:

RESULT:
EX. NO: 3(b)
FIND TOKENS, WORDS, CHARACTERS IN A STRING
DATE:

AIM:

To write a Java program to count number of tokens, words and characters in a string.

ALGORITHM:
1. Start.
2. Read the String using Scanner.
3. Count the number of words .
4. Count the number of Characters.
5. Stop.

PROGRAM :
import java.util.Scanner;
public class TokenCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
scanner.close();
// Counting number of words
int wordCount = 0;
boolean isWord = false;
for (char c : input.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
isWord = true;
} else if (isWord) {
wordCount++;
isWord = false;
}
}
if (isWord) {
wordCount++;
}
// Counting number of characters
int charCount = input.length();
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + charCount);
}
}
OUTPUT:

RESULT:
EX. NO: 4(A)
IMPLEMENT A CALCULATOR APPLICATION USING
DATE: SCANNER CLASS

AIM:

To write a Java application to implement calculator using scanner class.

ALGORITHM:

1. Start the program.


2. Get choice 1.Add 2.Subtract.
3. Read the numbers.
4. Perform operations based on the entered choice.
5. Get choice to continue or exit.
6. Stop the program.

PROGRAM:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isRunning = true;
while (isRunning) {
System.out.println("Menu:");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.println("Result: " + (num1 - num2));
break;
default:
System.out.println("Invalid choice!");
}
System.out.print("Do you want to continue? (y/n): ");
String input = scanner.next();
isRunning = (input.equalsIgnoreCase("y"));
}
scanner.close();
}
OUTPUT:

RESULT:
EX. NO: 4(B)
FIND NUMBER OF SIDES OF THE GIVEN
DATE: GEOMETRICAL FIGURE

AIM:

To write a Java program to print the number of sides in the given geometrical figure.

ALGORITHM:

1. Start the program.


2. Create an abstract class Shape with method
numberOfSlides().
3. Provide the classes Trapezoid,Triangle and
Hexagon inherited from Shape.
4. Print the number of sides in each geometry.
5. Stop the program.

PROGRAM:

abstract class Shape {


public abstract int numberOfSides();
}
class Trapezoid extends Shape {
public int numberOfSides() {
return 4;
}
}
class Triangle extends Shape {
public int numberOfSides() {
return 3;
}
}
class Hexagon extends Shape {
public int numberOfSides() {
return 6;
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape shape1 = new Trapezoid();
System.out.println("Number of sides in Trapezoid: " + shape1.numberOfSides());
Shape shape2 = new Triangle();
System.out.println("Number of sides in Triangle: " + shape2.numberOfSides());
Shape shape3 = new Hexagon();
System.out.println("Number of sides in Hexagon: " + shape3.numberOfSides());
}
}
OUTPUT:

RESULT:
EX. NO: 5(A)
CREATE AND ACCESS A VARIABLES AND METHODS
DATE: FROM USER DEFINED PACKAGE

AIM:

To write a Java program to import user-defined package and access member variables
and methods containing in the package.

ALGORITHM:

1. Start the program.


2. Create package P1.
3. Define member variables and methods in the package.
4. Import package P1.
5. Access all the member variables and methods containing in the package.
6. Stop.

PROGRAM:

// ClassA.java
package P1;
public class ClassA {
public int numA;
public ClassA(int numA) {
this.numA = numA;
}
public void methodA() {
System.out.println("Method A in ClassA");
}
}
// ClassB.java
package P1;
public class ClassB {
public String strB;
public ClassB(String strB) {
this.strB = strB;
}
public void methodB() {
System.out.println("Method B in ClassB");
}
}
import P1.*;
public class Main {
public static void main(String[] args) {
// Create objects of ClassA and ClassB
ClassA objA = new ClassA(42);
ClassB objB = new ClassB("Hello, world!");
// Access member variables of ClassA and ClassB
System.out.println("numA = " + objA.numA);
System.out.println("strB = " + objB.strB);
// Call methods of ClassA and ClassB
objA.methodA();
objB.methodB();
}
}
OUTPUT:

RESULT:
EX. NO: 5(B)
PERFORM INTEGER DIVISION WITH EXCEPTION
DATE: HANDLING

AIM:

To write a Java application using built in exception.

ALGORITHM:

1. Start the program.


2. Get inputs from the user.
3. Display division of num1 and num2 when divide button is clicked.
4. If they are not integers, throw a number format exception.
5. If 0, throw arithmetic exception.
6. Stop.

PROGRAM:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="DivApplet" width=350 height=300>
</applet>
*/
public class DivApplet extends JApplet implements ActionListener{
JTextField number1,number2,result;
JButton divide;
public void init(){
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
});
}
catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI(){
setLayout(new FlowLayout());
Label number1p = new Label("Number1: ",Label.RIGHT);
Label number2p = new Label("Number2: ",Label.RIGHT);
number1= new JTextField(20);
number2 = new JTextField(20);
result = new JTextField(20);
divide = new JButton("Divide");
add(number1p);
add(number1);
add(number2p);
add(number2);
add(result);
add(divide);
divide.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String snumber1,snumber2;
snumber1 = number1.getText();
snumber2 = number2.getText();
try{
int number1 = Integer.parseInt(snumber1);
int number2 = Integer.parseInt(snumber2);
if(number2==0)
JOptionPane.showMessageDialog(null, "Division by zero not defined.");
else{
double r = (double)number1/number2;
result.setText(((Double)r).toString());
}
}
catch(NumberFormatException ne)
{
JOptionPane.showMessageDialog(null,"Enter a number");
}
}
}
OUTPUT:

RESULT:
EX. NO: 6
CALCULATE STUDENTS MARK USING DRIVER CLASS
DATE:

AIM:

To write a Java application using user defined exception handling

ALGORITHM:

1. Start.
2. Create class Results extends Sports and Student.
3. It also has the interfaces.
4. Compute the final marks.
5. Stop.

PROGRAM:
Student.java
public class Student {
private String name;
private String rollNo;
public Student(String name, String rollNo) {
this.name = name;
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public String getRollNo() {
return rollNo;
}
}
Exam.java
public class Exam extends Student {
private int examMarks;
private int maxMarks;
public Exam(String name, String rollNo, int examMarks, int maxMarks) {
super(name, rollNo);
this.examMarks = examMarks;
this.maxMarks = maxMarks;
}
public int getExamMarks() {
return examMarks;
}
public int getMaxMarks() {
return maxMarks;
}
}
Sports.java
public interface Sports {
int getGraceMarks();
}
Results.java
public class Results extends Exam implements Sports {
private int sportsGraceMarks;
public Results(String name, String rollNo, int examMarks, int maxMarks, int
sportsGraceMarks) {
super(name, rollNo, examMarks, maxMarks);
this.sportsGraceMarks = sportsGraceMarks;
}
@Override
public int getGraceMarks() {
return sportsGraceMarks;
}
public int getTotalMarks() {
int totalMarks = examMarks + sportsGraceMarks;
return Math.min(totalMarks, getMaxMarks());
}
}
Driver.java
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter student name: ");
String name = scanner.nextLine();
System.out.print("Enter roll number: ");
String rollNo = scanner.nextLine();
System.out.print("Enter exam marks: ");
int examMarks = scanner.nextInt();
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter student name: ");
String name = scanner.nextLine();
System.out.print("Enter roll number: ");
String rollNo = scanner.nextLine();
System.out.print("Enter exam marks: ");
int examMarks = scanner.nextInt();
System.out.print("Enter maximum marks: ");
int maxMarks = scanner.nextInt();
System.out.print("Enter sports grace marks: ");
int sportsGraceMarks = scanner.nextInt();
Results results = new Results(name, rollNo, examMarks, maxMarks,
sportsGraceMarks);
System.out.println("Student Name: " + results.getName());
System.out.println("Roll Number: " + results.getRollNo());
System.out.println("Exam Marks: " + results.getExamMarks());
System.out.println("Maximum Marks: " + results.getMaxMarks());
System.out.println("Sports Grace Marks: " + results.getGraceMarks());
System.out.println("Total Marks: " + results.getTotalMarks());
scanner.close();
}
}
OUTPUT:

RESULT:
EX. NO: 7(A)
HANDLING ARITHMETIC EXCEPTION AND
DATE: ARRAY OUT OF BOUNDS EXCEPTION

AIM:

To write a Java program using I/O streams for handling arithmetic exception and
Array out of bounds exception

ALGORITHM:

1. Start
2. Read a file name.
3. Check whether the file exists or not
4. Display the details of the file whether the file is readable or writable, the
type of file and the length of the file in bytes.
5. Stop.

Program
import java.util.Scanner;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = {10, 20, 30};
try {
System.out.print("Enter the index of the element you want to access: ");
int index = scanner.nextInt();
int result = 100 / numbers[index];
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurred: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Out Of Bounds Exception occurred: " +
e.getMessage());
}
}
}
OUTPUT:

RESULT:
EX. NO: 7(B)
HANDLE USER-DEFINED EXCEPTION
DATE:

AIM:

To write a java program that implements user-defined exception.

ALGORITHM:
1. Start.
2. Create class Negative extends Exception.
3. Read number from the user.
4. If less than 0, throw Negative exception.
5. Stop.

PROGRAM:
import java.util.Scanner;
class Negative extends Exception {
public Negative() {
super("Negative number entered");
}
}
public class NegativeExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a positive number: ");
int number = scanner.nextInt();
if (number < 0) {
throw new Negative();
}
System.out.println("You entered: " + number);
} catch (Negative e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
OUTPUT 1:

OUTPUT 2:

RESULT:
EX. NO: 8(A)
IMPLEMENT MULTI–THREAD PROGRAMMING
DATE:

AIM:

To write a java program that implements multi-threading.

ALGORITHM:
1. Start the program.
2. Create three threads.
3. Display Good Morning, Hello and Welcome for each threads.
4. Stop the program.

PROGRAM:
public class MessageThreadDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new MessageThread("Good Morning", 1000));
Thread t2 = new Thread(new MessageThread("Hello", 2000));
Thread t3 = new Thread(new MessageThread("Welcome", 3000));
t1.start();
t2.start();
t3.start();
}
}
class MessageThread implements Runnable {
private String message;
private int interval;
public MessageThread(String message, int interval) {
this.message = message;
this.interval = interval;
}
@Override
public void run() {
while (true) {
try {
System.out.println(message);
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
OUTPUT :

RESULT:
EX. NO: 8(B)
SOLVING PRODUCER CONSUMER PROBLEM
DATE: USING INTER-THREAD COMMUNICATION

AIM:

To write a java program to solve producer consumer problem using inter-thread


communication.

ALGORITHM:
1. Start the program.
2. The producer should produce data only when the buffer is not full. In case it is
found that the buffer is full, the producer is not allowed to store any data into the
memory buffer.
3. Data can only be consumed by the consumer if and only if the memory buffer is
not empty. In case it is found that the buffer is empty, the consumer is not allowed
to use any data from the memory buffer.
4. Accessing memory buffer should not be allowed to producer and consumer at the
same time.
5. Stop the program.

PROGRAM:
import java.util.LinkedList;
public class ProducerConsumer {
LinkedList<Integer> buffer = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (this) {
while (buffer.size() == capacity) {
wait();
}
System.out.println("Producer produced-" + value);
buffer.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (buffer.size() == 0) {
wait();
}
int val = buffer.removeFirst();
System.out.println("Consumer consumed-" + val);
notify();
Thread.sleep(2000);
}
}
}
public static void main(String[] args) throws InterruptedException {
final ProducerConsumer pc = new ProducerConsumer();
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producerThread.start();
consumerThread.start();
producerThread.join();
consumerThread.join();
}
}
OUTPUT:

RESULT:
EX. NO: 8(C)
IMPLEMENT MULTITHREADING USING LAMBDA
DATE: EXPRESSION

AIM:

To write a java program to implement multithreading using lambda expression.

ALGORITHM:

1. Start.
2. Create and start the first thread using lambda expression.
3. Create and start the second thread using lambda expression.
4. Create and start the third thread using lambda expression
5. Print the result
6. Stop

PROGRAM:
public class MultithreadingLambda {
public static void main(String[] args) {
// Create and start the first thread using lambda expression
new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1 - " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
// Create and start the second thread using lambda expression
new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2 - " + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
// Create and start the third thread using lambda expression
new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 3 - " + i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
OUTPUT:

RESULT:
EX. NO: 9
HASHSET(COLLECTION FRAMEWORK)
DATE:

AIM:
To write a java program to create a HashSet object of type Book and adding instances
of the Book class into Hashset and Display them.

ALGORITHM:
1. Start the program.
2. Create a class book().
3. With instances name,id,author, publisher, and quantity.
4. Create constructor to initialize them.
5. Create hashset object of type book and three book instances b1,b2 and b3.
6. Add these instances into Hashset and display them
7. Stop the program.

PROGRAM:
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw
Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
OUTPUT:

RESULT:
EX. NO: 10(A)
SIMULATION OF TRAFFIC LIGHTS
DATE:

AIM:
To write a Java program that simulates a traffic light.
ALGORITHM:
1. Start.
2. Let the user select one of the 3 lights: red,yellow or green.
3. Turn on the light, when radio button is clicked.
4. Stop.

PROGRAM:

import java.awt.Color;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
class App extends JFrame implements ItemListener{
JFrame actualWindow;
JPanel messageContainer, lightsContainer;
JLabel message;
ButtonGroup btn_group;
JRadioButton rb_red, rb_yellow, rb_green;
App() {
Font myFont = new Font("Verdana",Font.BOLD, 30);
actualWindow = new JFrame("Traffic Lights");
messageContainer = new JPanel();
lightsContainer = new JPanel();
message = new JLabel("Select Light");
btn_group = new ButtonGroup();
rb_red = new JRadioButton("Red");
rb_yellow = new JRadioButton("Yellow");
rb_green = new JRadioButton("Green");
actualWindow.setLayout(new GridLayout(2, 1));
message.setFont(myFont);
rb_red.setForeground(Color.RED);
rb_yellow.setForeground(Color.YELLOW);
rb_green.setForeground(Color.GREEN);
btn_group.add(rb_red);
btn_group.add(rb_yellow);
btn_group.add(rb_green);
rb_red.addItemListener(this);
rb_yellow.addItemListener(this);
rb_green.addItemListener(this);
messageContainer.add(message);
lightsContainer.add(rb_red);
lightsContainer.add(rb_yellow);
lightsContainer.add(rb_green);
actualWindow.add(messageContainer);
actualWindow.add(lightsContainer);
actualWindow.setSize(300, 200);
actualWindow.setVisible(true);
}
@Override
public void itemStateChanged(ItemEvent ie) {
JRadioButton selected = (JRadioButton) ie.getSource();
String textOnButton = selected.getText();
if(textOnButton.equals("Red")) {
message.setForeground(Color.RED);
message.setText("STOP");
} else if(textOnButton.equals("Yellow")) {
message.setForeground(Color.YELLOW);
message.setText("READY");
} else {
message.setForeground(Color.GREEN);
message.setText("GO");
}
}
}
public class TrafficLight {
public static void main(String[] args) {
new App();
}
}
OUTPUT:

RESULT:
EX. NO: 10(B)
HANDLING MOUSE AND KEY EVENTS USING
DATE: ADAPTER CLASSES

AIM:
To write a java program that handles mouse and key events and shows the event name
at the center of the window when mouse is fired using adapter classes.
ALGORITHM:
1. Start the program.
2. Extend MouseEvent from JFrame inherits MouseListener.
3. Create constructor class.Set size, layout, visibility for the frame.
4. Implement all the methods of mouse and key events.
5. Stop the program.
PROGRAM:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}

OUTPUT:
RESULT:

You might also like