0% found this document useful (0 votes)
33 views46 pages

Java Lab BSC II Year

The document outlines various Java programming exercises, including sorting numbers using arrays, implementing find and replace operations, creating a calculator with constructors, calculating student percentages and grades using command line arguments, drawing shapes using polymorphism and inheritance, demonstrating multiple inheritance with interfaces, managing threads, and developing an applet for playing audio clips with multithreading. Each exercise includes an aim, algorithm, Java code, and a result indicating successful execution. The exercises cover fundamental programming concepts and practical applications in Java.

Uploaded by

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

Java Lab BSC II Year

The document outlines various Java programming exercises, including sorting numbers using arrays, implementing find and replace operations, creating a calculator with constructors, calculating student percentages and grades using command line arguments, drawing shapes using polymorphism and inheritance, demonstrating multiple inheritance with interfaces, managing threads, and developing an applet for playing audio clips with multithreading. Each exercise includes an aim, algorithm, Java code, and a result indicating successful execution. The exercises cover fundamental programming concepts and practical applications in Java.

Uploaded by

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

EX. NO.

: 01
DATE:
TO SORT GIVEN NUMBERS USING ARRAYS
AIM:
To write a program for sorting a given numbers using array.
ALGORITHM:
STEP – 1: To start a java program.
STEP – 2: Open the notepad and import the packages java.util.Arrays.
STEP – 3: To create a class named as ArraySortExample and to call an array
using Array.sort.
STEP – 4: To save the file using ArraySortExample.java
STEP – 5: To open the command prompt of compilation.
STEP – 6: To compile the program using the command javac
ArraySortExample.java
STEP – 8: To run the program using the command java ArraySortExample
STEP – 9: close the program and exit.
1. TO SORT GIVEN NUMBERS USING ARRAYS

// ArraySortExample.java
import java.util.Arrays;

public class ArraySortExample {


public static void main(String[] args) {
// Replace these numbers with your own array
int[] numbers = {5, 2, 8, 1, 6, 3};

// Call the sort method from Arrays class


Arrays.sort(numbers);

// Print the sorted array


System.out.println("Sorted Numbers: " + Arrays.toString(numbers));
}
}
OUTPUT:

RESULT:
Thus, the above java program is successfully executed.
Ex. No.:02
Date:
TO IMPLEMENT THE FIND AND REPLACE OPERATION IN THE
GIVEN TEXT
AIM:
To write a java program to find and replace operation in the given text.
ALGORITHM:
STEP – 1: To start a java program.
STEP – 2: Open the notepad and import the packages java.util.Scanner.
STEP – 3: To create a class named as FindReplaceProgram.
STEP – 4: To save the file named as FindReplaceProgram.java
STEP – 5: To open the command prompt for compilation.
STEP – 6: To compile the program using the command javac
FindReplaceProgram.java
STEP – 7: To run the program using the command java FindReplaceProgram
STEP – 8: close the program and exit.
2. TO IMPLEMENT THE FIND AND REPLACE OPERATION IN
THE GIVEN TEXT

// FindReplaceProgram.java
import java.util.Scanner;

public class FindReplaceProgram {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input text
System.out.println("Enter the text:");
String inputText = scanner.nextLine();

// Input find string


System.out.println("Enter the string to find:");
String findString = scanner.nextLine();

// Input replace string


System.out.println("Enter the replacement string:");
String replaceString = scanner.nextLine();

// Perform find and replace


String resultText = findAndReplace(inputText, findString, replaceString);

// Display the result


System.out.println("Result after find and replace:");
System.out.println(resultText);
scanner.close();
}

private static String findAndReplace(String inputText, String findString, String


replaceString) {
// Use the replaceAll method for find and replace
return inputText.replaceAll(findString, replaceString);
}
}
OUTPUT:

