0% found this document useful (0 votes)
4 views45 pages

Java Lab Manual

The document is a lab manual for the Object Oriented Programming (OOP) course using Java at Vijaya Institute of Technology for Women for the academic year 2025-2026. It outlines the college's vision and mission, the department's objectives, program outcomes, and specific outcomes for the course. Additionally, it includes various programming exercises designed to teach Java concepts such as data types, inheritance, exception handling, and database connectivity.

Uploaded by

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

Java Lab Manual

The document is a lab manual for the Object Oriented Programming (OOP) course using Java at Vijaya Institute of Technology for Women for the academic year 2025-2026. It outlines the college's vision and mission, the department's objectives, program outcomes, and specific outcomes for the course. Additionally, it includes various programming exercises designed to teach Java concepts such as data types, inheritance, exception handling, and database connectivity.

Uploaded by

sukanya200194
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming Through Java Lab

Department of CSE- DATA SCIENCE

OOPS THROUGH JAVA Lab Manual

YEAR/SEM:II/1

AY 2025 – 2026

R23

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


AN ISO 9001:2015 Certified Institute, Approved by AICTE, Affiliated to JNTUK Kakinada, AP
Phone: 0866-2844444, Email: vijayatechfw@[Link] Website: [Link]
College Code: NP, Enikepadu,Vijayawada-521108

Vijaya Institute Of Technology For Women Page No: 1


Object Oriented Programming Through Java Lab

VISION OF COLLEGE

Vijaya Institute of Technology for Women aims at empowering women engineers with values and
ethos to sustain across the globe and refining them as best intellectuals to fit in the Competitive
Society.

MISSION OF COLLEGE

[Link] educate all students to the highest levels of academic achievement.

[Link] enable the students to their potential and prepare them to become productive, responsible,
Creative members of the Society.

[Link] enable students to gain Knowledge in ground breaking technologies.

DEPARTMENT VISION

Creating knowledge of fundamental principles and innovative technologies through research


within the core areas of computer science and also in inter-disciplinary topics.

DEPARTMENT MISSION

• To produce qualified and motivated graduates through a rigorous curriculum of theory and
application that develops the ability to solve problems, individually and in teams.

• To Produce qualified and motivated graduates through a rigorous curriculum of theory and
Application that develops the ability to solve problems, individually and in teams.
• To create a Centre of excellence in engineering by imparting knowledge and skills.
• To contribute effectively to the important national endeavor to produce quality human resource
in the information technology and related areas for sustainable development of the country's
IT industry needs.

• To serve the local and the national community by creating awareness about IT related products
and to impress upon then the importance of knowledge management.

Vijaya Institute Of Technology For Women Page No: 2


Object Oriented Programming Through Java Lab

Program Outcomes (POs)

PO1: Engineering Knowledge: Apply knowledge of mathematics, natural science, computing,


engineering fundamentals and an engineering specialization as specified respectively to
develop to the solution of complex engineering problems.
PO2: Problem Analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions with consideration for sustainable
development.
PO3: Design/Development of Solutions: Design creative solutions for complex engineering
problems and design/develop systems/components/processes to meet identified needs with
consideration for the public health and safety, whole-life cost, net zero carbon, culture,
society and environment as required.
PO4: Conduct Investigations of Complex Problems: Conduct investigations of complex
engineering problems using research-based knowledge including design of experiments,
modelling, analysis & interpretation of data to provide valid conclusions.
PO5: Engineering Tool Usage: Create, select and apply appropriate techniques, resources and
modern engineering & IT tools, including prediction and modelling recognizing their limitations
to solve complex engineering problems.
PO6: The Engineer and The World: Analyze and evaluate societal and environmental aspects
while solving complex engineering problems for its impact on sustainability with reference to
economy, health, safety, legal framework, culture and environment.
PO7: Ethics: Apply ethical principles and commit to professional ethics, human values, diversity
and inclusion; adhere to national & international laws.
PO8: Individual and Collaborative Team work: Function effectively as an individual, and as a
member or leader in diverse/multi-disciplinary teams.
PO9: Communication: Communicate effectively and inclusively within the engineering
community and society at large, such as being able to comprehend and write effective reports
and design documentation, make effective presentations considering cultural, language, and
learning differences.
PO10: Project Management and Finance: Apply knowledge and understanding of engineering
management principles and economic decision-making and apply these to one’s own work, as a
member and leader in a team, and to manage projects and in multidisciplinary environments.
PO11: Life-Long Learning: Recognize the need for, and have the preparation and ability for
Independent and life-long learning
Adaptability to new and emerging technologies
Critical thinking in the broadest context of technological change.

Vijaya Institute Of Technology For Women Page No: 3


Object Oriented Programming Through Java Lab

PROGRAM SPECIFIC OUTCOMES(PSO’s)

PSO 1: Train the students to use the core concepts of computing and optimization techniques to
develop more efficient and effective computing mechanism and make them experts in designing
the computer software and hardware.

PSO 2: Training the students in cutting edge technologies such as Data science, Machine Learning,
Cloud Computing and Data Analytics to meet the industry deemed.

