Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Write a Java program that first sorts an integer array using bubble sort an_20241230_223135_0000

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Write a Java program that first sorts an integer array using bubble sort an_20241230_223135_0000

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Write a Java program that first sorts an integer array using bubble sort

and then performs binary search to find a given element within the
sorted array
import java.util.Arrays;

public class BubbleBinary


{

public static void main(String[] args)


{
int[] arr = {64, 34, 25, 12, 22, 11, 90};

// Sort the array using bubble sort


bubbleSort(arr);
System.out.println("Sorted array: " +Arrays.toString(arr));

int x = 12;
int result = binarySearch(arr, x);

if (result != -1)
{
System.out.println("Element " + x + " is present at index " + result);
}
else
{
System.out.println("Element " + x + " is not present in array");
}
}

public static void bubbleSort(int[] arr)


{
int n = arr.length;
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;
}
}
}
}

public static int binarySearch(int[] arr, int x)


{
int low = 0;
int high = arr.length - 1;

while (low <= high)


{
int mid = low + (high - low) / 2;

// If x is greater, ignore left half


if (arr[mid] < x)
{
low = mid + 1;
}

// If x is smaller, ignore right half


else if (arr[mid] > x)
{
high = mid - 1;
}

// Otherwise, element is present at mid


else
{
return mid;
}
}

// If we reach here, then the element was not present


return -1;
}
1
}
Write a Java program to implement the selection
sort algorithm
Public class SelectionSort
{
Public static void sort(int[] arr)
{
Int n = arr.length;
// One by one move boundary of unsorted subarray
For (int I = 0; I < n – 1; i++)
{
// Find the minimum element in unsorted array
Int min_idx = I;
For (int j = I + 1; j < n; j++)
If (arr[j] < arr[min_idx])
Min_idx = j;
// Swap the found minimum element with the first
// element
Int temp = arr[min_idx];
Arr[min_idx] = arr[i];
Arr[i] = temp;
}
}
// Prints the array
Public static void printArray(int arr[])
{
Int n = arr.length;
For (int I = 0; I < n; ++i)
System.out.print(arr[i] + “ “);
System.out.println();
}
// Driver code
Public static void main(String args[])
{
Int arr[] = {64, 25, 12, 22, 11};
Sort(arr);
System.out.println(“Sorted array”);
printArray(arr);
}
2
}
Write a Java program to implement the insertion
sort algorithm
Public class InsertionSort
{
Public static void sort(int[] arr)
{
Int n = arr.length;
For (int I = 1; I < n; ++i)
{
Int key = arr[i];
Int j = I – 1;
/* Move elements of arr[0..i-1], that are
Greater than key, to one position ahead
Of their current position */
While (j >= 0 && arr[j] > key)
{
Arr[j + 1] = arr[j];
J = j – 1;
}
Arr[j + 1] = key;
}
}
/* Prints the array */
Public static void printArray(int arr[])
{
Int n = arr.length;
For (int I = 0; I < n; ++i)
System.out.print(arr[i] + “ “);
System.out.println();
}
// Driver program
Public static void main(String args[])
{
Int arr[] = {12, 11, 13, 5, 6};
InsertionSort ob = new InsertionSort();
Ob.sort(arr);
printArray(arr);
}
3
}
Write a Java program to find the transpose of a given matrix and
check if it is a symmetric matrix
Import java.util.Scanner;
Public class TransposeSymmetricMatrix
{
Public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Get matrix dimensions from user
System.out.print(“Enter the number of rows: “);
Int rows = scanner.nextInt();
System.out.print(“Enter the number of columns: “);
Int cols = scanner.nextInt();
// Create the matrix
Int[][] matrix = new int[rows][cols];
// Get matrix elements from user
System.out.println(“Enter the matrix elements:”);
For (int I = 0; I < rows; i++)
{
For (int j = 0; j < cols; j++)
{
Matrix[i][j] = scanner.nextInt();
}
}
// Transpose the matrix
Int[][] transposedMatrix = transpose(matrix);
// Print the original and transposed matrices
System.out.println(“Original Matrix:”);
printMatrix(matrix);
System.out.println(“Transposed Matrix:”);
printMatrix(transposedMatrix);
// Check if the matrix is symmetric
Boolean isSymmetric = isSymmetric(matrix);
System.out.println(“Is Symmetric: “ + isSymmetric);
Scanner.close();
}
// Function to transpose a matrix
Public static int[][] transpose(int[][] matrix)
{
Int rows = matrix.length;
Int cols = matrix[0].length;
Int[][] transposedMatrix = new int[cols][rows];
For (int I = 0; I < rows; i++)
{
For (int j = 0; j < cols; j++)
{
transposedMatrix[j][i] = matrix[i][j];
}
}
Return transposedMatrix;
}
// Function to check if a matrix is symmetric
Public static boolean isSymmetric(int[][] matrix)
{
Int rows = matrix.length;
Int cols = matrix[0].length;
// Check if the matrix is square
If (rows != cols)
{
Return false;
}
// Check if elements at corresponding positions are
equal
For (int I = 0; I < rows; i++)
{
For (int j = 0; j < cols; j++)
{
If (matrix[i][j] != matrix[j][i])
{
Return false;
}
}
}
Return true;
}
// Function to print a matrix
Public static void printMatrix(int[][] matrix)
{
For (int[] row : matrix)
{
For (int element : row)
{
System.out.print(element + “ “);
}
System.out.println();
}
}
4
}
Create a Java program that takes two matrices as
input and calculates their product
Import java.util.Scanner;
Public class MatrixMultiplication
{
Public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Get dimensions of matrices from the user
System.out.print(“Enter the number of rows for matrix 1: “);
Int rows1 = scanner.nextInt();
System.out.print(“Enter the number of columns for matrix 1: “);
Int cols1 = scanner.nextInt();
System.out.print(“Enter the number of rows for matrix 2: “);
Int rows2 = scanner.nextInt();
System.out.print(“Enter the number of columns for matrix 2: “);
Int cols2 = scanner.nextInt();
// Check if matrix multiplication is possible
If (cols1 != rows2)
{
System.out.println(“Matrix multiplication is not possible.”);
Return;
}
// Create matrices
Int[][] matrix1 = new int[rows1][cols1];
Int[][] matrix2 = new int[rows2][cols2];
Int[][] result = new int[rows1][cols2];
// Get matrix elements from the user
System.out.println(“Enter elements for matrix 1:”);
For (int I = 0; I < rows1; i++)
{
For (int j = 0; j < cols1; j++)
{
Matrix1[i][j] = scanner.nextInt();
}
}
System.out.println(“Enter elements for matrix 2:”);
For (int I = 0; I < rows2; i++)
{
For (int j = 0; j < cols2; j++)
{
Matrix2[i][j] = scanner.nextInt();
}
}
// Multiply matrices
For (int I = 0; I < rows1; i++)
{
For (int j = 0; j < cols2; j++)
{
For (int k = 0; k < cols1; k++)
{
Result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Print the result
System.out.println(“Product of the matrices:”);
For (int[] row : result)
{
For (int element : row)
{
System.out.print(element + “ “);
}
System.out.println();
}
Scanner.close();
} 5
}
Create a Java program that takes a matrix as input and determines the
maximum and minimum elements along with their indices
Import java.util.Scanner;
Public class MatrixMinMax
{
Public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Get matrix dimensions from the user
System.out.print(“Enter the number of rows: “);
Int rows = scanner.nextInt();
System.out.print(“Enter the number of columns: “);
Int cols = scanner.nextInt();
// Create the matrix
Int[][] matrix = new int[rows][cols];
// Get matrix elements from the user
System.out.println(“Enter the matrix elements:”);
For (int I = 0; I < rows; i++
{
For (int j = 0; j < cols; j++)
{
Matrix[i][j] = scanner.nextInt();
}
}
// Find maximum and minimum elements
Int max = matrix[0][0];
Int min = matrix[0][0];
Int maxRow = 0;
Int maxCol = 0;
Int minRow = 0;
Int minCol = 0;
For (int I = 0; I < rows; i++)
{
For (int j = 0; j < cols; j++)
{
If (matrix[i][j] > max)
{
Max = matrix[i][j];
maxRow = I;
maxCol = j;
}
If (matrix[i][j] < min)
{
Min = matrix[i][j];
minRow = I;
minCol = j;
}
}
}
// Print the results
System.out.println(“Maximum element: “ + max + “
at position (“ + maxRow + “, “ + maxCol + “)”);
System.out.println(“Minimum element: “ + min + “ at
position (“ + minRow + “, “ + minCol + “)”);
Scanner.close();
}
} 6
Design a Java class to represent an amount with rupees and paisa. Implement
object passing to add two amounts and display the resulting amount
Class Amount
{
Private int rupees;
Private int paisa;
Public Amount(int rupees, int paisa)
{
This.rupees = rupees;
This.paisa = paisa;
}
Public void add(Amount other)
{
This.paisa += other.paisa;
This.rupees += other.rupees;
// Adjust paisa if it exceeds 99
While (this.paisa >= 100)
{
This.paisa -= 100;
This.rupees++;
}
}
Public void display()
{
System.out.println(“Rupees: “ + this.rupees + “, Paisa: “ + this.paisa);
}
}
Public class AddAmounts
{
Public static void main(String[] args)
{
Amount amount1 = new Amount(10, 50);
Amount amount2 = new Amount(20, 75);
System.out.println(“Amount 1:”);
Amount1.display();
System.out.println(“Amount 2:”);
Amount2.display();
// Add amount2 to amount1
Amount1.add(amount2);
System.out.println(“\nAmount 1 after adding Amount 2:”);
Amount1.display();
}
7
}
Design a Java class to represent time. Implement a method within the class to
find the difference between two time objects and display the result
class Time
{
private int hours;
private int minutes;
private int seconds;
public Time(int hours, int minutes, int seconds)
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public void setTime(int hours, int minutes, int seconds)
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public void showTime()
{
System.out.println(hours + ":" + minutes + ":" + seconds);
}
public Time difference(Time t2)
{
int totalSeconds1 = this.hours * 3600 + this.minutes * 60 + this.seconds;
int totalSeconds2 = t2.hours * 3600 + t2.minutes * 60 + t2.seconds;
int diffSeconds = totalSeconds1 - totalSeconds2;
// Handle negative differences
if (diffSeconds < 0)
{
diffSeconds += 24 * 3600; // Adjust for 24-hour format
}
int diffHours = diffSeconds / 3600;
diffSeconds %= 3600;
int diffMinutes = diffSeconds / 60;
diffSeconds %= 60;
return new Time(diffHours, diffMinutes, diffSeconds);
}
}
public class TimeDifference
{
public static void main(String[] args)
{
Time time1 = new Time(10, 30, 30);
Time time2 = new Time(5, 45, 15);
Time difference = time1.difference(time2);
System.out.println("Time 1:");
time1.showTime();
System.out.println("Time 2:");
time2.showTime();
System.out.println("Time Difference:");
difference.showTime();
} 8
}
Create a Java class to represent binary numbers. Include a method within the
class to add two binary numbers and return the result as a new binary
number object
Class Binary
{
Private String binaryString;
Public Binary(String binaryString)
{
This.binaryString = binaryString;
}
Public Binary add(Binary other)
{
// Ensure both binary strings have the same length
Int maxLength = Math.max(this.binaryString.length(), other.binaryString.length());
This.binaryString = padLeftWithZeros(this.binaryString, maxLength);
Other.binaryString = padLeftWithZeros(other.binaryString, maxLength);
StringBuilder result = new StringBuilder();
Int carry = 0;
For (int I = maxLength – 1; I >= 0; i--)
{
Int bit1 = Character.getNumericValue(this.binaryString.charAt(i));
Int bit2 = Character.getNumericValue(other.binaryString.charAt(i));
Int sum = bit1 + bit2 + carry;
If (sum >= 2)
{
Carry = 1;
Sum -= 2;
}
Else
{
Carry = 0;
}
Result.insert(0, sum);
}
If (carry == 1)
{
Result.insert(0, 1);
}
Return new Binary(result.toString());
}
Private String padLeftWithZeros(String str, int length
{
StringBuilder sb = new StringBuilder();
For (int I = str.length(); I < length; i++)
{
Sb.append(“0”);
}
Sb.append(str);
Return sb.toString();
}
Public void display()
{
System.out.println(“Binary: “ + binaryString);
}
}
Public class BinaryAddition
{
Public static void main(String[] args)
{
Binary binary1 = new Binary(“1101”);
Binary binary2 = new Binary(“1010”);
System.out.println(“Binary 1:”);
Binary1.display();
System.out.println(“Binary 2:”);
Binary2.display();
Binary sum = binary1.add(binary2);
System.out.println(“\nSum:”);
Sum.display();
} 9
}
Write a Java program to convert a given sentence into a palindrome sentence by either
keeping the word as it is (if it's already a palindrome) or appending its reverse to it
Import java.util.Scanner;
Public class PalindromeSentence
{
Public static boolean isPalindrome(String word)
{
Int left = 0;
Int right = word.length() – 1;
While (left < right)
{
If (Character.toLowerCase(word.charAt(left)) != Character.toLowerCase(word.charAt(right)))
{
Return false;
}
Left++;
Right--;
}
Return true;
}
Public static String reverseWord(String word)
{
StringBuilder reversed = new StringBuilder();
For (int I = word.length() – 1; I >= 0; i--)
{
Reversed.append(word.charAt(i));
}
Return reversed.toString();
}
Public static String convertToPalindromeSentence(String sentence)
{
String[] words = sentence.split(“ “);
StringBuilder palindromeSentence = new StringBuilder();
For (String word : words)
{
If (isPalindrome(word))
{
palindromeSentence.append(word).append(“ “);
}
Else
{
palindromeSentence.append(word).append(reverseWord(word)).append(“ “);
}
}
Return palindromeSentence.toString().trim();
}
Public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a sentence: “);
String sentence = scanner.nextLine();
String palindromeSentence = convertToPalindromeSentence(sentence);
System.out.println(“Palindrome sentence: “ + palindromeSentence);
} 10
}
Create a Java program that takes a string as input
and prints each character of the string on a new line

Public class PrintTeamNameVertically


{
Public static void main(String[] args)
{
String teamName = “JavaWarriors”;
// Print each character of the team name on a new line
For (int I = 0; I < teamName.length(); i++)
{
System.out.println(teamName.charAt(i));
}
}
}

11
Create a Java program that decodes a string encoded with integer values,
where each integer represents the position of a letter in the alphabet
Public class StringDecoder
{
Public static String decode(String encodedString)
{
StringBuilder decodedString = new StringBuilder();
String[] indices = encodedString.split(“,”);
For (String indexStr : indices)
{
Try {
Int index = Integer.parseInt(indexStr);
If (index >= 1 && index <= 26)
{
Char decodedChar = (char) (‘a’ + index – 1);
decodedString.append(decodedChar);
}
else
{
decodedString.append(“?”); // Handle invalid indices
}
} catch (NumberFormatException e)
{
decodedString.append(“?”); // Handle non-numeric
characters
}
}
Return decodedString.toString();
}
Public static void main(String[] args)
{
String encodedString = “1,2,3,1,13,5,2,5”;
String decodedString = decode(encodedString);
System.out.println(“Encoded String: “ + encodedString);
System.out.println(“Decoded String: “ + decodedString);
}
12
}
Write a Java program to arrange all the
letters of a given string in alphabetical order

Import java.util.Arrays;
Public class SortStringAlphabetically
{
Public static void main(String[] args)
{
String inputString = “hello”;
// Convert the string to a character array
Char[] charArray = inputString.toCharArray();
// Sort the character array
Arrays.sort(charArray);
// Convert the sorted character array back to a string
String sortedString = new String(charArray);
System.out.println(“Input string: “ + inputString);
System.out.println(“Output string (alphabetical order): “ + sortedString);
}
}

13
Create a Java program that performs binary
search on an array using a recursive function
Public class BinarySearchRecursive
{
Public static int binarySearch(int[] arr, int low, int high, int x)
{
If (high >= low)
{
Int mid = low + (high – low) / 2;
// If the element is present at the middle itself
If (arr[mid] == x)
Return mid;
// If the element is smaller than mid, then it can only
// be present in left subarray
If (arr[mid] > x)
Return binarySearch(arr, low, mid – 1, x);
// Else the element can only be present in right subarray
Return binarySearch(arr, mid + 1, high, x);
}
// We reach here when the element is not present in array
Return -1;
}
Public static void main(String args[])
{
Int arr[] = { 2, 3, 4, 10, 40 };
Int x = 10;
Int n = arr.length;
Int result = binarySearch(arr, 0, n – 1, x);
If (result == -1)
System.out.println(“Element not present”);
Else
System.out.println(“Element found at index “ + result);
}
} 14
Create a Java program that uses recursion to convert a
binary number (represented as a string) to its decimal value

Public class BinaryToDecimalRecursive


{
Public static int binaryToDecimal(String binary)
{
If (binary.isEmpty()) {
Return 0;
}
else
{
Int lastDigit = Integer.parseInt(String.valueOf(binary.charAt(binary.length() – 1)));
Return lastDigit * (int) Math.pow(2, binary.length() – 1)
+ binaryToDecimal(binary.substring(0, binary.length() – 1));
}
}
Public static void main(String[] args)
{
String binaryString = “1101”;
Int decimal = binaryToDecimal(binaryString);
System.out.println(“Binary: “ + binaryString);
System.out.println(“Decimal: “ + decimal);
}
}

15
Create a Java program that checks
whether a number is a circular prime
Import java.util.Scanner;
Public class CircularPrime
{
Public static boolean isPrime(int num)
{
If (num <= 1)
{
Return false;
}
For (int I = 2; I <= Math.sqrt(num); i++)
{
If (num % I == 0)
{
Return false;
}
}
Return true;
}
Public static int rotate(int num)
{
Int lastDigit = num % 10;
Int remainingDigits = num / 10;
Int rotatedNum = lastDigit * (int) Math.pow(10, String.valueOf(remainingDigits).length()) + remainingDigits;
Return rotatedNum;
}
Public static boolean isCircularPrime(int num)
{
If (!isPrime(num))
{
Return false;
}
Int temp = num;
Int digits = String.valueOf(num).length();
For (int I = 0; I < digits – 1; i++)
{
Temp = rotate(temp);
If (!isPrime(temp))
{
Return false;
}
}
Return true;
}
Public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a number: “);
Int num = scanner.nextInt();
If (isCircularPrime(num))
{
System.out.println(num + “ is a circular prime number.”);
}
else
{
System.out.println(num + “ is not a circular prime number.”);
}
Scanner.close();
} 16
}
Write a Java program to check if a given even
number satisfies the Goldbach conjecture
Public class GoldbachConjecture
{
Public static boolean isPrime(int num)
{
If (num <= 1)
{
Return false;
}
For (int I = 2; I * I <= num; i++)
{
If (num % I == 0)
{
Return false;
}
}
Return true;
}
Public static boolean isGoldbachNumber(int num)
{
If (num <= 2 || num % 2 != 0)
{
Return false;
}
For (int I = 2; I <= num / 2; i++)
{
If (isPrime(i) && isPrime(num – i))
{
Return true;
}
}
Return false;
}
Public static void main(String[] args)
{
Int evenNumber = 28; // Example even number
If (isGoldbachNumber(evenNumber))
{
System.out.println(evenNumber + “ is a Goldbach number.”);
}
else
{
System.out.println(evenNumber + “ is not a Goldbach number.”);
}
} 17
}
Create a Java program that displays the
current date and time in various formats
Import java.text.SimpleDateFormat;
Import java.util.Date;
Public class DateFormatExample
{
Public static void main(String[] args)
{
// Get current date and time
Date currentDate = new Date();
// Create SimpleDateFormat objects with different patterns
SimpleDateFormat dateFormat1 = new SimpleDateFormat(“yyyy-MM-dd”);
SimpleDateFormat dateFormat2 = new SimpleDateFormat(“dd/MM/yyyy”);
SimpleDateFormat dateFormat3 = new SimpleDateFormat(“MM/dd/yyyy”);
SimpleDateFormat dateFormat4 = new SimpleDateFormat(“E, MMM dd yyyy”);
SimpleDateFormat dateFormat5 = new SimpleDateFormat(“hh:mm:ss a”);
SimpleDateFormat dateFormat6 = new SimpleDateFormat(“HH:mm:ss”);
// Format the date using different patterns
String dateString1 = dateFormat1.format(currentDate);
String dateString2 = dateFormat2.format(currentDate);
String dateString3 = dateFormat3.format(currentDate);
String dateString4 = dateFormat4.format(currentDate);
String dateString5 = dateFormat5.format(currentDate);
String dateString6 = dateFormat6.format(currentDate);
// Print the formatted dates
System.out.println(“Date 1 (yyyy-MM-dd): “ + dateString1);
System.out.println(“Date 2 (dd/MM/yyyy): “ + dateString2);
System.out.println(“Date 3 (MM/dd/yyyy): “ + dateString3);
System.out.println(“Date 4 (E, MMM dd yyyy): “ + dateString4);
System.out.println(“Date 5 (hh:mm:ss a): “ + dateString5);
System.out.println(“Date 6 (HH:mm:ss): “ + dateString6);
}
}