RESULT:
Thus, the above java program is successfully executed.
EX.NO.:03
DATE:
TO IMPLEMENT A CALCULATOR TO PERFORM ARTHIMETIC
OPERATION, DOING WITH CONSTRUCTOR
AIM:
To write a java program for to implement a calculator to perform
arithmetic operation working with constructor.
ALGORITHM:
STEP – 1: To start a java program.
STEP – 2: Open the notepad and import the packages java.util.Scanner.
STEP – 3: To create a class named as CalculatorProgram.
STEP – 4: To save the file named as CalculatorProgram.java
STEP – 5: To open the command prompt for compilation.
STEP – 6: To compile the program using the command javac
CalculatorProgram.java
STEP – 7: To run the program using the command java CalculatorProgram
STEP – 8: close the program and exit.

3. TO IMPLEMENT A CALCULATOR TO PERFORM


ARTHIMETIC OPERATION, DOING WITH CONSTRUCTOR
// CalculatorProgram.java
import java.util.Scanner;

class Calculator {
private double result;

// Constructor
public Calculator() {
result = 0;
}

// Addition method
public void add(double num) {
result += num;
}

// Subtraction method
public void subtract(double num) {
result -= num;
}

// Multiplication method
public void multiply(double num) {
result *= num;
}

// Division method
public void divide(double num) {
if (num != 0) {
result /= num;
} else {
System.out.println("Cannot divide by zero.");
}
}

// Get the result


public double getResult() {
return result;
}
}

public class CalculatorProgram {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create a calculator object


Calculator calculator = new Calculator();

// Input first number


System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();

// Input operation (+, -, *, /)


System.out.print("Enter the operation (+, -, *, /): ");
char operation = scanner.next().charAt(0);

// Input second number


System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();

// Perform the operation based on user input


switch (operation) {
case '+':
calculator.add(num1);
break;
case '-':
calculator.subtract(num1);
break;
case '*':
calculator.multiply(num1);
break;
case '/':
calculator.divide(num1);
break;
default:
System.out.println("Invalid operation.");
}

// Display the result


System.out.println("Result: " + calculator.getResult());

scanner.close();
}
}
OUTPUT:
RESULT:
Thus, the above java program is successfully executed.
EX.NO.:04
DATE:
TO FIND STUDENT PERCENTAGE AND GRADE USING THE
COMMAND LINE ARGUMENTS
AIM:
To write a java program for to find student percentage and grade using
the command line arguments.
ALGORITHM:
STEP – 1: To start a java program.
STEP – 2: Open the notepad.
STEP – 3: To create a class named as StudentResult.
STEP – 4: To save the file named as StudentResult.java
STEP – 5: To open the command prompt for compilation.
STEP – 6: To compile the program using the command javac
StudentResult.java
STEP – 7: To run the program using the command java StudentResult
STEP – 8: close the program and exit.

4. TO FIND STUDENT PERCENTAGE AND GRADE USING THE


COMMAND LINE ARGUMENTS
// StudentResult.java
public class StudentResult {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java StudentResult <marks1> <marks2>
<marks3>");
return;
}

// Parse command line arguments as integers


int subject1 = Integer.parseInt(args[0]);
int subject2 = Integer.parseInt(args[1]);
int subject3 = Integer.parseInt(args[2]);

// Calculate total marks and percentage


int totalMarks = subject1 + subject2 + subject3;
double percentage = (double) totalMarks / 3;

// Display the percentage


System.out.println("Student Percentage: " + percentage + "%");

// Assign grade based on percentage


char grade;
if (percentage >= 90) {
grade = 'A';
} else if (percentage >= 80) {
grade = 'B';
} else if (percentage >= 70) {
grade = 'C';
} else if (percentage >= 60) {
grade = 'D';
} else {
grade = 'F';
}

// Display the grade


System.out.println("Student Grade: " + grade);
}
}

OUTPUT:
RESULT:
Thus, the above java program is successfully executed.