PSO 3: Hone up the skills of students to professional level to solve problems in the board area of
programming concepts and appraise environment and social issues with ethics and manage
different projects in inter disciplinary field.

Vijaya Institute Of Technology For Women Page No: 4


Object Oriented Programming Through Java Lab

Modules/ Exercises
Exercise - 1:
a. Write a JAVA program to display default value of all primitive data type 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.
Exercise - 2
a. Write a JAVA program to search for an element in a given list of elements using binary search
mechanism.
b. Write a JAVA program to sort for an element in a given list of elements using bubble sort
c. Write a JAVA program using String Buffer to delete, remove character.
Exercise - 3
a. Write a JAVA program to implement class mechanism. Create a class, methods and invoke them
inside main method.
b. Write a JAVA program implements method overloading.
c. Write a JAVA program to implement constructor.
d. Write a JAVA program to implement constructor overloading.
Exercise - 4
a. Write a JAVA program to implement Single Inheritance.
b. Write a JAVA program to implement multilevel Inheritance.
c. Write a JAVA program for abstract class to find areas of different shape.
Exercise - 5
a. Write a JAVA program give example for “super” keyword.
b. Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
c. Write a JAVA program that implements Runtime polymorphism.
Exercise - 6
a. Write a JAVA program that describes exception handling mechanism.
b. Write a JAVA program Illustrating Multiple catch clauses.
c. Write a JAVA program for creation of Java Built-in Exceptions.
d. Write a JAVA program for creation of User Defined Exception.
Exercise - 7
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).
b. Write a program illustrating is Alive and join ()
c. Write a Program illustrating Daemon Threads.
d. Write a JAVA program Producer Consumer Problem.
Exercise – 8
a. Write a JAVA program that import and use the user defined packages.
b. Without writing any code, build a GUI that display text in label and image in an ImageView (use
JavaFX).
c. Build a Tip Calculator app using several JavaFX components and learn how to respond to user
interactions with the GUI.
Exercise – 9
a) Write a java program that connects to a database using JDBC
b) Write a java program to connect to a database using JDBC and insert values into it.
c) Write a java program to connect to a database using JDBC and delete values from it

Vijaya Institute Of Technology For Women Page No: 5


Object Oriented Programming Through Java Lab

Exercise - 1:
a. Write a JAVA program to display default value of all primitive data type of JAVA

class DefaultValues {
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
boolean bool;

void displayDefaults() {
[Link]("Default Values of Primitive Data Types:");
[Link]("Byte: " + b);
[Link]("Short: " + s);
[Link]("Int: " + i);
[Link]("Long: " + l);
[Link]("Float: " + f);
[Link]("Double: " + d);
[Link]("Char: [" + c + "] (empty character)");
[Link]("Boolean: " + bool);
}

public static void main(String[] args) {


DefaultValues obj = new DefaultValues();
[Link]();
}
}

Expected Output:

Default Values of Primitive Data Types:


Byte: 0
Short: 0
Int: 0
Long: 0
Float: 0.0
Double: 0.0
Char: [] (empty character)
Boolean: false

Vijaya Institute Of Technology For Women Page No: 6


Object Oriented Programming Through Java Lab

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 [Link];
class QuadraticEquation {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input coefficients
[Link]("Enter coefficient a: ");
double a = [Link]();

[Link]("Enter coefficient b: ");


double b = [Link]();

[Link]("Enter coefficient c: ");


double c = [Link]();

// Calculate discriminant
double D = b * b - 4 * a * c;
[Link]("Discriminant (D) = " + D);

// Determine nature of roots


if (D > 0) {
[Link]("Roots are real and distinct.");
double root1 = (-b + [Link](D)) / (2 * a);
double root2 = (-b - [Link](D)) / (2 * a);
[Link]("Root 1: " + root1);
[Link]("Root 2: " + root2);
} else if (D == 0) {
[Link]("Roots are real and equal.");
double root = -b / (2 * a);
[Link]("Root: " + root);
} else {
[Link]("Roots are complex and imaginary.");
double realPart = -b / (2 * a);
double imaginaryPart = [Link](-D) / (2 * a);
[Link]("Root 1: " + realPart + " + " + imaginaryPart + "i");
[Link]("Root 2: " + realPart + " - " + imaginaryPart + "i");
}

[Link]();
}
}

Example Output:
Enter coefficient a: 1
Enter coefficient b: -7
Enter coefficient c: 10
Discriminant (D) = 9.0
Roots are real and distinct.
Root 1: 5.0
Root 2: 2.0

Vijaya Institute Of Technology For Women Page No: 7


Object Oriented Programming Through Java Lab

Exercise - 2
a. Write a JAVA program to search for an element in a given list of elements using binary search
mechanism.

import [Link];

