Exercise - 2
a) Write a JAVA program to search for an element in a given list of elements using
binary
search mechanism.
import [Link];
public class BinarySearchExample {
// Iterative implementation of binary search
public static int binarySearch(int[] arr, int target) {
int low = 0;
int high = [Link] - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Calculate mid to prevent potential
overflow
if (arr[mid] == target) {
return mid; // Element found, return its index
} else if (arr[mid] < target) {
low = mid + 1; // Target is in the right half
} else {
high = mid - 1; // Target is in the left half
}
}
return -1; // Element not found
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
// Example sorted array
int[] sortedArray = {5, 12, 23, 30, 45, 50, 67, 88, 91};
[Link]("Sorted array: ");
for (int num : sortedArray) {
[Link](num + " ");
[Link]();
[Link]("Enter the element to search: ");
int searchElement = [Link]();
int resultIndex = binarySearch(sortedArray, searchElement);
if (resultIndex != -1) {
[Link]("Element " + searchElement + " found at index: " +
resultIndex);
} else {
[Link]("Element " + searchElement + " not found in the
array.");
[Link]();
OUTPUT:
C:\Users\23>d:
D:\>cd foldername
D:\foldername>set path=C:\Program Files (x86)\Java\jdk1.7.0\bin
D:\foldername>javac [Link]
D:\foldername>java BinarySearch
Enter the number of elements: 9
Entera Elements (sorted or unsorted):
{5, 12,23,30,45,50, 67, 88, 91}
sorted adday: 5, 12,23,30,45, 50, 67,88,91
Enter the element to search: 50
Element Found at Position=5
b.).Write a JAVA program to sort for an element in a given list of elements using
bubble sort
import [Link];
public class BubbleSort {
/**
* Sorts an array of integers using the Bubble Sort algorithm.
* @param arr The array of integers to be sorted.
*/
public static void bubbleSort(int[] arr) {
int n = [Link];
// Outer loop for passes
for (int i = 0; i < n - 1; i++) {
// Inner loop for comparisons and swaps in each pass
// The (n - i - 1) reduces comparisons as the largest elements
// 'bubble up' to their correct positions at the end of the array
// in each pass.
for (int j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
public static void main(String[] args) {
int[] data = {64, 34, 25, 12, 22, 11, 90};
[Link]("Array before sorting: " + [Link](data));
bubbleSort(data); // Call the bubbleSort method
[Link]("Array after sorting: " + [Link](data));
OUTPUT:
Array before sorting: {64,34,25,12,22,11, 90}
Array after sorting: {11, 12,22,25,34,64,90}
c.).Write a JAVA program using String Buffer to delete, remove character
public class RemoveCharExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
[Link]("Original StringBuffer: " + sb);
// Remove the character at index 6 (which is 'W')
[Link](6);
[Link]("StringBuffer after deleting char at index 6: " + sb);
}
OUTPUT:
original string Buffer: Hello world
stringBuffer after deleting Char at index: Hello orld
2. Removing a range of characters using delete():
public class RemoveRangeExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java Programming");
[Link]("Original StringBuffer: " + sb);
// Remove characters from index 4 (inclusive) to index 11 (exclusive)
// This will remove " Program"
[Link](4, 11);
[Link]("StringBuffer after deleting range: " + sb);
}
}
OUTPUT:
original string Buffer: Java Programming
stringBuffer after deleting Char at index: Javamming
Exercise – 3
a) Write a JAVA program to implement class mechanism. Create a class, methods
and invoke
them inside main method
public class MyClass {
// Class fields (attributes)
String message;
int number;
// Constructor to initialize the object
public MyClass(String msg, int num) {
[Link] = msg;
[Link] = num;
}
// Instance method - operates on an instance of the class
public void displayInfo() {
[Link]("Message: " + message);
[Link]("Number: " + number);
}
// Static method - belongs to the class itself, not an instance
public static void greet() {
[Link]("Hello from the MyClass!");
}
// Main method - entry point of the program
public static void main(String[] args) {
// Invoking a static method directly using the class name
[Link]();
// Creating an object (instance) of MyClass
MyClass obj1 = new MyClass("First object", 10);
// Invoking an instance method on the object
[Link]();
// Creating another object
MyClass obj2 = new MyClass("Second object", 25);
// Invoking the instance method on the second object
[Link]();
}
}
OUTPUT:
Message: First object
Number: 10
Message: Second object
Number: 25
3.b)Write a JAVA program implement method overloading.
public class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two doubles
public double add(double a, double b) {
return a + b;
}
// Overloaded method to concatenate two strings
public String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
// Calling the method with two integer arguments
[Link]("Sum of 5 and 3: " + [Link](5, 3));
// Calling the method with three integer arguments
[Link]("Sum of 5, 3, and 2: " + [Link](5, 3, 2));
// Calling the method with two double arguments
[Link]("Sum of 2.5 and 3.7: " + [Link](2.5, 3.7));
// Calling the method with two string arguments
[Link]("Concatenation of 'Hello' and 'World': " +
[Link]("Hello", "World"));
}
}
OUTPUT:
Sum of 5 and 3 : 8
Sum of 5,3 and 2 : 10
Sum of 2.5 and 3.7 : 6.2
Concatenation of ‘Hello’ and ‘world’ : Helloworld
3.c) Write a JAVA program to implement constructor.
public class Car {
String model;
int year;
// Default Constructor
public Car() {
[Link] = "Unknown";
[Link] = 0;
[Link]("Default constructor called.");
}
// Parameterized Constructor
public Car(String model, int year) {
[Link] = model; // 'this' keyword refers to the current object's instance
variable
[Link] = year;
[Link]("Parameterized constructor called.");
}
// Method to display car information
public void displayCarInfo() {
[Link]("Model: " + model + ", Year: " + year);
}
public static void main(String[] args) {
// Creating an object using the default constructor
Car car1 = new Car();
[Link](); // Output: Model: Unknown, Year: 0
[Link](); // For better readability in output
// Creating an object using the parameterized constructor
Car car2 = new Car("Toyota Camry", 2023);
[Link](); // Output: Model: Toyota Camry, Year: 2023
}
}
Output :
Default Constructor called
Mode 1: Unknown ,Year : 0
Parameterized Constructor called
Mode 1 : Toyota Camry,Year : 2023
3.d)Write a JAVA program to implement constructor overloading
class Main {
String language;
// constructor with no parameter
Main() {
[Link] = "Java";
}
// constructor with a single parameter
Main(String language) {
[Link] = language;
}
public void getName() {
[Link]("Programming Language: " + [Link]);
}
public static void main(String[] args) {
// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
[Link]();
[Link]();
}
}
OUTPUT:
Programming Language: Java
Programming Language: Python
Exercise-4
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.");
// Main class to test the inheritance
public class SingleInheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
// Calling method from parent class
[Link]();
// Calling method from child class
[Link]();
OUTPUT:
This animal eats food
This Dog barks
4.b) Write a JAVA program to implement multi level Inheritance
// [Link] (Superclass)
class Animal {
void eat() {
[Link]("Animal eats");
void sleep() {
[Link]("Animal sleeps");
// [Link] (Intermediate class)
class Mammal extends Animal {
void walk() {
[Link]("Mammal walks");
// [Link] (Subclass)
class Dog extends Mammal {
void bark() {
[Link]("Dog barks");
public static void main(String[] args) {
Dog dog = new Dog();
[Link](); // Inherited from Animal
[Link](); // Inherited from Animal
[Link](); // Inherited from Mammal
[Link](); // Specific to Dog
OUTPUT:
Animal eats
Animal sleep
Animal walks
Dog barks
4.c) Write a JAVA program for abstract class to find areas of different shapes
// [Link] (Abstract class)
abstract class Shape {
abstract double calculateArea();
}
// [Link] (Subclass)
class Circle extends Shape {
private double radius;
Circle(double radius) {
[Link] = radius;
@Override
double calculateArea() {
return [Link] * radius * radius;
// [Link] (Subclass)
class Rectangle extends Shape {
private double length;
private double width;
Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
@Override
double calculateArea() {
return length * width;
// [Link] (Subclass)
class Triangle extends Shape {
private double base;
private double height;
Triangle(double base, double height) {
[Link] = base;
[Link] = height;
@Override
double calculateArea() {
return 0.5 * base * height;
}
// Main class
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
Triangle triangle = new Triangle(3.0, 7.0);
[Link]("Circle area: " + [Link]());
[Link]("Rectangle area: " + [Link]());
[Link]("Triangle area: " + [Link]());
OUTPUT:
Circle area: 78.53981633974483
Rectangle area: 24.0
Triangle area: 10.5
Exercise - 5
5. a) Write a JAVA program give example for “super” keyword
// Super keyword with variable
// Base class vehicle
class Vehicle {
int maxSpeed = 120;
// sub class Car extending vehicle
class Car extends Vehicle {
int maxSpeed = 180;
void display()
// print maxSpeed from the vehicle class
// using super
[Link]("Maximum Speed: "
+ [Link]);
// Driver Program
class Test {
public static void main(String[] args)
Car small = new Car();
[Link]();
OUTPUT:
Maximum speed : 120
5.b) Write a JAVA program to implement Interface. What kind of Inheritance can
be achieved?
// Java program to demonstrate the
// multiple inheritance in interface
// Interface to implement the
// addition and subtraction methods
interface Add_Sub {
public void add(double x, double y);
public void subtract(double x, double y);
// Interface to implement the multiplication
// and division
interface Mul_Div
{
public void multiply(double x, double y);
public void divide(double x, double y);
// Calculator interface which extends
// both the above defined interfaces
interface Calculator extends Add_Sub, Mul_Div
public void printResult(double result);
// Calculator class which implements the interface
public class MyCalculator implements Calculator
// Implementing the addition method
public void add(double x, double y) {
double result = x + y;
printResult(result);
// Implementing the subtraction method
public void subtract(double x, double y) {
double result = x - y;
printResult(result);
OUTPUT:
The result is : 15.0
The result is : 20.0
The result is : 54.0
The result is : 7.5
5.c) Write a JAVA program that implements Runtime polymorphism
// Java Program for Method Overriding
// Class 1
// Helper class
class Parent {
// Method of parent class
void Print() {
[Link]("parent class");
}
// Class 2
// Helper class
class subclass1 extends Parent {
// Method
void Print() {
[Link]("subclass1");
// Class 3
// Helper class
class subclass2 extends Parent {
// Method
void Print() {
[Link]("subclass2");
// Class 4
// Main class
class Geeks {
// Main driver method
public static void main(String[] args) {
// Creating object of class 1
Parent a;
// Now we will be calling print methods
// inside main() method
a = new subclass1();
[Link]();
a = new subclass2();
[Link]();
OUTPUT:
Subclass1
Subclass2
Exercise - 6
6. a) Write a JAVA program that describes exception handling mechanism
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
public class Main {
public static void main(String[] args) {
try {
// Code that might throw a custom exception
throw new CustomException("Custom exception occurred");
} catch (CustomException e) {
// Handle the custom exception
[Link]("Exception caught: " + [Link]());
OUTPUT:
Exception Caught : Custom exception occured
6.b) Write a JAVA program Illustrating Multiple catch clauses
Public class MultipleCatchClauses {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 10 / 0;
} catch (ArithmeticException e) {
[Link]("ArithmeticException caught: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException caught: " +
[Link]());
} catch (Exception e) {
[Link]("Exception caught: " + [Link]());
OUTPUT:
ArthmeticException caught : Zero
6.c) Write a JAVA program for creation of Java Built-in Exceptions
public class BuiltInExceptions {
public static void main(String[] args) {
try {
// ArithmeticException
int num = 10 / 0;
} catch (ArithmeticException e) {
[Link]("ArithmeticException caught: " + [Link]());
try {
// NullPointerException
String str = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("NullPointerException caught: " + [Link]());
try {
// ArrayIndexOutOfBoundsException
int[] arr = new int[5];
[Link](arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException caught: " +
[Link]());
}
OUTPUT:
ArithmeticException caught : /by zero
NullPointerException caught : cannot invoke "[Link]()" ,because “locall>" is
null
ArrayIndexOut Of BoundsException caught : Index 10 out of bounds for length 5