18
Create a Java application that allows a user to enter the principal amount, annual
interest rate, and time period in years. The program should then calculate and
display both the simple interest and compound interest earned on the principal
import java.util.Scanner;

public class InterestCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the principal amount: ");


double principal = scanner.nextDouble();

System.out.print("Enter the rate of interest: ");


double rate = scanner.nextDouble();

System.out.print("Enter the time period in years: ");


double time = scanner.nextDouble();

// Calculate simple interest


double simpleInterest = (principal * rate * time) / 100;

// Calculate compound interest (assuming annual compounding)


double compoundInterest = principal * Math.pow(1 + (rate / 100), time) - principal;

System.out.println("Simple Interest: " + simpleInterest);


System.out.println("Compound Interest: " + compoundInterest);

scanner.close();
}
}

19
Create a Java class named 'D2Point' to represent a point in a two-dimensional plane. The class
should have the following:
* Private instance variables for x and y coordinates.
* A constructor to initialize the x and y coordinates.
* Getter methods to access the x and y coordinates.
* Methods to add, subtract, and multiply (by a scalar) two D2Point objects.
* A method to calculate the distance between two D2Point objects.
* A toString() method to provide a string representation of the point
public class D2Point {
private double x;
private double y;

public D2Point(double x, double y) {


this.x = x;
this.y = y;
}

public double getX() {


return x;
}

public double getY() {


return y;
}

public D2Point add(D2Point other) {


return new D2Point(this.x + other.x, this.y + other.y);
}

public D2Point subtract(D2Point other) {


return new D2Point(this.x - other.x, this.y - other.y);
}

public D2Point multiply(double scalar) {


return new D2Point(this.x * scalar, this.y * scalar);
}

public double distance(D2Point other) {


double dx = this.x - other.x;
double dy = this.y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}

@Override
public String toString() {
return "(" + x + ", " + y + ")";
}

public static void main(String[] args) {


D2Point point1 = new D2Point(2.5, 3.1);
D2Point point2 = new D2Point(1.2, -0.5);

System.out.println("Point 1: " + point1);


System.out.println("Point 2: " + point2);

D2Point sum = point1.add(point2);


System.out.println("Point 1 + Point 2: " + sum);

D2Point difference = point1.subtract(point2);


System.out.println("Point 1 - Point 2: " + difference);

D2Point scaled = point1.multiply(2.0);


System.out.println("Point 1 * 2.0: " + scaled);

double distance = point1.distance(point2);


System.out.println("Distance between Point 1 and Point 2: " + distance);
} 20
}
Design a Java program to calculate the areas of different geometric shapes using
an interface. Create an interface named 'Shape' with a method 'calculateArea()'.
Implement the 'Shape' interface in two classes: 'Circle' and 'Rectangle'. Each class
should have appropriate constructors and implement the 'calculateArea()'
method according to its specific shape. Write a test class to create objects of
these classes and demonstrate the use of polymorphism to calculate their areas
interface Shape {
double calculateArea();
}