class BinarySearch {
// Method to perform binary search
public static int binarySearch(int[] arr, int key) {
int left = 0, right = [Link] - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Check if key is at mid


if (arr[mid] == key) {
return mid; // Return index of the key
}
// If key is smaller, search in left half
else if (arr[mid] > key) {
right = mid - 1;
}
// If key is larger, search in right half
else {
left = mid + 1;
}
}
return -1; // Key not found
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Input size of array


[Link]("Enter the number of elements: ");
int n = [Link]();

int[] arr = new int[n];

// Input sorted array elements


[Link]("Enter " + n + " sorted elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Input element to search


[Link]("Enter the element to search: ");
int key = [Link]();

// Perform binary search


int result = binarySearch(arr, key);

// Display result
if (result != -1) {

Vijaya Institute Of Technology For Women Page No: 8


Object Oriented Programming Through Java Lab

[Link]("Element found at index: " + result);


} else {
[Link]("Element not found in the list.");
}

[Link]();
}
}

Expected Output:

Enter the number of elements: 5


Enter 5 sorted elements:
10 20 30 40 50
Enter the element to search: 30
Element found at index: 2

Vijaya Institute Of Technology For Women Page No: 9


Object Oriented Programming Through Java Lab

b. Write a JAVA program to sort for an element in a given list of elements using bubble sort.

import [Link];
class BubbleSort {
// Method to perform Bubble Sort
public static void bubbleSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Method to display the array


public static void displayArray(int[] arr) {
for (int num : arr) {
[Link](num + " ");
}
[Link]();
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Input size of array


[Link]("Enter the number of elements: ");
int n = [Link]();

int[] arr = new int[n];

// Input array elements


[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
// Sorting the array
[Link]("Array before sorting:");
displayArray(arr);

bubbleSort(arr);

// Displaying sorted array


[Link]("Array after sorting:");
displayArray(arr);
[Link]();
}
}

Vijaya Institute Of Technology For Women Page No: 10


Object Oriented Programming Through Java Lab

Expected Output:

Enter the number of elements: 5


Enter 5 elements:
64 34 25 12 22
Array before sorting:
64 34 25 12 22
Array after sorting:
12 22 25 34 64

Vijaya Institute Of Technology For Women Page No: 11


Object Oriented Programming Through Java Lab

c. Write a JAVA program using String Buffer to delete, remove character.


import [Link];
class StringBufferExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input string
[Link]("Enter a string: ");
StringBuffer sb = new StringBuffer([Link]());
// Display original string
[Link]("Original String: " + sb);
// Deleting a substring
[Link]("Enter start and end index to delete substring: ");
int start = [Link]();
int end = [Link]();
[Link](start, end);
[Link]("String after deletion: " + sb);
// Removing a character
[Link]("Enter index to delete a character: ");
int index = [Link]();
[Link](index);
[Link]("String after removing character: " + sb);
[Link]();
}
}
Expected Output:
Enter a string: Hello World
Original String: Hello World
Enter start and end index to delete substring: 6 11
String after deletion: Hello
Enter index to delete a character: 2
String after removing character: Helo

Vijaya Institute Of Technology For Women Page No: 12


Object Oriented Programming Through Java Lab

Exercise - 3
a. Write a JAVA program to implement class mechanism. Create a class, methods and invoke
them inside main method.

// Define a class
class Student {
// Data members (instance variables)
String name;
int age;

// Method to set student details


void setDetails(String n, int a) {
name = n;
age = a;
}

// Method to display student details


void displayDetails() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
}
}

public class ClassMechanismExample {


public static void main(String[] args) {
// Creating an object of Student class
Student s1 = new Student();

// Calling method to set details


[Link]("Alice", 20);

// Calling method to display details


[Link]("Student Information:");
[Link]();
}
}

Expected Output:

Student Information:
Student Name: Alice
Student Age: 20

Vijaya Institute Of Technology For Women Page No: 13


Object Oriented Programming Through Java Lab

b. Write a JAVA program implements method overloading.

class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two double numbers


double add(double a, double b) {
return a + b;
}
}

public class MethodOverloadingExample {


public static void main(String[] args) {
MathOperations obj = new MathOperations();

// Calling overloaded methods


[Link]("Sum of two integers: " + [Link](5, 10));
[Link]("Sum of three integers: " + [Link](5, 10, 15));
[Link]("Sum of two double values: " + [Link](5.5, 2.5));
}
}

Expected Output:

Sum of two integers: 15


Sum of three integers: 30
Sum of two double values: 8.0

Vijaya Institute Of Technology For Women Page No: 14


Object Oriented Programming Through Java Lab

c. Write a JAVA program to implement constructor.

class Student {
String name;
int age;

// Constructor to initialize values


Student(String n, int a) {
name = n;
age = a;
}

// Method to display student details


void display() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
}
}

public class ConstructorExample {


public static void main(String[] args) {
// Creating an object of Student class (Constructor is called automatically)
Student s1 = new Student("Alice", 20);

// Display student details


[Link]();
}
}

Expected Output:

Student Name: Alice


Student Age: 20

Vijaya Institute Of Technology For Women Page No: 15


Object Oriented Programming Through Java Lab

d. Write a JAVA program to implement constructor overloading.


