0% found this document useful (0 votes)
14 views38 pages

Java Programs for Sorting and Linked Lists

Uploaded by

rudragadhavi4611
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)
14 views38 pages

Java Programs for Sorting and Linked Lists

Uploaded by

rudragadhavi4611
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

Name: RUDRA GADHAVI

ROLL NO: 631

1. Write a java program to enter strings at command line input and then sort strings into ascending order. Ans:
import [Link];
public class SortStrings
{
public static void main(String[] args){ // Check if command-line arguments are passed
if ([Link] == 0)
{
[Link]("Please enter some strings as command-line arguments.");
return;
}
// Sort the strings in ascending order
[Link](args);

// Display the sorted strings


[Link]("Sorted strings in ascending order:");
for (String str : args)
{
[Link](str);
}
}
}

1
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

2. Write a java program to create EMPLOYEE class with name, age and salary data members. Take input (data) from
user and create minimum 5 objects of employee class. Display all employees data in ascending order of salary.
Ans:
[Link];
class Employee {
String name;
int age;
double salary;

// Constructor to initialize the Employee object


public Employee(String name, int age, double salary)
{
[Link] = name;
[Link] = age;
[Link] = salary;
}
// Override toString method to display employee details
@Override public String toString()
{
return "Name: " + name + ", Age: " + age + ", Salary: " + salary;
}
}
public class EmployeeManagement
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
// Create an array to store employee objects
Employee[] employees = new Employee[5];

// Taking input for 5 employees


for (int i = 0; i < 5; i++)
{
[Link]("Enter details for Employee " + (i + 1) + ":");
[Link]("Name: ");
String name = [Link]();
[Link]("Age: "); int age
= [Link]();
[Link]("Salary: ");
double salary = [Link]();
[Link]();

2
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

// Consume the leftover newline character


employees[i] = new Employee(name, age, salary);
}
// Sort the employees array based on salary in ascending order
[Link](employees, (e1, e2) -> [Link]([Link], [Link]));

// Display all employee data in ascending order of salary


[Link]("\nEmployees sorted by Salary (Ascending Order):");
for (Employee employee : employees)
{
[Link](employee);
}
[Link]();
}

3
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

4
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

3. Write a java program to. create and display Singly linked list and perform following task:
1. Insert node at specific position.
2. Delete node from specific position. Ans:
import [Link];
// Node class to represent each element in the linked list
class Node {
int data;
Node next;
public Node(int data)
{
[Link] = data;
[Link] = null;
}
}
class SinglyLinkedList
{
Node head;
// Constructor to initialize the linked list
public SinglyLinkedList()
{
head = null;
}
// Method to display the linked list
public void display()
{
if (head == null)
{
[Link]("The list is empty.");
return;
}
Node current = head;
while (current != null)
{
[Link]([Link] + " -> ");
current = [Link];
}
[Link]("null");
}
// Method to insert a node at a specific position
public void insertAtPosition(int data, int position){
Node newNode = new Node(data);

5
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

if (position == 0)
{
// Insert at the beginning
[Link] = head;
head = newNode; return;
}
Node current = head;
int count = 0;
// Traverse the list to find the node just before the desired position
while (current != null && count < position - 1)
{
current = [Link];
count++;
}
if (current == null)
{
[Link]("Position is out of range.");
}
else
{
// Insert the new node after the current node
[Link] = [Link];
[Link] = newNode;
}
}
// Method to delete a node at a specific position
public void deleteAtPosition(int position)
{
if (head == null)
{
[Link]("The list is empty.");
return;
}

if (position == 0)
{
// Delete the first node
head = [Link];
return;
}

6
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

Node current = head;


int count = 0;

// Traverse to the node just before the desired position


while (current != null && count < position - 1)
{
current = [Link];
count++;
}
if (current == null || [Link] == null)
{
[Link]("Position is out of range.");
}
else
{
// Skip the node at the specified position
[Link] = [Link];
}
}
}

public class SinglyLinkedListDemo


