MSC105P: Advanced Java Programming Lab
1. Write a program to convert a given Decimal number to Binary, Octal
and Hexadecimal using recursive functions.
import [Link];
public class DecimalConversion {
static String toBinary(int num) {
if (num == 0)
return "";
return toBinary(num / 2) + (num % 2);
}
static String toOctal(int num) {
if (num == 0)
return "";
return toOctal(num / 8) + (num % 8);
}
static String toHexadecimal(int num) {
if (num == 0)
return "";
int remainder = num % 16;
char hexChar;
if (remainder < 10)
hexChar = (char) (remainder + '0');
else
hexChar = (char) (remainder - 10 + 'A');
return toHexadecimal(num / 16) + hexChar;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a decimal number: ");
int decimal = [Link]();
// Handle zero case explicitly
if (decimal == 0) {
[Link]("Binary: 0");
[Link]("Octal: 0");
[Link]("Hexadecimal: 0");
} else {
[Link]("Binary: " + toBinary(decimal));
[Link]("Octal: " + toOctal(decimal));
[Link]("Hexadecimal: " + toHexadecimal(decimal));
}
[Link]();
}
}
How to run in command prompt
C:\Users\Shilpa S>cd /
C:\javaPrograms>javac [Link]
C:\javaPrograms>java [Link]
output
Enter a decimal number: 56
Binary: 111000
Octal: 70
Hexadecimal: 38
2. Write a program to explain the concept of constructor overloading.
class Student {
int id;
String name;
int age;
// Default constructor
Student() {
id = 0;
name = "Unknown";
age = 18;
}
// Constructor with one parameter
Student(int i) {
id = i;
name = "Not Assigned";
age = 18;
}
// Constructor with two parameters
Student(int i, String n) {
id = i;
name = n;
age = 18;
}
// Constructor with three parameters
Student(int i, String n, int a) {
id = i;
name = n;
age = a;
}
// Method to display student details
void display() {
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age);
}
}
public class ConstructorOverloadingDemo {
public static void main(String[] args) {
// Creating objects using different constructors
Student s1 = new Student();
Student s2 = new Student(101);
Student s3 = new Student(102, "suma");
Student s4 = new Student(103, "Arjun", 21);
// Displaying details
[Link]();
[Link]();
[Link]();
[Link]();
}
}
cmd
C:\javap>javac [Link]
C:\javap>java ConstructorOverloadingDemo
Output
ID: 0, Name: Unknown, Age: 18
ID: 101, Name: Not Assigned, Age: 18
ID: 102, Name: suma, Age: 18
ID: 103, Name: Arjun, Age: 21
3. Explain the concept of passing objects as parameters by adding two distances
given in feet and inches
// Program to demonstrate passing objects as parameters
// by adding two distances (in feet and inches)
class Distance {
int feet;
int inches;
// Method to set distance
void setDistance(int f, int i) {
feet = f;
inches = i;
}
// Method to display distance
void displayDistance() {
[Link](feet + " feet " + inches + " inches");
}
// Method to add two Distance objects
Distance addDistance(Distance d2) {
Distance result = new Distance();
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
// Convert inches to feet if >= 12
if ([Link] >= 12) {
[Link] += [Link] / 12;
[Link] = [Link] % 12;
}
return result; // Returning object
}
}
public class AddDistance {
public static void main(String[] args) {
Distance d1 = new Distance();
Distance d2 = new Distance();
Distance d3;
[Link](5, 9); // 5 feet 9 inches
[Link](4, 11); // 4 feet 11 inches
[Link]("First Distance: ");
[Link]();
[Link]("Second Distance: ");
[Link]();
// Passing object as parameter
d3 = [Link](d2);
[Link]("\nTotal Distance: ");
[Link]();
}
}
cmd
C:\javap>javac [Link]
C:\javap>java AddDistance
Output :
First Distance:
5 feet 9 inches
Second Distance:
4 feet 11 inches
Total Distance:
10 feet 8 inches
4. Write a program to implement inheritance Concept in Java
// Program to demonstrate Inheritance in Java
// Parent class
class Animal {
void eat() {
[Link]("Animals can eat");
}
void sleep() {
[Link]("Animals can sleep");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}
// Main class
public class InheritanceExample {
public static void main(String[] args) {
// Create object of child class
Dog d = new Dog();
// Accessing methods from parent and child class
[Link](); // inherited from Animal class
[Link](); // inherited from Animal class
[Link](); // defined in Dog class
}
}
cmd
C:\javap>javac [Link]
C:\javap>java InheritanceExample
Output:
Animals can eat
Animals can sleep
Dog barks
5. Write program to explain the concept of runtime polymorphism in Java.
class Animal {
// Method to be overridden
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding sound() method
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
// Overriding sound() method
void sound() {
[Link]("Cat meows");
}
}
class Main {
public static void main(String[] args) {
// Parent class reference, child class objects
Animal a;
a = new Dog(); // Upcasting
[Link](); // Calls Dog's sound() → Runtime Polymorphism
a = new Cat(); // Upcasting
[Link](); // Calls Cat's sound() → Runtime Polymorphism
}
}
cmd
C:\javap>javac [Link]
C:\javap>java Main
Output:
Dog barks
Cat meows
6. Write a program to implement producer consumer problem using thread
concept.
// Producer-Consumer Problem in Java using wait() and notify()
class Buffer {
int item;
boolean hasItem = false; // Buffer initially empty
// Producer puts item
synchronized void produce(int value) {
try {
while (hasItem) {
wait(); // Wait until consumer consumes
}
item = value;
[Link]("Produced: " + value);
hasItem = true;
notify(); // Notify consumer
} catch (Exception e) {
[Link](e);
}
}
// Consumer takes item
synchronized int consume() {
int value = 0;
try {
while (!hasItem) {
wait(); // Wait until producer produces
}
value = item;
[Link]("Consumed: " + value);
hasItem = false;
notify(); // Notify producer
} catch (Exception e) {
[Link](e);
}
return value;
}
}
// Producer Thread
class Producer extends Thread {
Buffer b;
Producer(Buffer b) {
this.b = b;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](i);
try { [Link](500); } catch (Exception e) {}
}
}
}
// Consumer Thread
class Consumer extends Thread {
Buffer b;
Consumer(Buffer b) {
this.b = b;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]();
try { [Link](1000); } catch (Exception e) {}
}
}
}
// Main class
public class ProducerConsumerDemo {
public static void main(String[] args) {
Buffer b = new Buffer();
Producer p = new Producer(b);
Consumer c = new Consumer(b);
[Link]();
[Link]();
}
}
cmd
C:\javap>javac [Link]
C:\javap>java ProducerConsumerDemo
Output
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
7. Write a program to create object for Tree Set and Stack and use all methods
import [Link].*;
public class CollectionDemo {
public static void main(String[] args) {
// ----------------------------
// TreeSet Example
// ----------------------------
TreeSet<Integer> ts = new TreeSet<>();
// Adding elements
[Link](40);
[Link](10);
[Link](20);
[Link](30);
[Link]("TreeSet: " + ts);
// TreeSet Methods
[Link]("First Element: " + [Link]());
[Link]("Last Element: " + [Link]());
[Link]("Higher(20): " + [Link](20)); // next greater
[Link]("Lower(20): " + [Link](20)); // next smaller
[Link]("Ceiling(25): " + [Link](25)); // >= element
[Link]("Floor(25): " + [Link](25)); // <= element
[Link]("Contains 20? " + [Link](20));
[Link]("TreeSet Size: " + [Link]());
// Removing elements
[Link](20);
[Link]("After Removing 20: " + ts);
// Poll methods
[Link]("Poll First: " + [Link]());
[Link]("Poll Last: " + [Link]());
[Link]("TreeSet After Polling: " + ts);
// Stack Example
Stack<String> stack = new Stack<>();
// Push elements
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("\nStack: " + stack);
// Stack Methods
[Link]("Top element (peek): " + [Link]());
[Link]("Pop element: " + [Link]());
[Link]("Stack After Pop: " + stack);
[Link]("Is Stack Empty? " + [Link]());
[Link]("Stack Size: " + [Link]());
// Searching in Stack
[Link]("Position of A: " + [Link]("A")); // returns 1-based
position
// Add more elements
[Link]("D");
[Link]("E");
[Link]("Stack After Adding: " + stack);
// Removing element by object
[Link]("B");
[Link]("After Removing B: " + stack);
// Iterating Stack
[Link]("Iterating Stack:");
for(String s : stack) {
[Link](s);
}
}
}
cmd
C:\javap>javac [Link]
C:\javap>java CollectionDemo
output
TreeSet: [10, 20, 30, 40]
First Element: 10
Last Element: 40
Higher(20): 30
Lower(20): 10
Ceiling(25): 30
Floor(25): 20
Contains 20? true
TreeSet Size: 4
After Removing 20: [10, 30, 40]
Poll First: 10
Poll Last: 40
TreeSet After Polling: [30]
Stack: [A, B, C]
Top element (peek): C
Pop element: C
Stack After Pop: [A, B]
Is Stack Empty? false
Stack Size: 2
Position of A: 2
Stack After Adding: [A, B, D, E]
After Removing B: [A, D, E]
Iterating Stack:
A
D
E
8. Write a program to implement Exception handling in Java
class ExceptionExample {
public static void main(String[] args) {
try {
// Code that may cause exception
int a = 10;
int b = 0;
// Arithmetic Exception (Divide by zero)
int result = a / b;
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
// Handling the exception
[Link]("Exception caught: " + [Link]());
[Link]("You cannot divide a number by zero.");
}
finally {
// This block always runs
[Link]("Finally block executed.");
}
[Link]("Program continues normally...");
}
}
cmd
C:\javap>javac [Link]
C:\javap>java ExceptionExample
Output
Exception caught: / by zero
You cannot divide a number by zero.
Finally block executed.
Program continues normally...
9. Write a program to implement the Concept of Interface in Java.
// Defining an interface
interface Animal {
void sound(); // abstract method
void eat(); // abstract method
}
// Implementing the interface in a class
class Dog implements Animal {
// Providing implementation for interface methods
public void sound() {
[Link]("The dog barks");
}
public void eat() {
[Link]("The dog eats bones");
}
}
// Main class
public class InterfaceExample {
public static void main(String[] args) {
Animal myDog = new Dog(); // Interface reference, object of Dog
[Link]();
[Link]();
}
}
cmd
C:\javap>javac [Link]
C:\javap>java InterfaceExample
Output
The dog barks
The dog eats bones
10. Write a program to get file name at runtime and display number of lines and
words in that file
import [Link].*;
import [Link];
public class FileCount {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter file name: ");
String fileName = [Link](); // get file name at runtime
int lineCount = 0;
int wordCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while ((line = [Link]()) != null) {
lineCount++;
// Split the line into words
String[] words = [Link]().split("\\s+");
// Avoid counting empty lines
if ([Link]().length() != 0) {
wordCount += [Link];
}
}
[Link]();
}
catch (FileNotFoundException e) {
[Link]("File not found! Please check the file name.");
return;
}
catch (IOException e) {
[Link]("Error reading the file.");
return;
}
[Link]("Total Lines: " + lineCount);
[Link]("Total Words: " + wordCount);
}
}
cmd
C:\javap>javac [Link]
C:\javap>java FileCount
Output
Enter file name: [Link]
Total Lines: 27
Total Words: 82
11. Write a program to list files in the current working directory depending upon
a given
pattern.
import [Link];
import [Link];
public class ListFilesByPattern {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Get pattern from user (example: .txt or abc or .java)
[Link]("Enter file pattern: ");
String pattern = [Link]();
// Get current working directory
File directory = new File("."); // dot means current directory
// List all files
File[] files = [Link]();
if (files == null) {
[Link]("Could not access directory.");
return;
}
[Link]("\nFiles matching pattern \"" + pattern + "\":");
boolean found = false;
for (File file : files) {
if ([Link]()) {
// Check if filename contains the given pattern
if ([Link]().contains(pattern)) {
[Link]([Link]());
found = true;
}
}
}
if (!found) {
[Link]("No files found with the given pattern.");
}
}
}
Output
C:\javap>javac [Link]
C:\javap>java ListFilesByPattern
Enter file pattern: java
Files matching pattern "java":
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
C:\javap>java ListFilesByPattern
Enter file pattern: txt
Files matching pattern "txt":
No files found with the given pattern.
C:\javap>java ListFilesByPattern
Enter file pattern: pdf
Files matching pattern "pdf":
No files found with the given pattern.
[Link] a Frame for Student Registration containing all the fields Name, Age,
Contact,
Father’s Name, Annual Income and a submit button. Perform field validations.
import [Link].*;
import [Link].*;
import [Link].*;
public class StudentRegistrationForm extends JFrame implements ActionListener
{
// Components
JTextField nameField, ageField, contactField, fatherNameField, incomeField;
JButton submitBtn;
public StudentRegistrationForm() {
setTitle("Student Registration Form");
setSize(400, 350);
setLayout(new GridLayout(7, 2, 5, 5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Labels and text fields
add(new JLabel("Name:"));
nameField = new JTextField();
add(nameField);
add(new JLabel("Age:"));
ageField = new JTextField();
add(ageField);
add(new JLabel("Contact No:"));
contactField = new JTextField();
add(contactField);
add(new JLabel("Father's Name:"));
fatherNameField = new JTextField();
add(fatherNameField);
add(new JLabel("Annual Income:"));
incomeField = new JTextField();
add(incomeField);
submitBtn = new JButton("Submit");
[Link](this);
add(submitBtn);
setVisible(true);
}
// Handling submit button click
public void actionPerformed(ActionEvent e) {
String name = [Link]();
String age = [Link]();
String contact = [Link]();
String fatherName = [Link]();
String income = [Link]();
// Validations
if ([Link]() || [Link]()) {
[Link](this, "Name and Father's Name cannot
be empty!");
return;
}
// Age must be a number
try {
int ageValue = [Link](age);
if (ageValue <= 0 || ageValue > 120) {
[Link](this, "Enter a valid age!");
return;
}
} catch (Exception ex) {
[Link](this, "Age must be a number!");
return;
}
// Contact must be 10 digits
if () {
[Link](this, "Contact must be 10 digits!");
return;
}
// Income must be a valid number
try {
double inc = [Link](income);
if (inc < 0) {
[Link](this, "Annual Income cannot be
negative!");
return;
}
} catch (Exception ex) {
[Link](this, "Annual Income must be a
number!");
return;
}
// If all fields are valid
[Link](this, "Registration Successful!");
}
public static void main(String[] args) {
new StudentRegistrationForm();
}
}
Cmd
C:\javap>javac [Link]
C:\javap>java StudentRegistrationForm
Output
13. Write a program to demonstrate the usage of Swings
import [Link].*;
import [Link].*;
import [Link].*;
public class SwingDemo extends JFrame implements ActionListener {
JTextField nameField;
JButton showBtn;
JTextArea outputArea;
public SwingDemo() {
// Frame title
setTitle("Swing Demo Program");
// Frame layout
setLayout(new FlowLayout());
// Frame size
setSize(400, 300);
// Components
JLabel nameLabel = new JLabel("Enter your name: ");
add(nameLabel);
nameField = new JTextField(15);
add(nameField);
showBtn = new JButton("Show Message");
[Link](this);
add(showBtn);
outputArea = new JTextArea(5, 25);
add(outputArea);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// Event Handling
@Override
public void actionPerformed(ActionEvent e) {
String name = [Link]();
if ([Link]()) {
[Link](this, "Please enter a name!");
} else {
[Link]("Hello " + name + "! Welcome to Swing
Programming.");
}
}
public static void main(String[] args) {
new SwingDemo();
}
}
Cmd
C:\javap>javac [Link]
C:\javap>java SwingDemo
Output
14. Write a program to perform the following operation using JDBC: Insert,
Update, Delete and Select Data.
import [Link].*;
import [Link];
public class StudentCRUD {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; // your DB
String user = "root"; // your username
String pass = "password"; // your password
try {
[Link]("[Link]");
Connection con = [Link](url, user, pass);
Scanner sc = new Scanner([Link]);
while (true) {
[Link]("\n=== Student CRUD Menu ===");
[Link]("1. Insert Student");
[Link]("2. Update Student");
[Link]("3. Delete Student");
[Link]("4. View Students");
[Link]("5. Exit");
[Link]("Enter choice: ");
int ch = [Link]();
if (ch == 1) {
[Link]("Enter ID: ");
int id = [Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Marks: ");
int marks = [Link]();
PreparedStatement pst = [Link](
"INSERT INTO student VALUES(?,?,?)");
[Link](1, id);
[Link](2, name);
[Link](3, marks);
[Link]();
[Link]("Inserted Successfully!");
} else if (ch == 2) {
[Link]("Enter ID to Update: ");
int id = [Link]();
[Link]("Enter New Marks: ");
int marks = [Link]();
PreparedStatement pst = [Link](
"UPDATE student SET marks=? WHERE id=?");
[Link](1, marks);
[Link](2, id);
int count = [Link]();
if (count > 0)
[Link]("Updated Successfully!");
else
[Link]("Record Not Found");
} else if (ch == 3) {
[Link]("Enter ID to Delete: ");
int id = [Link]();
PreparedStatement pst = [Link](
"DELETE FROM student WHERE id=?");
[Link](1, id);
int count = [Link]();
if (count > 0)
[Link]("Deleted Successfully!");
else
[Link]("Record Not Found");
} else if (ch == 4) {
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM student");
[Link]("\nID\tName\tMarks");
while ([Link]()) {
[Link]([Link](1) + "\t" +
[Link](2) + "\t" +
[Link](3));
}
} else if (ch == 5) {
[Link]("Exiting...");
break;
} else {
[Link]("Invalid Choice");
}
}
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE student(
id INT PRIMARY KEY,
name VARCHAR(30),
marks INT
);
Output
C:\javap>javac [Link]
C:\javap>java -cp .;C:\jdbc\mysql-connector-j-9.5.0\[Link]
StudentCRUD
=== Student CRUD Menu ===
1. Insert Student
2. Update Student
3. Delete Student
4. View Students
5. Exit
Enter choice: 1
Enter ID: 22
Enter Name: ss
Enter Marks: 444
Inserted Successfully!
=== Student CRUD Menu ===
1. Insert Student
2. Update Student
3. Delete Student
4. View Students
5. Exit
Enter choice: 2
Enter ID to Update: 5
Enter New Marks: 77
Record Not Found
=== Student CRUD Menu ===
1. Insert Student
2. Update Student
3. Delete Student
4. View Students
5. Exit
Enter choice: 5
Exiting...