class Student {
String name;
int age;

// Constructor with no parameters (Default Constructor)


Student() {
name = "Unknown";
age = 0;
}

// Constructor with one parameter


Student(String n) {
name = n;
age = 18; // Default age
}

// Constructor with two parameters


Student(String n, int a) {
name = n;
age = a;
}

// Method to display student details


void display() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
}
}

public class ConstructorOverloadingExample {


public static void main(String[] args) {
// Creating objects using different constructors
Student s1 = new Student();
Student s2 = new Student("Alice");
Student s3 = new Student("Bob", 21);

// Displaying student details

Vijaya Institute Of Technology For Women (Autonomous) Page No: 16


Object Oriented Programming Through Java Lab

[Link]("Student 1:");
[Link]();

[Link]("\nStudent 2:");
[Link]();

[Link]("\nStudent 3:");
[Link]();
}
}

Expected Output:

Student 1:
Student Name: Unknown
Student Age: 0

Student 2:
Student Name: Alice
Student Age: 18

Student 3:
Student Name: Bob
Student Age: 21

Vijaya Institute Of Technology For Women (Autonomous) Page No: 17


Object Oriented Programming Through Java Lab

Exercise - 4
a. Write a JAVA program to implement Single Inheritance.

// Parent class
class Animal {
void eat() {
[Link]("This animal eats food.");
}
}

// Child class inheriting from Animal


class Dog extends Animal {
void bark() {
[Link]("The dog barks.");
}
}

public class SingleInheritanceExample {


public static void main(String[] args) {
// Creating an object of Dog class
Dog myDog = new Dog();

// Calling methods from both parent and child classes


[Link](); // Inherited method
[Link](); // Child class method
}
}

Expected Output:

This animal eats food.


The dog barks.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 18


Object Oriented Programming Through Java Lab

b. Write a JAVA program to implement multilevel Inheritance.

// Base class (Parent)


class Animal {
void eat() {
[Link]("This animal eats food.");
}
}

// Derived class (Child of Animal)


class Mammal extends Animal {
void walk() {
[Link]("Mammals can walk.");
}
}

// Derived class (Child of Mammal)


class Dog extends Mammal {
void bark() {
[Link]("The dog barks.");
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
// Creating an object of Dog class
Dog myDog = new Dog();

// Calling methods from all levels of inheritance


[Link](); // Inherited from Animal
[Link](); // Inherited from Mammal
[Link](); // Defined in Dog
}
}

Expected Output:

This animal eats food.


Mammals can walk.
The dog barks.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 19


Object Oriented Programming Through Java Lab

c. Write a JAVA program for abstract class to find areas of different shape.
// Abstract class
abstract class Shape {
// Abstract method to calculate area
abstract void calculateArea();
}

// Subclass for Circle


class Circle extends Shape {
double radius;

// Constructor
Circle(double r) {
radius = r;
}

// Implementation of abstract method


void calculateArea() {
double area = [Link] * radius * radius;
[Link]("Area of Circle: " + area);
}
}

// Subclass for Rectangle


class Rectangle extends Shape {
double length, width;

// Constructor
Rectangle(double l, double w) {
length = l;
width = w;
}

// Implementation of abstract method


void calculateArea() {
double area = length * width;
[Link]("Area of Rectangle: " + area);
}

Vijaya Institute Of Technology For Women (Autonomous) Page No: 20


Object Oriented Programming Through Java Lab

// Subclass for Triangle


class Triangle extends Shape {
double base, height;

// Constructor
Triangle(double b, double h) {
base = b;
height = h;
}

// Implementation of abstract method


void calculateArea() {
double area = 0.5 * base * height;
[Link]("Area of Triangle: " + area);
}
}

public class AbstractClassExample {


public static void main(String[] args) {
// Creating objects of different shapes
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
Shape triangle = new Triangle(3, 8);

// Calculating areas
[Link]();
[Link]();
[Link]();
}
}
Expected Output:

Area of Circle: 78.53981633974483


Area of Rectangle: 24.0
Area of Triangle: 12.0

Vijaya Institute Of Technology For Women (Autonomous) Page No: 21


Object Oriented Programming Through Java Lab

Exercise - 5
a. Write a JAVA program give example for “super” keyword.

// Parent class
class Animal {
String name = "Animal";

// Constructor of parent class


Animal() {
[Link]("Animal constructor is called.");
}

// Method in parent class


void makeSound() {
[Link]("Animals make different sounds.");
}
}
// Child class
class Dog extends Animal {
String name = "Dog";

// Constructor of child class


Dog() {
// Calling parent class constructor using super()
super();
[Link]("Dog constructor is called.");
}

// Method in child class


void display() {
[Link]("Child class variable: " + name);
[Link]("Parent class variable: " + [Link]); // Access parent class variable

[Link](); // Call parent class method


}
}
public class SuperKeywordExample {
public static void main(String[] args) {
// Creating an object of Dog class
Dog myDog = new Dog();

// Calling method to demonstrate super keyword usage


[Link]();
}
}

Expected Output:

Animal constructor is called.


Dog constructor is called.
Child class variable: Dog
Parent class variable: Animal
Animals make different sounds.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 22


Object Oriented Programming Through Java Lab

b. Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?

// Interface definition
interface Shape {
// Abstract method (no implementation)
void calculateArea();
}

// Class implementing the interface


class Circle implements Shape {
double radius;

// Constructor
Circle(double r) {
radius = r;
}

// Implementing interface method


public void calculateArea() {
double area = [Link] * radius * radius;
[Link]("Area of Circle: " + area);
}
}

// Another class implementing the same interface


class Rectangle implements Shape {
double length, width;

// Constructor
Rectangle(double l, double w) {
length = l;
width = w;
}

// Implementing interface method


public void calculateArea() {
double area = length * width;
[Link]("Area of Rectangle: " + area);
}
}

public class InterfaceExample {


public static void main(String[] args) {
// Creating objects of different shapes
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);

// Calculating areas
[Link]();
[Link]();
}
}