{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
SinglyLinkedList list = new SinglyLinkedList();

// Inserting some initial nodes


[Link](10, 0);
[Link](20, 1);
[Link](30, 2); [Link](40,
3);
[Link](50, 4);

// Display the initial list


[Link]("Initial linked list:");
[Link]();

// Insert node at a specific position


[Link]("\nEnter the position to insert a new node: ");

7
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

int insertPosition = [Link]();


[Link]("Enter the data for the new node: ");
int insertData = [Link]();
[Link](insertData, insertPosition);

// Display the list after insertion

[Link]("\nLinked list after insertion:");


[Link]();

// Delete node from a specific position


[Link]("\nEnter the position to delete a node: ");
int deletePosition = [Link]();
[Link](deletePosition);

// Display the list after deletion


[Link]("\nLinked list after deletion:");
[Link]();
[Link]();
}
}

8
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

4. Write an application that execute two Threads. One thread display "BCA" every 1000 milliseconds and the order
displays "MCA" every 3000 milliseconds. Create the threads by extending the thread class. Ans:
// Thread class to print "BCA"
class BCAThread extends Thread
{
public void run()
{
try {
while (true)
{
[Link]("BCA");
[Link](1000); // Sleep for 1000 milliseconds
}
}
catch (InterruptedException e)
{
[Link](e);
}
}
}
// Thread class to print "MCA" class MCAThread extends Thread {
public void run()
{
try {
while (true)
{
[Link]("MCA");
[Link](3000); // Sleep for 3000 milliseconds
}
}
catch (InterruptedException e)
{
[Link](e);
}
}
}
public class ThreadExample
{
public static void main(String[] args)
{

9
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

// Creating instances of the thread classes

BCAThread bcaThread = new BCAThread();


MCAThread mcaThread = new MCAThread();

// Starting the threads


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

5. Write a java program to create a player history that can be display in the following form. Player name and team
name is stored in Player class. Score of test match and One Day match in the other class say Run class number of
One Day match and number of test match must be in Match class and finally calculate the average. The package 1
contains Player, Run and Match classes, Where package2 contain main() class. Ans:

10
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

File 4: [Link] (in package2)


package package2;
import [Link];
import [Link];
11
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

import [Link];

public class MainClass


{
public static void main(String[] args)
{
// Creating instances of Player, Run, and Match classes
Player player = new Player("Virat Kohli", "India");
Run run = new Run(7540, 12820); // Test match runs and One Day runs
Match match = new Match(100, 250); // Number of Test and One Day matches

// Calculating averages
double testMatchAverage = (double) [Link]() / [Link]();
double oneDayMatchAverage = (double) [Link]()/[Link]();

// Displaying player history


[Link]("Player Name: " + [Link]());
[Link]("Team Name: " + [Link]());
[Link]("Test Match Runs: " + [Link]());
[Link]("One Day Match Runs: " + [Link]());
[Link]("Number of Test Matches: " + [Link]());
[Link]("Number of One Day Matches: " + [Link]());
[Link]("Test Match Average: %.2f%n", testMatchAverage);
[Link]("One Day Match Average: %.2f%n", oneDayMatchAverage);
}
}

6. A. Write a java program to design a class Mystring having data member of type String add member function to
achieve following task. i. Reverse String ii. String in tOGGLECASE iii. Sentence case iv. Extract N-Characters from

12
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

right-end of the string Write a menu driven program to call these methods Mystring Class. The program must use
Exception handling.
Ans:
import [Link];
class MyString
{
private String str;

public MyString(String str)


{
[Link] = str;
}

// Reverse the string


public String reverseString()
{
StringBuilder reversed = new StringBuilder(str);
return [Link]().toString();
}

// Convert the string to tOGGLE cASE


public String toggleCase()
{
StringBuilder toggled = new StringBuilder();
for (char c : [Link]())
{
if ([Link](c))
{
[Link]([Link](c));
}
else if ([Link](c))
{
[Link]([Link](c));
}
else
{
[Link](c);
}
}
return [Link]();
}

13
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

// Convert the string to Sentence case


public String sentenceCase()
{
if (str == null || [Link]()) return str;
return [Link]([Link](0)) + [Link](1).toLowerCase();
}

// Extract N characters from the right end of the string


public String extractRight(int n) throws Exception
{
if (n > [Link]())
{
throw new Exception("N is greater than the length of the string.");
}
return [Link]([Link]() - n);
}
}

public class Main


{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();
MyString myString = new MyString(inputString);
while (true)
{
[Link]("\nMenu:");
[Link]("1. Reverse String");
[Link]("2. Convert to tOGGLE cASE");
[Link]("3. Convert to Sentence Case");
[Link]("4. Extract N Characters from Right-End");
[Link]("5. Exit");
[Link]("Choose an option: ");
int choice = [Link]();
try {

switch (choice)
{
case 1:
14
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

[Link]("Reversed String: " + [Link]());


break;

case 2:
[Link]("tOGGLE cASE String: " + [Link]());
break;

case 3:
[Link]("Sentence Case String: " + [Link]());
break;
case
4:
[Link]("Enter the value of N: ");
int n = [Link]();
[Link]("Extracted String: " + [Link](n));
break;

case 5:
[Link]("Exiting the program.");
[Link]();
return;
default:
[Link]("Invalid choice. Please choose a valid option.");
}
}
catch (Exception e)
{
[Link]("Error: " + [Link]());
}
}
}
}

15
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

7. Write a java program that creates Singly Link List to perform create, insert, delete and display node using menu
driven program.
Ans: import
[Link];
class Node
{
int data;
Node next; public
Node(int data)
{
[Link] = data;
[Link] = null;
}
}

class SinglyLinkedList
{
private Node head;

// Create or append a node


public void create(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
}
else
16
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

{
Node temp = head;
while ([Link] != null)
{
temp = [Link];
}
[Link] = newNode;
}
}

// Insert a node at a specific position


public void insert(int data, int position)
{
Node newNode = new Node(data);
if (position == 1)
{
[Link] = head;
head = newNode;
}
Else
{
Node temp = head;
for (int i = 1; i < position - 1 && temp != null; i++)
{
temp = [Link];
}
if (temp != null)
{
[Link] = [Link];
[Link] = newNode;
}
else
{
[Link]("Invalid position!");
}
}
}

// Delete a node by value


public void delete(int data)
{
if (head == null)
17
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

{
[Link]("List is empty!");
return;
}
if ([Link] == data)
{
head = [Link];
return;
}
Node temp = head;
while ([Link] != null && [Link] != data)
{
temp = [Link];
}
if ([Link] != null)
{
[Link] = [Link];
}
else {
[Link]("Node not found!");
}
}
// Display the linked list
public void display()
{
if (head == null)
{
[Link]("List is empty!");
return;
}
Node temp = head;
while (temp != null)
{
[Link]([Link] + " -> ");
temp = [Link];
}
[Link]("null");
}
}