EX.NO.:05
DATE:
TO DRAW CIRCLE OR TRIANGLE OR SQUARE USING
POLYMORPHISM AND INHERITANCE
AIM:
To write a java program to draw circle or triangle or square using
polymorphism and inheritance.
ALGORITHM:
STEP – 1: To start a java program.
STEP – 2: Open the notepad and import packages java.util.scanner.
STEP – 3: To create a class named as DrawingProgram.
STEP – 4: To save the file named as DrawingProgram.java
STEP – 5: To open the command prompt for compilation.
STEP – 6: To compile the program using the command javac
DrawingProgram.java
STEP – 7: To run the program using the command java DrawingProgram
STEP – 8: close the program and exit.

5. TO DRAW CIRCLE OR TRIANGLE OR SQUARE USING


POLYMORPHISM AND INHERITANCE
// DrawingProgram.java
import java.util.Scanner;

// Shape class (Base class)


abstract class Shape {
abstract void draw();
}

// Circle class (Derived class)


class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle");
System.out.println(" *** ");
System.out.println(" * * ");
System.out.println(" * * ");
System.out.println(" *** ");
}
}

// Triangle class (Derived class)


class Triangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Triangle");
System.out.println(" * ");
System.out.println(" *** ");
System.out.println(" ***** ");
System.out.println(" ******* ");
}
}

// Square class (Derived class)


class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a Square");
System.out.println(" **** ");
System.out.println(" * * ");
System.out.println(" * * ");
System.out.println(" **** ");
}
}

public class DrawingProgram {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Choose a shape to draw: ");


System.out.println("1. Circle");
System.out.println("2. Triangle");
System.out.println("3. Square");

int choice = scanner.nextInt();

Shape shape;

switch (choice) {
case 1:
shape = new Circle();
break;
case 2:
shape = new Triangle();
break;
case 3:
shape = new Square();
break;
default:
System.out.println("Invalid choice");
return;
}

// Draw the selected shape using polymorphism


shape.draw();
scanner.close();
}
}

OUTPUT:
RESULT:
Thus, the above program is successfully verified.

EX.NO.:06
DATE:
TO IMPLEMENT MULTIPLE INHERITANCE CONCEPTS IN JAVA
USING INTERFACE
AIM:
To write a java program to implement multiple inheritance concepts in
java using interface, you can choose your own example for a company or an
educational institution or a general concept which requires the use of interface
to solve particular program.
ALGORITHM:
STEP – 1: To start a java program.
STEP – 2: Open the notepad.
STEP – 3: To create a class named as CompanayExample.
STEP – 4: To save the file named as CompanyExample.java
STEP – 5: To open the command prompt for compilation.
STEP – 6: To compile the program using the command javac
CompanyExample.java
STEP – 7: To run the program using the command java CompanyExample
STEP – 8: close the program and exit.

6. TO IMPLEMENT MULTIPLE INHERITANCE CONCEPTS IN


JAVA USING INTERFACE
// CompanyExample.java
// Base interface for all employees
interface Employee {
void work();
void getSalary();
}

// Interface for managers


interface Manager extends Employee {
void manageTeam();
}

// Interface for programmers


interface Programmer extends Employee {
void code();
}

// Concrete class representing an employee


class RegularEmployee implements Employee {
@Override
public void work() {
System.out.println("Performing regular work");
}

@Override
public void getSalary() {
System.out.println("Getting regular salary");
}
}

// Concrete class representing a manager


class ProjectManager implements Manager {
@Override
public void work() {
System.out.println("Managing projects");
}

@Override
public void getSalary() {
System.out.println("Getting manager's salary");
}

@Override
public void manageTeam() {
System.out.println("Managing a team of employees");
}
}

// Concrete class representing a programmer


class JavaProgrammer implements Programmer {
@Override
public void work() {
System.out.println("Writing Java code");
}

@Override
public void getSalary() {
System.out.println("Getting programmer's salary");
}

@Override
public void code() {
System.out.println("Coding in Java");
}
}

public class CompanyExample {


public static void main(String[] args) {
// Example usage of the interfaces and classes
RegularEmployee employee = new RegularEmployee();
ProjectManager manager = new ProjectManager();
JavaProgrammer programmer = new JavaProgrammer();

// Calling methods specific to each role


employee.work();
employee.getSalary();
manager.work();
manager.getSalary();
manager.manageTeam();
programmer.work();
programmer.getSalary();
programmer.code();
}
}
OUTPUT:
RESULT:
Thus, the above program is successfully verified.