Vijaya Institute Of Technology For Women (Autonomous) Page No: 23


Object Oriented Programming Through Java Lab

Expected Output:

Area of Circle: 78.53981633974483


Area of Rectangle: 24.0

// First interface
interface Animal {
void eat();
}

// Second interface
interface Bird {
void fly();
}

// Class implementing multiple interfaces


class Bat implements Animal, Bird {
public void eat() {
[Link]("Bat eats insects and fruits.");
}

public void fly() {


[Link]("Bat can fly.");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
// Creating an object of Bat class
Bat myBat = new Bat();

// Calling methods from both interfaces


[Link]();
[Link]();
}
}

Expected Output:

Bat eats insects and fruits.


Bat can fly.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 24


Object Oriented Programming Through Java Lab

c. Write a JAVA program that implements Runtime polymorphism.


// Parent class
class Animal {
// Method to be overridden
void makeSound() {
[Link]("Animals make different sounds.");
}
}

// Child class 1
class Dog extends Animal {
// Overriding makeSound() method
void makeSound() {
[Link]("Dog barks.");
}
}
// Child class 2
class Cat extends Animal {
// Overriding makeSound() method
void makeSound() {
[Link]("Cat meows.");
}
}
public class RuntimePolymorphismExample {
public static void main(String[] args) {
// Parent class reference pointing to Child class objects (Upcasting)
Animal myAnimal;
myAnimal = new Dog();
[Link](); // Calls Dog's version of makeSound()
myAnimal = new Cat();
[Link](); // Calls Cat's version of makeSound()
}
}
Expected Output:

Dog barks.
Cat meows.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 25


Object Oriented Programming Through Java Lab

Exercise - 6
a. Write a JAVA program that describes exception handling mechanism.

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
// Code that may cause an exception
int a = 10, b = 0;
int result = a / b; // This will cause ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
// Handling the exception
[Link]("Exception caught: Division by zero is not allowed.");
} finally {
// Finally block always executes
[Link]("Execution completed.");
}
}
}

Expected Output:

Exception caught: Division by zero is not allowed.


Execution completed.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 26


Object Oriented Programming Through Java Lab

b. Write a JAVA program Illustrating Multiple catch clauses.

public class MultipleCatchExample {


public static void main(String[] args) {
try {
int arr[] = {10, 20, 30};
int a = 10, b = 0;

// This will cause ArithmeticException


int result = a / b;
[Link]("Result: " + result);

// This will cause ArrayIndexOutOfBoundsException


[Link]("Array Element: " + arr[5]);

} catch (ArithmeticException e) {
[Link]("Exception caught: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception caught: Array index is out of bounds.");
} catch (Exception e) {
[Link]("Exception caught: General exception occurred.");
} finally {
[Link]("Execution completed.");
}
}
}

Expected Output:

Exception caught: Division by zero is not allowed.


Execution completed.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 27


Object Oriented Programming Through Java Lab

c. Write a JAVA program for creation of Java Built-in Exceptions.

public class BuiltInExceptionsExample {


public static void main(String[] args) {
try {
// 1. ArithmeticException (Division by zero)
int a = 10, b = 0;
int result = a / b; // Causes ArithmeticException
[Link]("Result: " + result);

} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
}

try {
// 2. ArrayIndexOutOfBoundsException (Invalid index access)
int arr[] = {1, 2, 3};
[Link]("Array Element: " + arr[5]); // Causes ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception caught: " + e);
}

try {
// 3. NullPointerException (Accessing method on null object)
String str = null;
[Link]("String length: " + [Link]()); // Causes NullPointerException

} catch (NullPointerException e) {
[Link]("Exception caught: " + e);
}

[Link]("Program execution continued...");


}
}

Expected Output:

Exception caught: [Link]: / by zero


Exception caught: [Link]: Index 5 out of bounds for length 3
Exception caught: [Link]: Cannot invoke "[Link]()" because "str" is
null
Program execution continued...

Vijaya Institute Of Technology For Women (Autonomous) Page No: 28


Object Oriented Programming Through Java Lab