Public class Main


{
18
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

public static void main(String[] args)


{
Scanner scanner = new Scanner([Link]);
SinglyLinkedList list = new SinglyLinkedList(); while (true)
{
[Link]("\nMenu:");
[Link]("1. Create/Add Node");
[Link]("2. Insert Node at Position");
[Link]("3. Delete Node by Value");
[Link]("4. Display List");
[Link]("5. Exit");
[Link]("Enter your choice: ");

int choice = [Link]();


switch (choice)
{
case 1:
[Link]("Enter value to add: ");
int data = [Link]();
[Link](data);
break;

case 2:
[Link]("Enter value to insert: ");
int insertData = [Link]();
[Link]("Enter position: "); int
position = [Link]();
[Link](insertData, position); break;

case 3:
[Link]("Enter value to delete: ");
int deleteData = [Link]();
[Link](deleteData); break;

case 4:
[Link]("Linked List:");
[Link](); break;
case
5:
[Link]("Exiting program.");
[Link](); return;
default:

19
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

[Link]("Invalid choice! Please try again.");


}
}
}
}

8. Write a java application which accepts two strings. Merge both the strings using alternate characters of each one.
For example: If String1 is: "Very", and String2 is: "Good". Then result should be: "VGeoroyd". Ans:
import [Link];
public class AlternateMerge
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
// Accepting input strings
[Link]("Enter first string: ");
String string1 = [Link]();
[Link]("Enter second string: ");
String string2 = [Link]();

// Merging strings alternately


StringBuilder mergedString = new StringBuilder();
int maxLength = [Link]([Link](), [Link]());

for (int i = 0; i < maxLength; i++)


{
if (i < [Link]())
{
20
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

[Link]([Link](i));
}
if (i < [Link]())
{
[Link]([Link](i)); }
}
// Displaying the result
[Link]("Merged String: " + [Link]());
[Link]();
}
}

9. Write a Java program that prompts the user to input the base and height of a triangle. Accordingly calculates and
displays the area of a triangle using the formula (base* height) / 2, and handles any input errors such as
nonnumeric inputs or negative values for base or height. Additionally, include error messages for invalid input
and provide the user with the option to input another set of values or exit the program. Ans:
import [Link];
public class TriangleArea
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);