EX.NO.:07
DATE:
TO CREATE THREADS AND PERFORM OPERATIONS LIKE START,
STOP, SUSPEND, RESUME
AIM:
To write a java program to create threads and perform operations like
start, stop, suspend and resume.
ALGORITHM:
STEP – 1: To start a java program.
STEP – 2: Open the notepad.
STEP – 3: To create a class named as ThreadOperationsExample.
STEP – 4: To save the file named as ThreadOperationsExample.java
STEP – 5: To open the command prompt for compilation.
STEP – 6: To compile the program using the command javac
ThreadOperationsExample.java
STEP – 7: To run the program using the command java
ThreadOperationsExample.
STEP – 8: close the program and exit.

7. TO CREATE THREADS AND PERFORM OPERATIONS LIKE


START, STOP, SUSPEND, RESUME
// ThreadOperationsExample.java
class MyThread extends Thread {
private boolean suspended = false;

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {
System.out.println("Thread: " + i);
Thread.sleep(1000);

synchronized (this) {
while (suspended) {
wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

synchronized void mySuspend() {


suspended = true;
}

synchronized void myResume() {


suspended = false;
notify();
}
}

public class ThreadOperationsExample {


public static void main(String[] args) {
MyThread myThread = new MyThread();

// Start the thread


myThread.start();

try {
// Let the thread run for a while
Thread.sleep(3000);

// Suspend the thread


myThread.mySuspend();
System.out.println("Thread suspended.");

// Let the thread stay suspended for a while


Thread.sleep(3000);

// Resume the thread


myThread.myResume();
System.out.println("Thread resumed.");

// Wait for the thread to finish


myThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

OUTPUT:
RESULT:
Thus, the above program is successfully verified.

EX.NO.:08
DATE:
TO DEVELOP AN APPLET TO PLAY MUTLIPLE AUDIO CLIPS
USING MULTITHREADING
AIM:
To write a program to develop an java applet to play multiple audio clips
using multithreading.
ALGORITHM:
STEP - 1: To create a new folder.
STEP – 2: To write the java code and save the file the folder with named as
SoundApplet.java
STEP – 3: To write the html code and save the file in same folder with named
as SoundApplet.html
STEP – 4: To save any audio clip in the folder and rename the wav files as
sound.wav
STEP – 5: To open the folder in the visual studio and test the code.
STEP – 6: To open the terminal by right click on the folder and select the open
terminal options.
STEP - 7: Now to run the code type javac SoundApplet.java
STEP – 8: Then type appletviewer SoundApplet.html
STEP – 9: Now the output will be displayed.
STEP – 10: Stop and exit the program.

8. TO DEVELOP AN APPLET TO PLAY MUTLIPLE AUDIO CLIPS


USING MULTITHREADING
// SoundApplet.java
// Java Program to play sound using Applet

// Importing necessary packages


import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// Defining the class


public class SoundApplet extends Applet implements ActionListener {

private AudioClip soundClip;


private Button playBtn;
private Button pauseBtn;
private Button restartBtn;
private Label status;

public void init(){


// Loading the audio clip (replace "sound.wav" with
// your sound file)
soundClip
= getAudioClip(getCodeBase(), "sound.wav");
// Setting up the layout manager to FlowLayout
setLayout(new FlowLayout());

// Creating the UI buttons for control


playBtn = new Button("Play");
pauseBtn = new Button("Pause");
restartBtn = new Button("Restart");

// Customizing the button look


Font buttonFont = new Font("Arial", Font.BOLD, 14);

playBtn.setFont(buttonFont);
pauseBtn.setFont(buttonFont);
restartBtn.setFont(buttonFont);
playBtn.setBackground(Color.GREEN);
pauseBtn.setBackground(Color.RED);
restartBtn.setBackground(Color.BLUE);
playBtn.setForeground(Color.WHITE);
pauseBtn.setForeground(Color.WHITE);
restartBtn.setForeground(Color.WHITE);

// Adding the action listeners to the buttons


playBtn.addActionListener(this);
pauseBtn.addActionListener(this);
restartBtn.addActionListener(this);

// Adding buttons and label to the applet window


add(playBtn);
add(pauseBtn);
add(restartBtn);

// Creating a label for sound preview


status = new Label("Sound Preview: Click 'Play'");

add(status);
}

public void actionPerformed(ActionEvent e){


if (e.getSource() == playBtn) {
if (soundClip != null) {

soundClip.play();
status.setText("Sound Preview: Playing");
}
}

else if (e.getSource() == pauseBtn) {


if (soundClip != null) {

soundClip.stop();
status.setText("Sound Preview: Paused");
}
}

else if (e.getSource() == restartBtn) {


if (soundClip != null) {
soundClip.stop();
soundClip.play();
status.setText("Sound Preview: Restarted");
}
}
}

SoundApplet.html
<!DOCTYPE html>
<html>
<head>
<title>Sound Applet</title>
</head>
<body>
<applet code="SoundApplet.class" width="300" height="300">
</applet>
</body>
</html>

OUTPUT:
RESULT:
Thus, the above program is executed successfully.

EX.NO.:09
DATE:
TO RETRIEVE EMPLOYEE DATA FROM A FILE
AIM:
To write a program to retrieve employee data from a file.
ALGORITHM:
STEP - 1: To create a new folder.
STEP – 2: To write the java code and save the file the folder with named as
EmployeeDataReader.java
STEP – 3: To write the html code and save the file in same folder with named
as employee_data.txt
STEP – 4: To open the command prompt for compilation.
STEP – 6: To compile the program using the command javac
EmployeeDataReader.java
STEP – 7: To run the program using the command java EmployeeDataReader.
STEP – 8: close the program and exit.

9. TO RETRIEVE EMPLOYEE DATA FROM A FILE


SAVE THE FILE AS employee_data.txt
101,John Smith,50000.0
102,Jane Doe,60000.0
103,Michael Johnson,75000.0
104,Emily Davis,55000.0
105,Robert Brown,80000.0

// EmployeeDataReader.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class EmployeeDataReader {

public static void main(String[] args) {


String fileName = "employee_data.txt"; // Change this to your file's name

try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;

while ((line = reader.readLine()) != null) {


// Split the line into employee data using comma as a separator
String[] employeeData = line.split(",");

// Assuming the format: ID,Name,Salary


int id = Integer.parseInt(employeeData[0]);
String name = employeeData[1];
double salary = Double.parseDouble(employeeData[2]);

// Process the employee data (you can customize this part)


System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: " + salary);
System.out.println("---------------");
}

reader.close();
} catch (IOException e) {
System.err.println("Error reading from the file: " + e.getMessage());
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.err.println("Error parsing employee data: " + e.getMessage());
}
}
}

OUTPUT:
RESULT:
Thus, the above program is executed successfully.

EX.NO:10
DATE:
TO RETRIEVE STUDENT DATA USING JDBC

AIM:
To write a program to retrieve student data using JDBC.

ALGORITHM:
STEP - 1: To Start the program.
STEP - 2: Import the packages sql.
STEP - 3: Create the class as MysqlCon
STEP - 4: Register the JDBC connection.
STEP - 5: Create a connection and give username and password as parameters.
STEP - 6: Create a statement object.
STEP - 7: Create a ResultSet object.
STEP - 8: In the while loop get the row values of table one by one and print.
STEP - 9: Close the Connection
STEP - 10: Stop the program.

10.TO RETRIEVE STUDENT DATA USING JDBC


import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/student
","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from stud");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:
D:\Javaprog> javac

MysqlCon.java D:\Javaprog>

java MysqlCon

SELVA [email protected] 8090101020


KUMAR [email protected] 9999010131

RESULT:
Thus, the above program is successfully verified.

You might also like