d. Write a JAVA program for creation of User Defined Exception.


// Creating a user-defined exception by extending Exception class
class InvalidAgeException extends Exception {
// Constructor to display custom message
InvalidAgeException(String message) {
super(message);
}
}

public class UserDefinedExceptionExample {


// Method to check age
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above to vote.");
} else {
[Link]("You are eligible to vote.");
}
}

public static void main(String[] args) {


try {
validateAge(16); // This will throw the custom exception
} catch (InvalidAgeException e) {
[Link]("Exception caught: " + [Link]());
}

[Link]("Program execution continued...");


}
}

Expected Output:

Exception caught: Age must be 18 or above to vote.


Program execution continued...

Vijaya Institute Of Technology For Women (Autonomous) Page No: 29


Object Oriented Programming Through Java Lab

Exercise - 7
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).

// Thread 1: Prints "Good Morning" every 1 second


class GoodMorningThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000); // 1 second delay
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}
// Thread 2: Prints "Hello" every 2 seconds
class HelloThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000); // 2 seconds delay
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}

// Thread 3: Prints "Welcome" every 3 seconds


class WelcomeThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Welcome");
[Link](3000); // 3 seconds delay
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
// Creating and starting threads
new GoodMorningThread().start();
new HelloThread().start();
new WelcomeThread().start();
}
}

Vijaya Institute Of Technology For Women (Autonomous) Page No: 30


Object Oriented Programming Through Java Lab

Expected Output:

Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
...

// Thread 1: Prints "Good Morning" every 1 second


class GoodMorningRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}

// Thread 2: Prints "Hello" every 2 seconds


class HelloRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000);
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}

// Thread 3: Prints "Welcome" every 3 seconds


class WelcomeRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Welcome");
[Link](3000);
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}

public class RunnableExample {

Vijaya Institute Of Technology For Women (Autonomous) Page No: 31


Object Oriented Programming Through Java Lab

public static void main(String[] args) {


// Creating thread objects using Runnable
Thread t1 = new Thread(new GoodMorningRunnable());
Thread t2 = new Thread(new HelloRunnable());
Thread t3 = new Thread(new WelcomeRunnable());

// Starting threads
[Link]();
[Link]();
[Link]();
}
}

Expected Output:

Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
...

Vijaya Institute Of Technology For Women (Autonomous) Page No: 32


Object Oriented Programming Through Java Lab

b. Write a program illustrating is Alive and join ().