while (true)
{
try
{
// Input base and height
[Link]("Enter base of the triangle: ");
double base = [Link]([Link]());
[Link]("Enter height of the triangle: "); double
height = [Link]([Link]());

21
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

// Validate input
if (base <= 0 || height <= 0)
{
[Link]("Error: Base and height must be positive values.");
}
else
{
// Calculate and display area
double area = (base * height) / 2;
[Link]("Area of the triangle: %.2f%n", area);
}
}
catch (NumberFormatException e)
{
[Link]("Error: Please enter valid numeric values.");
}
// Ask to continue or exit
[Link]("Do you want to calculate another triangle? (yes/no): ");
String choice = [Link]().trim().toLowerCase();
if (![Link]("yes"))
{

[Link]("Exiting program. Goodbye!");


break;
}
}

[Link]();
}
}

22
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

23
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

10. Write a java program that accepts string from command line and display each character in capital at the delay of
one second.
Ans: public class
DisplayWithDelay
{
public static void main(String[] args)
{
if ([Link] == 0)
{
[Link]("Please provide a string as a command-line argument.");
return;
}
String input = args[0].toUpperCase();
for (char c : [Link]())
{
[Link](c);
Try
{
[Link](1000); // 1-second delay
}
catch (InterruptedException e)
{
[Link]("An error occurred: " + [Link]());
}
}
}
}

24
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

11. Create class EMPLOYEE in java with id, name and salary as data-members. Again create 5 different employee
objects by taking input from user. Display all the information of an employee which is having maximum salary. Ans:

import [Link];
class Employee
{
int id;
String name;
double salary;
public Employee(int id, String name, double salary)
{
[Link] = id;
[Link] = name;
[Link] = salary;
}
}
public class MaxSalaryEmployee
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
Employee[] employees = new Employee[5];

// Taking input for 5 employees


for (int i = 0; i < 5; i++)
{

25
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

[Link]("Enter details for Employee " + (i + 1));


[Link]("ID: ");
int id = [Link]();
[Link](); // Consume the newline
[Link]("Name: ");
String name = [Link]();
[Link]("Salary: "); double
salary = [Link]();
employees[i] = new Employee(id, name, salary);
}

// Finding the employee with the maximum salary


Employee maxSalaryEmployee = employees[0]; for
(Employee emp : employees)
{
if ([Link] > [Link])
{

maxSalaryEmployee = emp;
}
}

// Displaying the employee with the maximum salary


[Link]("\nEmployee with the highest salary:");
[Link]("ID: " + [Link]);
[Link]("Name: " + [Link]);
[Link]("Salary: " + [Link]); [Link]();
}
}

26
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

12. Write a Java code that handles the custom exception like when a user gives input as Floating point number then
it raises exception with appropriate message.
Ans:
import [Link];
class FloatingPointInputException extends Exception
{
public FloatingPointInputException(String message)
{
super(message);
}
}
public class CustomExceptionExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
try {
27
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

[Link]("Enter an integer: ");


String input = [Link]();
if ([Link]("."))
{
throw new FloatingPointInputException("Error: Floating-point numbers are not allowed!");
}
int number = [Link](input);
[Link]("You entered the integer: " + number);
}
catch (FloatingPointInputException e){
[Link]([Link]());
}
catch (NumberFormatException e) {
[Link]("Error: Invalid input. Please enter a valid integer.");
}
finally{
[Link]();
}
}
}
}

13. Write a Java program to display string with capital letters which are inputted through command line.
Display those string(s) which starts with "B".
Ans: public class
DisplayStringsWithB
{
public static void main(String[] args)
{
if ([Link] == 0)
{
[Link]("Please provide strings as command-line arguments.");
return;
}

28
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

[Link]("Strings starting with 'B':");


for (String str : args)
{
if ([Link]().startsWith("B"))
{
[Link]([Link]());
}
}
}
}

14. Write an application that creates and start three threads, each thread is instantiated from the same class. It
executes a loop with 5 iterations. First thread display "BEST", second thread display "OF" and last thread display
"LUCK". All threads sleep for 1000 ms. The application waits for all threads to complete and display a message. Ans:-
class MyThread extends Thread
{
private final String message;
public MyThread(String message)
{
[Link] = message;
}
@Override public void run()

29
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

{
try {
for (int i = 0; i < 5; i++)
{
[Link](message);
[Link](1000); // Sleep for 1000 ms
}
}
catch (InterruptedException e)
{
[Link]("Thread interrupted: " + [Link]());
}
}
}

