FAADIL_JAVA_LAB
FAADIL_JAVA_LAB
FAADIL_JAVA_LAB
COLLEGE OF ENGINEERING
(Autonomous college under VTU)
Bull Temple Rd, Basavanagudi, Bengaluru, Karnataka 560019
2023-2025
Department of Computer Applications
“JAVA PROGRAMMING”
(22MCA1PCJP)
By
Faadil Khaleel
(1BM23MC032)
LABORATORY CERTIFICATE
This is to certify that Faadil Khaleel (1BM23MC032) has satisfactorily Completed the
course of practical in “Java Programming - 22MCA2PCJP” Laboratory prescribed
by BMS College of Engineering (Autonomous college under VTU) 2nd Semester MCA
Course in this college during the year 2023-2024.
Examiner:
CONTENTS
1. a). Write a JAVA program to display default value of all primitive data type 5
of JAVA
b). Write a java program that display the roots of a quadratic equation
ax2+bx=0. Calculate the discriminate D and basing on value of D, describe
the nature of root.
c). Five Bikers Compete in a race such that they drive at a constant speed
which may or may not be the same as the other. To qualify the race, the speed
of a racer must be more than the average speed of all 5 racers. Take as input
the speed of each racer and print back the speed of qualifying racers.
d) Write a case study on public static void main (250 words)
2. a). Write a program to create a class named shape. In this class we have three 11
sub classes circle, triangle and square each class has two-member function
named draw () and erase (). Create these using polymorphism concepts.
b). Write a program to create a room class, the attributes of this class is room
no, room type, room area and AC machine. In this class the member functions
are set data and display data.
3. a). Write a program to create interface A in this interface we have two method 15
meth1 and meth2. Implements this interface in another class named My Class.
b). Write a program to create interface named test. In this interface the
member function is square. Implement this interface in arithmetic class.
Create one new class called ToTestInt in this class use the object of arithmetic
class.
c). Create an outer class with a function display, again create another class
inside the outer class named inner with a function called display and call the
two functions in the main class.
4. a). Write a JAVA program that creates threads by extending Thread class. 20
First thread display “Good Morning” every 1 sec, the second thread displays
“Hello” every 2 seconds and the third display “Welcome” every 3 seconds
(Repeat the same by implementing Runnable)
b). Write a program illustrating isAlive and join ()
7. a). Write a program to create a text file in the path c:\java\abc.txt and check 39
whether that file is exists. Using the command exists(), isDirectory(), isFile(),
getName() and getAbsolutePath().
b) Write a program to rename the given file, after renaming the file delete the
renamed file. (Accept the file name using command line arguments.)
c) Write a program to create a directory and check whether the directory is
created.
8. a). Write a program that can read a host name and convert it to an IP address 44
b). Write a Socket base java server program that responds to client messages
as follows: When it receives a message from client, it simply converts the
message into all uppercase letters and sends back to the client. Write both
client and server programs demonstrating this.
9. a). Create the classes required to store data regarding different types of 48
courses that employees in a company can enroll for. All courses have name
and course fee. Courses are also either classroom delivered or delivered
online. Courses could also be full time or part time. The program must enable
the course coordinator to register employees for courses and list out
employees registered for specific courses.
b). Write a java program in to create a class Worker. Write classes Daily
Worker and SalariedWorker that inherit from Worker. Every worker has a
name and a salaryrate. Write method Pay (int hours) to compute the week pay
of every worker. A Daily worker is paid on the basis of the number of days
she/he works. The salaried worker gets paid the wage for 40 hours a week no
matter what the actual hours are. Test this program to calculate the pay of
workers.
1.a)Write a JAVA program to display default value of all primitive data type of JAVA
OutPut:
b.)Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the discriminate D
and basing on value of D, describe the nature of root.
import java.util.Scanner;
class quadraticEquation{
public static void solve(double a, double b, double c) { double d = b * b - 4 * a * c;
if (d > 0) {
double root1 = (-b + Math.sqrt(d)) / (2 * a);
double root2 = (-b - Math.sqrt(d)) / (2 * a);
System.out.println("The roots are real and distinct."); System.out.println("Root 1 = " + root1);
System.out.println("Root 2 = " + root2);
} else if (d == 0) {
double root = -b / (2 * a);
System.out.println("The root is real (equal roots).");
System.out.println("Root = " + root);
} else {
System.out.println("The roots are complex .");
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-d) / (2 * a);
System.out.println("Root 1 = " + realPart + " + " + imaginaryPart + "i"); System.out.println("Root 2 = " +
realPart + " - " + imaginaryPart + "i"); }
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of coefficient a:");
double a = scanner.nextDouble();
System.out.println("Enter the value of coefficient b:");
double b = scanner.nextDouble();
System.out.println("Enter the value of coefficient c:");
double c = scanner.nextDouble();
solve(a, b, c);
}
}
outPut:
1.c)Five Bikers Compete in a race such that they drive at a constant speed which may or may not be the same
as the other. To qualify the race, the speed of a racer must be more than the average speed of all 5 racers. Take
as input the speed of each racer and print back the speed of qualifying racers.
import java.util.Scanner;
class Bikers
{
public static void main(String args[ ])
{
float S1,S2,S3,S4,S5;
float AvgSpeed;
Scanner sc = new Scanner(System.in);
System.out.println(" Enter Speed of five Bike Racer");
S1 = sc.nextInt();
S2 = sc.nextInt();
S3 = sc.nextInt();
S4 = sc.nextInt();
S5 = sc.nextInt();
AvgSpeed=(S1+S2+S2+S3+S4+S5)/5;
if( S1>AvgSpeed)
System.out.println("The Speed of Qualifying Racer is"+S1);
if( S2>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S2);
if( S3>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S3);
if( S4>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S4);
if( S5>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S5);
}
}
OutPut:
In Java, the public static void main method is the entry point of a Java program. It is the starting point
where the program begins execution. In this case study, we will explore the significance of public
static void main and its role in Java programming.
Best Practices
When writing a public static void main method, it is essential to follow best practices to ensure that
the program is executed correctly. These include:
• Declaring the method as public and static to make it accessible from outside the class.
• Using the void return type to indicate that the method does not return any value.
• Providing a clear and concise name for the method, such as main.
• Keeping the method short and focused on initializing the program.
Conclusion
In conclusion, public static void main is a critical component of Java programming, providing a single
entry point for the JVM to start executing the program. By following best practices and understanding
the role of public static void main, developers can write efficient and effective Java programs.
2.a)Write a program to create a class named shape. In this class we have three sub classes circle, triangle and
square each class has two member function named draw () and erase (). Create these using polymorphism
concepts.
class shape{
void draw(){
System.out.println("Drawing Shape");
}
void erase(){
System.out.println("erasing Shape");
}
}
void erase(){
System.out.println("erasing Circle");
}
}
void erase(){
System.out.println("erasing Triangle");
}
}
class Square extends shape{
void draw(){
System.out.println("Drawing Square");
}
void erase(){
System.out.println("erasing Square");
}
}
class shapemain{
public static void main(String args[]){
shape c=new Circle();
shape t=new Triangle();
shape s=new Square();
c.draw();
c.erase();
t.draw();
t.erase();
s.draw();
s.erase();
}
}
Output:
2.b)Write a program to create a room class, the attributes of this class is roomno, roomtype, roomarea and AC
machine. In this class the member functions are setdata and displaydata.
class Room {
int roomno;
String roomtype;
double roomarea;
boolean hasAC;
public void setdata(int roomno, String roomtype, double roomarea, boolean hasAC) {
this.roomno = roomno;
this.roomtype = roomtype;
this.roomarea = roomarea;
this.hasAC = hasAC;
}
room1.displaydata();
}
}
Output:
3.a)Write a program to create interface A in this interface we have two method meth1 and meth2. Implements
this interface in another class named MyClass.
interface interfaceA{
void meth1();
void meth2();
}
OutPut:
3 b)Write a program to create interface named test. In this interface the member function is square. Implement
this interface in arithmetic class. Create one new class called ToTestInt in this class use the object of arithmetic
class.c). Create an outer class with a function display, again create another class inside the outer class named
inner with a function called display and call the two functions in the main class.
import java.util.Scanner;
interface Test {
int square(int num);
}
class ToTestInt {
Arithmetic arithmetic = new Arithmetic();
class Outer {
void display() {
System.out.println("Outer display method");
class Inner {
void display() {
System.out.println("Inner display method");
}
}
Inner inner = new Inner();
Department of Computer Applications, BMSCE 17
22MCA2PCJP: Java Programming
inner.display();
}
}
OutPut:
3.c). Create an outer class with a function display, again create another class inside the outer class
named inner with a function called display and call the two functions in the main class.
class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
public class innerouter {
public static void main(String[] args) {
Outer outer = new Outer();
outer.display();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
4.a)Write a JAVA program that creates threads by extending Thread class .First thread display “Good Morning
“every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome” every 3
seconds ,(Repeat the same by implementing Runnable)
System.out.println("Welcome");
Thread.sleep(3000); // Sleep for 3 seconds
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
t1.start();
t2.start();
t3.start();
}
}
}
}
t1.start();
t2.start();
t3.start();
}
}
OutPut:
t1.start();
t2.start();
try {
t1.join(); // Main thread waits for t1 to finish
t2.join(); // Main thread waits for t2 to finish
} catch (InterruptedException e) {
System.out.println(e);
}
OutPut:
5.a)Write a Java program to perform employee payroll processing using packages. In the java file, Emp.java
creates a package employee and creates a class Emp. Declare the variables name,empid, category, bpay, hra,da,
npay, pf, grosspay, incometax, and allowance. Calculate the values in methods. Create another java file
Emppay.java. Create an object e to call the methods to perform and print values.
// File: Emp.java
package employee;
// Constructor
public Emp(String name, int empid, String category, double bpay) {
this.name = name;
this.empid = empid;
this.category = category;
this.bpay = bpay;
}
// File: Emppay.java
import employee.Emp;
e.calculateAllowances();
5.b)Write a Package MCA which has one class Student. Accept student detail through parameterized
constructor. Write display () method to display details. Create a main class which will use package and
calculate total marks and percentage.
// File: MCA/Student.java
package MCA;
// Parameterized constructor
public Student(String name, int rollNo, int[] marks) {
this.name = name;
this.rollNo = rollNo;
this.marks = marks;
}
// File: MainClass.java
import MCA.Student;
OUTPUT:
6)a)Write a complex program to illustrate how the thread priorities? Imagine that the first thread has just begun
to run, even before it has a chance to do anything. Now comes the higher priority thread that wants to run as
well. Now the higher priority thread has to do its work before the first thread starts.
class PriorityThreadExample {
public static void main(String[] args) {
// Creating the first thread (lower priority)
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 1 is running...");
try {
Thread.sleep(1000); // Simulating work by sleeping for 1 second
} catch (InterruptedException e) {
System.out.println("Thread 1 was interrupted.");
}
}
System.out.println("Thread 1 has finished.");
}
});
});
b)Write a Java program that implements producer consumer problem using the concept of inter thread
communication.
import java.util.LinkedList;
import java.util.Queue;
class ProducerConsumerExample {
producerThread.start();
consumerThread.start();
}
}
class Buffer {
private Queue<Integer> queue;
private int capacity;
queue.add(value);
System.out.println("Produced: " + value);
// Producer class that will produce items and add them to the buffer
class Producer implements Runnable {
private Buffer buffer;
@Override
public void run() {
int value = 0;
try {
while (true) {
buffer.produce(++value); // Produce an item
Thread.sleep(500); // Simulate time to produce the item
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@Override
public void run() {
try {
while (true) {
buffer.consume(); // Consume an item
Thread.sleep(1000); // Simulate time to consume the item
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Department of Computer Applications, BMSCE 37
22MCA2PCJP: Java Programming
7)a)Write a program to create a text file in the path c:\java\abc.txt and check whether that file is exists. Using
the command exists(), isDirectory(), isFile(), getName() and getAbsolutePath().
import java.io.IOException;
try {
if (!file.exists()) {
file.createNewFile();
System.out.println("File created successfully!");
} else {
System.out.println("File already exists!");
}
if (file.exists()) {
System.out.println("File exists!");
} else {
System.out.println("File does not exist!");
}
if (file.isDirectory()) {
System.out.println("File is a directory!");
} else {
System.out.println("File is not a directory!");
}
if (file.isFile()) {
System.out.println("File is a file!");
} else {
System.out.println("File is not a file!");
}
b)Write a program to rename the given file, after renaming the file delete the renamed file. (Accept
the file name using command line arguments.)
import java.io.File;
public class RenameAndDeleteFile {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java RenameAndDeleteFile <filename>");
System.exit(1);
}
if (!file.exists()) {
System.out.println("File does not exist!");
System.exit(1);
}
if (file.renameTo(newFile)) {
System.out.println("File renamed successfully!");
} else {
System.out.println("Failed to rename file!");
System.exit(1);
}
if (newFile.delete()) {
System.out.println("Renamed file deleted successfully!");
} else {
System.out.println("Failed to delete renamed file!");
}
}
}
c)Write a program to create a directory and check whether the directory is created.
import java.io.File;
public class CreateDirectory {
public static void main(String[] args) {
String dirName = "MyNewDirectory";
if (dir.mkdir()) {
System.out.println("Directory created: " + dirName);
} else {
System.out.println("Failed to create directory: " + dirName);
}
if (dir.exists()) {
System.out.println("Directory exists: " + dirName);
} else {
System.out.println("Directory does not exist: " + dirName);
}
}
}
8)a)Write a program that can read a host name and convert it to an IP address
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
try {
// Convert hostname to IP address
InetAddress ipAddress = InetAddress.getByName(hostname);
System.out.println("IP Address: " + ipAddress.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Could not resolve the hostname.");
}
scanner.close();
}
}
b)Write a Socket base java server program that responds to client messages as follows:
When it receives a message from client, it simply converts the message into all uppercase letters and
sends back to the client. Write both client and server programs demonstrating this.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
9.
a). Create the classes required to store data regarding different types of courses that employees in a
company can enroll for. All courses have name and course fee. Courses are also either classroom
delivered or delivered online. Courses could also be full time or part time. The program must enable
the course coordinator to register employees for courses and list out employees registered for specific
courses.
import java.util.Scanner;
public Course(String name, double fee, int maxEmployees, boolean isOnline, boolean
isFullTime) {
this.name = name;
this.fee = fee;
this.employeesRegistered = new Employee[maxEmployees];
this.numEmployees = 0;
this.isOnline = isOnline;
this.isFullTime = isFullTime;
}
@Override
public String toString() {
return "Course{name='" + name + "', fee=" + fee + ", online=" + isOnline + ", fullTime="
+ isFullTime + "}";
}
}
class Employee {
private String name;
class CourseCoordinator {
private Course[] courses;
private int numCourses;
while (true) {
try {
System.out.println("\n1. Add Course");
switch (choice) {
case 1:
System.out.print("Enter course name: ");
String courseName = scanner.nextLine();
System.out.print("Enter course fee: ");
double fee = Double.parseDouble(scanner.nextLine().trim());
System.out.print("Enter maximum number of employees: ");
int maxEmployees = Integer.parseInt(scanner.nextLine().trim());
System.out.print("Is the course online? (true/false): ");
boolean isOnline = Boolean.parseBoolean(scanner.nextLine().trim());
System.out.print("Is the course full-time? (true/false): ");
boolean isFullTime = Boolean.parseBoolean(scanner.nextLine().trim());
case 2:
System.out.print("Enter course name to register: ");
String regCourseName = scanner.nextLine();
System.out.print("Enter employee name: ");
String employeeName = scanner.nextLine();
case 3:
System.out.print("Enter course name to list employees: ");
String listCourseName = scanner.nextLine();
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter numeric values where required.");
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
}
b). Write a java program in to create a class Worker. Write classes DailyWorker and SalariedWorker that
inherit from Worker. Every worker has a name and a salaryrate. Write method Pay (int hours) to compute the
week pay of every worker. A Daily worker ia paid on the basis of the number of days she/he works. The
salaried worker gets paid the wage for 40 hours a week no matter what the actual hours are. Test this program
to calculate the pay of workers.
// Salaried worker is paid for 40 hours per week regardless of the hours worked
@Override
public double pay(int hours) {
// Fixed weekly pay for 40 hours
return getSalaryRate() * 40;
}
}
week.");
System.out.println(salariedWorker.getName() + " earned: $" + salariedWorker.pay(hoursWorked) + " this
week.");
}
}
10.
a).Write a JAVA program to paint like paint brush in applet.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseListener;
/*
<applet code="PaintBrushApplet" width=400 height=400>
</applet>
*/
// Capture the initial point of the brush when the mouse is pressed
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
// Optional: paint method can be used to draw the initial UI or repaint the applet
public void paint(Graphics g) {
g.setColor(Color.black);
g.drawString("Draw with your mouse!", 20, 20);
}
}
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
g2d.rotate(angle);
g2d.drawLine(0, 0, 0, -length);
g2d.setTransform(oldTransform);
}
c). Write a JAVA program to create different shapes and fill colors using Applet.
import java.applet.Applet;
import java.awt.*;
g.setColor(Color.red);
g.fillRect(50, 50, 100, 50);
g.setColor(Color.green);
g.fillOval(200, 50, 100, 50);
g.setColor(Color.blue);
g.fillRoundRect(50, 150, 100, 50, 20, 20);
11.
a). Write a JAVA program to build a Calculator in Swings
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public SimpleCalculator() {
// Create the frame
setTitle("Simple Calculator");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(buttonPanel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
String command = source.getText();
switch (command) {
case "=":
calculate();
break;
case "+":
case "-":
case "*":
case "/":
handleOperator(command);
break;
default:
appendToInput(command);
break;
}
}
switch (operator) {
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
if (secondNumber != 0) {
b). Write a JAVA program to display the digital watch using swings.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
// Use JApplet for Swing-based applets
public class DigitalWatchApplet extends JApplet {
private JLabel timeLabel;
private SimpleDateFormat timeFormat;
@Override
public void init() {
// Set up the GUI
setSize(300, 100);
setLayout(new BorderLayout());
// Initial update
updateTime();
}