class MyThread extends Thread {


public void run() {
try {
for (int i = 1; i <= 3; i++) {
[Link]([Link]().getName() + " - Count: " + i);
[Link](1000); // 1 second delay
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}
public class ThreadJoinIsAliveExample {
public static void main(String[] args) {
// Creating threads
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
// Starting threads
[Link]();
[Link]();
// Checking if threads are alive
[Link]("Thread t1 is alive: " + [Link]());
[Link]("Thread t2 is alive: " + [Link]());
try {
// Main thread waits for t1 and t2 to finish
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted: " + e);
}

// After threads finish


[Link]("Thread t1 is alive: " + [Link]());
[Link]("Thread t2 is alive: " + [Link]());
[Link]("Main thread execution completed.");
}
}

Expected Output:

Thread t1 is alive: true


Thread t2 is alive: true
Thread-0 - Count: 1
Thread-1 - Count: 1
Thread-0 - Count: 2
Thread-1 - Count: 2
Thread-0 - Count: 3
Thread-1 - Count: 3
Thread t1 is alive: false
Thread t2 is alive: false
Main thread execution completed.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 33


Object Oriented Programming Through Java Lab

c. Write a Program illustrating Daemon Threads.

class DaemonThreadExample extends Thread {


public void run() {
// Checking if the thread is daemon or not
if (isDaemon()) {
[Link]([Link]().getName() + " is a Daemon Thread.");
} else {
[Link]([Link]().getName() + " is a User Thread.");
}

try {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " - Count: " + i);
[Link](1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
[Link]("Thread Interrupted: " + e);
}
}
}
public class DaemonThreadDemo {
public static void main(String[] args) {
// Creating daemon and user threads
DaemonThreadExample t1 = new DaemonThreadExample(); // User thread
DaemonThreadExample t2 = new DaemonThreadExample(); // Daemon thread

[Link](true); // Setting thread t2 as daemon

// Starting both threads


[Link]();
[Link]();

// Main thread sleeps for 3 seconds


try {
[Link](3000);
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("Main thread finished execution.");
}
}

Expected Output:

Thread-0 is a User Thread.


Thread-1 is a Daemon Thread.
Thread-0 - Count: 1
Thread-1 - Count: 1
Thread-0 - Count: 2
Thread-1 - Count: 2
Thread-0 - Count: 3
Thread-1 - Count: 3
Main thread finished execution.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 34


Object Oriented Programming Through Java Lab

d. Write a JAVA program Producer Consumer Problem.


import [Link];
class SharedBuffer {
private LinkedList<Integer> buffer = new LinkedList<>();
private int capacity = 5; // Max buffer size

// Producer method
public synchronized void produce(int item) throws InterruptedException {
while ([Link]() == capacity) {
[Link]("Buffer is full. Producer waiting...");
wait(); // Wait if buffer is full
}

[Link](item);
[Link]("Produced: " + item);
notify(); // Notify consumer
}

// Consumer method
public synchronized int consume() throws InterruptedException {
while ([Link]()) {
[Link]("Buffer is empty. Consumer waiting...");
wait(); // Wait if buffer is empty
}

int item = [Link]();


[Link]("Consumed: " + item);
notify(); // Notify producer
return item;
}
}

// Producer thread
class Producer extends Thread {
private SharedBuffer buffer;

Producer(SharedBuffer buffer) {
[Link] = buffer;

Vijaya Institute Of Technology For Women (Autonomous) Page No: 35


Object Oriented Programming Through Java Lab

public void run() {


int item = 1;
try {
while (true) {
[Link](item++);
[Link](1000); // Simulate delay
}
} catch (InterruptedException e) {
[Link]("Producer interrupted.");
}
}
}

// Consumer thread
class Consumer extends Thread {
private SharedBuffer buffer;

Consumer(SharedBuffer buffer) {
[Link] = buffer;
}

public void run() {


try {
while (true) {
[Link]();
[Link](1500); // Simulate delay
}
} catch (InterruptedException e) {
[Link]("Consumer interrupted.");
}
}
}

// Main class
public class ProducerConsumerDemo {
public static void main(String[] args) {

Vijaya Institute Of Technology For Women (Autonomous) Page No: 36


Object Oriented Programming Through Java Lab

SharedBuffer buffer = new SharedBuffer();

// Creating Producer and Consumer threads


Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);

// Starting threads
[Link]();
[Link]();
}
}

Expected Output:

Produced: 1
Consumed: 1
Produced: 2
Produced: 3
Consumed: 2
Produced: 4
Produced: 5
Consumed: 3
Produced: 6
Buffer is full. Producer waiting...
Consumed: 4
Produced: 7
...

Vijaya Institute Of Technology For Women (Autonomous) Page No: 37


Object Oriented Programming Through Java Lab

Exercise – 8
a. Write a JAVA program that import and use the user defined packages.

// Declare the package


package mypackage;
public class Calculator {
// Method for addition
public int add(int a, int b) {
return a + b;
}
// Method for subtraction
public int subtract(int a, int b) {
return a - b;
}

// Method for multiplication


public int multiply(int a, int b) {
return a * b;
}
// Method for division
public double divide(int a, int b) {
if (b != 0) {
return (double) a / b;
} else {
[Link]("Error: Division by zero!");
return 0;
}
}
}

// Import the user-defined package


import [Link];
public class MainProgram {
public static void main(String[] args) {
// Creating an object of the Calculator class
Calculator calc = new Calculator();
// Using the methods
[Link]("Addition: " + [Link](10, 5));
[Link]("Subtraction: " + [Link](10, 5));
[Link]("Multiplication: " + [Link](10, 5));
[Link]("Division: " + [Link](10, 5));
}
}

Expected Output:

javac [Link]
java MainProgram

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

Vijaya Institute Of Technology For Women (Autonomous) Page No: 38


Object Oriented Programming Through Java Lab

b. Without writing any code, build a GUI that display text in label and image in an ImageView
(use JavaFX).

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class JavaFXLabelImageView extends Application {


@Override
public void start(Stage primaryStage) {
// Create a Label
Label label = new Label("Hello, JavaFX!");

// Load an image (Ensure the image file exists in the project directory)
Image image = new Image("file:[Link]"); // Change the path accordingly
ImageView imageView = new ImageView(image);

// Set ImageView properties


[Link](300); // Set width
[Link](true); // Maintain aspect ratio

// Create a VBox layout and add Label & ImageView


VBox root = new VBox(10, label, imageView);
[Link]("-fx-alignment: center; -fx-padding: 20;");

// Set the Scene and Stage


Scene scene = new Scene(root, 400, 400);
[Link]("JavaFX Label and ImageView");
[Link](scene);
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Expected Output:

A JavaFX window opens with:


1. A Label at the top displaying "Hello, JavaFX!".
2. An ImageView below the label showing an image ([Link]).
3. The VBox layout centers the elements and applies padding.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 39


Object Oriented Programming Through Java Lab

c. Build a Tip Calculator app using several JavaFX components and learn how to respond to
user interactions with the GUI.
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];

public class TipCalculatorApp extends Application {

@Override
public void start(Stage primaryStage) {
// Label and TextField for Bill Amount
Label billLabel = new Label("Enter Bill Amount:");
TextField billInput = new TextField();
[Link]("Enter amount");

// ChoiceBox for Tip Percentage


Label tipLabel = new Label("Select Tip Percentage:");
ChoiceBox<Integer> tipChoiceBox = new ChoiceBox<>();
[Link]().addAll(10, 15, 20);
[Link](15); // Default tip percentage

// Button to calculate tip


Button calculateButton = new Button("Calculate Tip");

// Labels for displaying results


Label tipAmountLabel = new Label("Tip Amount: $0.00");
Label totalAmountLabel = new Label("Total Amount: $0.00");

// Event Handling - Calculate tip on button click


[Link](e -> {
try {
double billAmount = [Link]([Link]());
int tipPercentage = [Link]();
double tipAmount = billAmount * tipPercentage / 100;
double totalAmount = billAmount + tipAmount;

Vijaya Institute Of Technology For Women (Autonomous) Page No: 40


Object Oriented Programming Through Java Lab

// Update Labels
[Link]([Link]("Tip Amount: $%.2f", tipAmount));
[Link]([Link]("Total Amount: $%.2f", totalAmount));
} catch (NumberFormatException ex) {
[Link]("Invalid input! Enter a valid number.");
[Link]("");
}
});

// Layout using VBox


VBox root = new VBox(10, billLabel, billInput, tipLabel, tipChoiceBox, calculateButton,
tipAmountLabel, totalAmountLabel);
[Link](new Insets(20));
[Link]("-fx-alignment: center;");

// Scene and Stage Setup


Scene scene = new Scene(root, 300, 250);
[Link]("Tip Calculator");
[Link](scene);
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

Expected Output & Functionality:

1. User enters the bill amount in the text field.


2. User selects a tip percentage (10%, 15%, 20%) from the ChoiceBox.
3. User clicks "Calculate Tip", and:
o Tip Amount is displayed.
o Total Amount (bill + tip) is displayed.

Vijaya Institute Of Technology For Women (Autonomous) Page No: 41


Object Oriented Programming Through Java Lab

Exercise-9:
a)Write a java program that connects to a database using JDBC
Step-by-Step Procedure
1. Import JDBC packages.
2. Load JDBC driver.
3. Establish connection with database.
4. Display success message.
5. Close connection.
Implementation:
import [Link];
import [Link];

class JdbcConnection
{
public static void main(String args[])
{
try
{
[Link]("[Link]");

Connection con = [Link](


"jdbc:mysql://localhost:3306/studentdb",
"root",
"root");

[Link]("Database Connected Successfully");

[Link]();
}

catch(Exception e)
{
[Link](e);
}
}
}

import [Link];
import [Link];

class JdbcConnection
{
public static void main(String args[])
{
try
{
[Link]("[Link]");

Connection con = [Link](


"jdbc:mysql://localhost:3306/studentdb",
"root",
"root");

[Link]("Database Connected Successfully");

Vijaya Institute Of Technology For Women (Autonomous) Page No: 42


Object Oriented Programming Through Java Lab
[Link]();
}

catch(Exception e)
{
[Link](e);
}
}
}

Explanation of the Code


• [Link]() loads MySQL JDBC driver.
• [Link]() establishes database connection.

Connection Syntax:
jdbc:mysql://localhost:3306/databasename
• [Link]() closes database connection.

Output
Database Connected Successfully

Vijaya Institute Of Technology For Women (Autonomous) Page No: 43


Object Oriented Programming Through Java Lab

b) Write a java program to connect to a database using JDBC and insert values into it.
Step-by-Step Procedure
1. Connect to database.
2. Create SQL INSERT query.
3. Execute query using Statement.
4. Display success message.
Implementation:
Import [Link];
Import [Link];
import [Link];

class JdbcInsert
{
public static void main(String args[])
{
try
{
[Link]("[Link]");

Connection con = [Link](


"jdbc:mysql://localhost:3306/studentdb",
"root",
"root");

Statement st = [Link]();

String query =
"insert into student values(101,'Ravi',85)";

[Link](query);

[Link]("Record Inserted Successfully");

[Link]();
}

catch(Exception e)
{
[Link](e);
}
}
}

Explanation of the Code


Statement object executes SQL queries.
Execute Update() is used for:
INSERT
UPDATE
DELETE
SQL Query Used:
Insert into student values(101,'Ravi',85)
OUTPUT:
Record Inserted SuccessfullY

Vijaya Institute Of Technology For Women (Autonomous) Page No: 44


Object Oriented Programming Through Java Lab

c) Write a java program to connect to a database using JDBC and delete values from it
Step-by-Step Procedure
1. Connect to database.
2. Write DELETE query.
3. Execute query.
4. Display success message.
Implementation:
import [Link];
import [Link];
import [Link];

class JdbcDelete
{
public static void main(String args[])
{
try
{
[Link]("[Link]");

Connection con = [Link](


"jdbc:mysql://localhost:3306/studentdb",
"root",
"root");

Statement st = [Link]();

String query =
"delete from student where id=101";

[Link](query);

[Link]("Record Deleted Successfully");

[Link]();
}

catch(Exception e)
{
[Link](e);
}
}
}

Explanation of the Code


• DELETE query removes records from table.

SQL Query Used:


Delete from student where id=101
• executeUpdate() executes delete operation.

Output
Record Deleted Successfully

Vijaya Institute Of Technology For Women (Autonomous) Page No: 45

You might also like