public class MultiThreadExample


{
public static void main(String[] args)
{
// Creating threads
MyThread thread1 = new MyThread("BEST");
MyThread thread2 = new MyThread("OF");
MyThread thread3 = new MyThread("LUCK");
// Starting threads
[Link](); [Link]();
[Link]();
try
{
// Waiting for all threads to complete
[Link](); [Link]();
[Link]();
}
catch (InterruptedException e)
{
[Link]("Main thread interrupted: " + [Link]());
}

// Final message after all threads complete


[Link]("All threads completed. GOOD LUCK!");
}
}

30
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

15. WAJP to create a Player [Link] the classes Cricket_Player,Football_Player and Hockey_ Player from Player
class.
Ans:
class Player
{
String name;
int age;
public Player(String name, int age)
{
[Link] = name;
[Link] = age;
}
public void display()
31
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

{
[Link]("Name: " + name + ", Age: " + age);
}
}

class Cricket_Player extends Player


{
public Cricket_Player(String name, int age)
{
super(name, age);
}
public void play()
{
[Link](name + " is a Cricket Player.");
}
}

class Football_Player extends Player


{
public Football_Player(String name, int age)
{
super(name, age);
}
public void play()
{
[Link](name + " is a Football Player.");
}
}

class Hockey_Player extends Player