class Circle implements Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

class Rectangle implements Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double calculateArea() {
return width * height;
}
}

public class AreaCalculator {


public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);

System.out.println("Area of circle: " + circle.calculateArea());


System.out.println("Area of rectangle: " + rectangle.calculateArea());
}
21
}
Write a Java program that demonstrates the use of the Stack class.
Create a stack of integers, push some elements onto the stack, and
then pop all the elements from the stack and print them to the console
import java.util.Stack;

public class StackExample {

public static void main(String[] args) {


// Create a new stack
Stack<Integer> stack = new Stack<>();

// Push elements onto the stack


stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);

// Print the stack


System.out.println("Stack: " + stack);

// Pop elements from the stack


while (!stack.isEmpty()) {
System.out.println("Popped element: " +
stack.pop());
}
}
} 22
Write a Java program that demonstrates the use of the Queue
interface. Create a queue of integers, enqueue some elements, and then
dequeue all the elements from the queue and print them to the console

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

public static void main(String[] args) {


// Create a queue
Queue<Integer> queue = new LinkedList<>();

// Enqueue elements
queue.add(1);
queue.add(2);
queue.add(3);

System.out.println("Queue: " + queue);

// Dequeue elements
while (!queue.isEmpty()) {
System.out.println("Dequeued: " + queue.remove());
}
}
}

23

You might also like