{
public Hockey_Player(String name, int age)
{
super(name, age);
}
public void play()
{
[Link](name + " is a Hockey Player.");
}
}
public class Main
{
32
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

public static void main(String[] args)


{
Cricket_Player cricketPlayer = new Cricket_Player("Virat", 34);
Football_Player footballPlayer = new Football_Player("Messi", 36);
Hockey_Player hockeyPlayer = new Hockey_Player("Dhyan", 29);
[Link](); [Link]();

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

16. Define a class called Student. Store rollno &name of the student. Define member functions to assign & display
value of roll no. & name.
Ans:
class Student
{
private int rollNo;
private String name;

// Method to assign values

33
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

public void assignValues(int rollNo, String name)


{
[Link] = rollNo;
[Link] = name;
}
// Method to display values
public void displayValues()
{
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
}
public static void main(String[] args)
{
Student student = new Student();
[Link](101, "John Doe");
[Link]();
}
}

34
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

17. Create a method area(),overload it to calculate area of circle ,rectangle and square. Ans:
class Shape
{
// Calculate area of a circle
public double area(double radius)
{
return [Link] * radius * radius;
}
// Calculate area of a rectangle
public double area(double length, double breadth)
{
return length * breadth;
}
// Calculate area of a square
public double area(int side)
{
return side * side;
}
public static void main(String[] args)
{
Shape shape = new Shape();
// Examples
[Link]("Area of Circle: %.2f%n", [Link](7.0)); // Circle with radius 7.0
[Link]("Area of Rectangle: " + [Link](5.0, 10.0)); // Rectangle 5x10
[Link]("Area of Square: " + [Link](4)); // Square with side 4
}
}

35
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

18. WAJP to create an interface area. Create three classes called rectangle,triangle,and square calculate areas
respectively.
Ans:
interface Area
{
void calculateArea(); // Method to calculate area
}
class Rectangle implements Area
{
private double length, breadth;
public Rectangle(double length, double breadth)
{
[Link] = length;
[Link] = breadth;
}
public void calculateArea()
{
[Link]("Area of Rectangle: " + (length * breadth));
}
}
class Triangle implements Area
{
private double base, height;
public Triangle(double base, double height)
{
[Link] = base;
[Link] = height;
}
public void calculateArea()
{
[Link]("Area of Triangle: " + (0.5 * base * height));
}
}
class Square implements Area
{
private double side;
public Square(double side)
{
[Link] = side;
}
public void calculateArea()
{
36
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

[Link]("Area of Square: " + (side * side));


}
}
public class AreaCalculator
{
public static void main(String[] args)
{
Area rectangle = new Rectangle(5, 10);
Area triangle = new Triangle(6, 8);
Area square = new Square(4);
[Link]();
[Link]();
[Link]();
}
}

37
JAVA JOURNAL SYBCA
Name: RUDRA GADHAVI

ROLL NO: 631

19. You are given a stingstr=”SDJInternationalCollege”.Perform the following operation on it. Find the length of string
Replace the character‘e’by‘E’ Convert all character in uppercase Ans:
public class StringOperations
{
public static void main(String[] args)
{
String str = "SDJInternationalCollege";

// Find the length of the string


int length = [Link]();
[Link]("Length of the string: " + length);

// Replace the character 'e' by 'E'


String replacedString = [Link]('e', 'E');
[Link]("String after replacing 'e' with 'E': " + replacedString);
// Convert all characters to uppercase
String upperCaseString = [Link]();
[Link]("String in uppercase: " + upperCaseString);
}
}

38
JAVA JOURNAL SYBCA

Common questions

Powered by AI

A custom exception for handling floating-point input in Java can be implemented by defining a new exception class, such as FloatingPointInputException, that extends the Exception class. In the main program, when reading a user input expected to be an integer, the program checks if the input contains a floating-point representation (like a decimal). If it does, an instance of the custom exception is thrown with an appropriate message. This exception is caught in a catch block, and the message is displayed to the user, preventing floating-point inputs when integers are required .

An interface in Java for calculating areas, such as Area, defines a contract with a method signature for calculating the area but without implementation. Classes like Rectangle, Triangle, and Square implement this interface to provide specific logic for area calculation based on their dimensions. Each class defines its implementation of the calculateArea() method as per the shape's formula. By adhering to the interface, any implementing class guarantees the presence of the calculateArea() method, allowing for polymorphic use where different shape objects can be treated uniformly when calculating areas .

The Java program handles incorrect numeric input by using a try-catch block. It prompts the user to input values for the base and height of a triangle and attempts to parse these inputs into numeric values. If an invalid input is detected, such as a nonnumeric value or a negative number for base or height, the program throws a NumberFormatException or checks conditions, handles the error by displaying an appropriate message, and provides the user with the option to either input another set of values or exit the program .

In Java, user input for creating Employee objects is read using a Scanner object. The program creates an Employee object for each set of input details (name, age, salary) and stores these objects in an array. To sort the objects by salary, the Arrays.sort() method is used with a custom comparator comparing the salary fields of the Employee objects. This sorts the Employee objects in ascending order of salary before displaying them .

To modify a Java program to sort an array of strings provided via command-line input, you can utilize the Arrays.sort() method. This method sorts the array of strings in ascending order. Check if command-line arguments are provided and use Arrays.sort(args) to sort them. Finally, iterate through the array and print each string to display the sorted order .

In Java, synchronized execution of multiple threads can be ensured by using the join() method. After creating and starting threads, the main program calls the join() method on each thread object. This method blocks the calling thread (usually the main thread) until the thread whose join is called is complete. By using join(), the program waits for all threads to finish before continuing with the remaining tasks, ensuring synchronized execution. Additionally, each thread can include sleep() calls to regulate execution timing, but synchronization of thread completion relies on join().

A Java program can format and display data of a 'Student' class by defining member functions for assigning and displaying values. The Student class includes private fields for the student's roll number and name. The program provides a method like assignValues() to initialize these fields and a displayValues() method to print them in a formatted way. By calling these methods, the program effectively stores and retrieves student data, encapsulating the functionality within the Student class .

To merge two strings alternately in Java, initialize a StringBuilder to construct the resulting string. Iterate through both strings using a loop up to the length of the longer string. In each iteration, append characters alternately from each string if the index is within the bounds of the respective string. This involves checking the length condition before attempting to append a character from each string. Once the loop completes, the StringBuilder contains the merged result, which is then converted to a string for display .

The toggleCase method in a Java program works by iterating through each character of the string, checking the case of each character, and converting it to the opposite case. Specifically, if a character is uppercase, it is converted to lowercase and vice versa. Characters that are neither uppercase nor lowercase remain unchanged. The method builds a new string with these toggled characters and returns it .

Inheritance in a Java program using player classes can be demonstrated by creating a base class, such as Player, which contains common attributes (e.g., name, age) and methods. Specialized classes (e.g., Cricket_Player, Football_Player, Hockey_Player) extend the Player class to inherit its properties and methods. These subclasses may also implement specific methods to display unique behaviors or attributes related to each sport. By invoking methods from the base class and the subclasses, the program exhibits inheritance where each sports player class shares common characteristics from the Player class while also having sport-specific behaviors .

You might also like