[Go to site: main page, start]

0% found this document useful (0 votes)
27 views15 pages

Java Programming Assignments Guide

The document contains various Java programming exercises that cover topics such as string manipulation, multithreading, exception handling, and data structures. Each exercise includes a problem statement followed by a complete Java code solution. The exercises range from displaying strings based on conditions to creating custom exceptions and managing linked lists.
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)
27 views15 pages

Java Programming Assignments Guide

The document contains various Java programming exercises that cover topics such as string manipulation, multithreading, exception handling, and data structures. Each exercise includes a problem statement followed by a complete Java code solution. The exercises range from displaying strings based on conditions to creating custom exceptions and managing linked lists.
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

Java Programming language

1. Write a Java Program to Display string with capital letter which are inputted through command
lin. Display those string(s) which starts with �B�
Ans:-

import [Link];
class DisplayStringsWithB {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("No strings provided.");
return;
}
for (String str : args) {
String upperCaseStr = [Link]();
if ([Link]("B")) {
[Link](upperCaseStr);
}
}
}
}

2. 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 DisplayMessages extends Thread {


private String message;
public DisplayMessages(String message) {
[Link] = message;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link](message);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new DisplayMessages("BEST");
Thread thread2 = new DisplayMessages("OF");
Thread thread3 = new DisplayMessages("LUCK");

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

107-YOGIRAJ KACHHAD 1
Java Programming language

[Link]();
[Link]();
[Link]();
[Link]("All threads have completed execution.");
}
}

3. 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 FloatingPointException extends Exception {
public FloatingPointException(String message) {
super(message);
}
}
class CustomExceptionExample {
public static void checkForFloatingPoint(String input) throws FloatingPointException {
try {
[Link](input);
throw new FloatingPointException("Error: Floating point number detected. Please enter a
whole number.");
} catch (NumberFormatException e) {

}
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Please enter a number: ");
String userInput = [Link]();
try {
checkForFloatingPoint(userInput);
[Link]("You entered a valid number: " + userInput);
} catch (FloatingPointException e) {
[Link]([Link]());
}
}
}

4. Create class EMPLLOYEE in java with id, name and salary as data members. 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;

107-YOGIRAJ KACHHAD 2
Java Programming language

String name;
double salary;
public Employee(int id, String name, double salary) {
[Link] = id;
[Link] = name;
[Link] = salary;
}
public void displayInfo() {
[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
}
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Employee[] employees = new Employee[5];
for (int i = 0; i < 5; i++) {
[Link]("Enter details for Employee " + (i + 1));

[Link]("Enter ID: ");


int id = [Link]();
[Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Salary: ");
double salary = [Link]();
[Link]();
employees[i] = new Employee(id, name, salary);
}
Employee maxSalaryEmployee = employees[0];
for (int i = 1; i < [Link]; i++) {
if (employees[i].salary > [Link]) {
maxSalaryEmployee = employees[i];
}
}
[Link]("\nEmployee with the maximum salary:");
[Link]();
}
}

5. Write a java program that accept string from command line and display each character in
Capital at delay of one second.
Ans:-

class DisplayCharactersWithDelay {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide a string as a command line argument.");
return;

107-YOGIRAJ KACHHAD 3
Java Programming language

String inputString = args[0];

for (int i = 0; i < [Link](); i++) {


char currentChar = [Link]([Link](i));
[Link](currentChar);

try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("Thread was interrupted");
}
}

[Link]();
}
}

6. 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 non-numeric 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];

class TriangleAreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
while (true) {
try {
[Link]("Enter the base of the triangle: ");
double base = [Link]([Link]());

if (base <= 0) {
[Link]("Base must be a positive number. Please try again.");
continue;
}

[Link]("Enter the height of the triangle: ");


double height = [Link]([Link]());

if (height <= 0) {
[Link]("Height must be a positive number. Please try again.");
continue;
}

double area = (base * height) / 2;

107-YOGIRAJ KACHHAD 4
Java Programming language

[Link]("The area of the triangle is: " + area);

} catch (NumberFormatException e) {
[Link]("Invalid input. Please enter numeric values for base and height.");
}

[Link]("Do you want to enter another set of values? (yes/no): ");


String choice = [Link]();
if ([Link]("no")) {
break;
}
}
[Link]();
}
}

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 SinglyLinkedList {
class Node {
int data;
Node next;
Node(int data) {
[Link] = data;
[Link] = null;
}
}

Node head = null;

public void create(int data) {


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

public void insert(int data) {


Node newNode = new Node(data);
if (head == null) {

107-YOGIRAJ KACHHAD 5
Java Programming language

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

public void delete(int data) {


if (head == null) {
[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]("Node with value " + data + " not found.");
} else {
[Link] = [Link];
}
}

public void display() {


if (head == null) {
[Link]("List is empty.");
return;
}
Node temp = head;
while (temp != null) {
[Link]([Link] + " ");
temp = [Link];
}
[Link]();
}
}

class LinkedListMenuDriven {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
SinglyLinkedList list = new SinglyLinkedList();
while (true) {
[Link]("Menu:");
[Link]("1. Create");

107-YOGIRAJ KACHHAD 6
Java Programming language

[Link]("2. Insert");
[Link]("3. Delete");
[Link]("4. Display");
[Link]("5. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter data to create a node: ");
int createData = [Link]();
[Link](createData);
break;
case 2:
[Link]("Enter data to insert a node: ");
int insertData = [Link]();
[Link](insertData);
break;
case 3:
[Link]("Enter data to delete a node: ");
int deleteData = [Link]();
[Link](deleteData);
break;
case 4:
[Link]();
break;
case 5:
[Link]("Exiting...");
[Link]();
return;
default:
[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 Stringl is: "Very"", and
String2 is: "Good"
Then result should be: "VGeoroyd".
Ans:-

import [Link];

class MergeStrings {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter first string: ");

107-YOGIRAJ KACHHAD 7
Java Programming language

String str1 = [Link]();


[Link]("Enter second string: ");
String str2 = [Link]();

StringBuilder result = new StringBuilder();


int length = [Link]([Link](), [Link]());

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


if (i < [Link]()) {
[Link]([Link](i));
}
if (i < [Link]()) {
[Link]([Link](i));
}
}

[Link]("Merged string: " + [Link]());


}
}

[Link] a java code that handles the custom exception like when a user gives input as floating
//point number than it raise exception with appropriate message.
Ans:-

import [Link];

class FloatingPointException extends Exception {


public FloatingPointException(String message) {
super(message);
}
}

class CustomExceptionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
String input = [Link]();

try {
double number = [Link](input);
if (number % 1 != 0) {
throw new FloatingPointException("Error: Floating point number detected.");
}
[Link]("You entered a valid integer: " + (int) number);
} catch (FloatingPointException e) {
[Link]([Link]());
} catch (NumberFormatException e) {
[Link]("Error: Invalid input. Please enter a valid number.");
}
}

107-YOGIRAJ KACHHAD 8
Java Programming language

[Link] STUDENT class having data members roll and name. Create 5 objects of STUDENT class.
take input from the user and print all student's data in ascending order of name with interval of 10
ms.
Ans:-

import [Link];

class STUDENT {
int roll;
String name;

STUDENT(int roll, String name) {


[Link] = roll;
[Link] = name;
}
}

class StudentSort {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
STUDENT[] students = new STUDENT[5];

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


[Link]("Enter roll number for student " + (i + 1) + ": ");
int roll = [Link]();
[Link]();
[Link]("Enter name for student " + (i + 1) + ": ");
String name = [Link]();
students[i] = new STUDENT(roll, name);
}

for (int i = 0; i < [Link] - 1; i++) {


for (int j = i + 1; j < [Link]; j++) {
if (students[i].[Link](students[j].name) > 0) {
STUDENT temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}

for (STUDENT student : students) {


[Link]("Roll: " + [Link] + ", Name: " + [Link]);
try {
[Link](10);
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}

107-YOGIRAJ KACHHAD 9
Java Programming language

}
}
}

[Link] a Java Program that accepts string data. Extract either All Vowels or All Non-Vowels from
given Data According to Options Selection. Also Provide an Option to Display Output in Uppercase
or Lowercase.
Ans:-

import [Link];

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

[Link]("Enter a string: ");


String input = [Link]();

[Link]("Choose an option:");
[Link]("1. Extract Vowels");
[Link]("2. Extract Non-Vowels");
int choice = [Link]();
[Link](); // consume newline

[Link]("Choose case:");
[Link]("1. Uppercase");
[Link]("2. Lowercase");
int caseChoice = [Link]();

StringBuilder result = new StringBuilder();


for (char c : [Link]()) {
if (choice == 1 && isVowel(c)) {
[Link](c);
} else if (choice == 2 && !isVowel(c) && [Link](c)) {
[Link](c);
}
}

if (caseChoice == 1) {
[Link]([Link]().toUpperCase());
} else {
[Link]([Link]().toLowerCase());
}
}

public static boolean isVowel(char c) {


c = [Link](c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}

107-YOGIRAJ KACHHAD 10
Java Programming language

[Link] a Java Program that Accepts String Data from User and then Provide options for Changing
case into Any of the Following. (UPPERCASE, lowercise, Sentence case, tOGGLE CASE).
Ans:-

import [Link];
class ChangeCase {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter a string: ");


String input = [Link]();

[Link]("Choose an option:");
[Link]("1. UPPERCASE");
[Link]("2. lowercase");
[Link]("3. Sentence case");
[Link]("4. TOGGLE CASE");
int choice = [Link]();

String result = "";

switch (choice) {
case 1:
result = [Link]();
break;
case 2:
result = [Link]();
break;
case 3:
result = [Link](0, 1).toUpperCase() + [Link](1).toLowerCase();
break;
case 4:
StringBuilder toggleCase = new StringBuilder();
for (int i = 0; i < [Link](); i++) {
char c = [Link](i);
if ([Link](c)) {
[Link]([Link](c));
} else {
[Link]([Link](c));
}
}
result = [Link]();
break;
default:
[Link]("Invalid choice");
return;
}

[Link]("Result: " + result);

107-YOGIRAJ KACHHAD 11
Java Programming language

}
}

[Link] a program that accept Book information like


Title, Author, Publication and Price for the N book from the user and display books in descending
order with interval of 1 second using thread.
Ans:-

import [Link].*;

class Book {
String title;
String author;
String publication;
double price;

public Book(String title, String author, String publication, double price) {


[Link] = title;
[Link] = author;
[Link] = publication;
[Link] = price;
}
}

class BookInfo {
public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of books: ");
int n = [Link]();
[Link]();

List<Book> books = new ArrayList<>();

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


[Link]("Enter title of book " + (i + 1) + ": ");
String title = [Link]();
[Link]("Enter author of book " + (i + 1) + ": ");
String author = [Link]();
[Link]("Enter publication of book " + (i + 1) + ": ");
String publication = [Link]();
[Link]("Enter price of book " + (i + 1) + ": ");
double price = [Link]();
[Link]();
[Link](new Book(title, author, publication, price));
}

for (int i = 0; i < [Link]() - 1; i++) {


for (int j = i + 1; j < [Link](); j++) {
if ([Link](i).price < [Link](j).price) {

107-YOGIRAJ KACHHAD 12
Java Programming language

Book temp = [Link](i);


[Link](i, [Link](j));
[Link](j, temp);
}
}
}

for (Book book : books) {


[Link]("Title: " + [Link]);
[Link]("Author: " + [Link]);
[Link]("Publication: " + [Link]);
[Link]("Price: " + [Link]);
[Link](1000);
}
}
}

[Link] a java application which accepts 10 names of student and their age. Sort names and age
in descending order. Display the names of students using thread class at interval of one second
Ans:-

import [Link].*;

class Student {
String name;
int age;

public Student(String name, int age) {


[Link] = name;
[Link] = age;
}
}

class DisplayStudentThread extends Thread {


private String name;

public DisplayStudentThread(String name) {


[Link] = name;
}

@Override
public void run() {
try {
[Link](name);
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}

107-YOGIRAJ KACHHAD 13
Java Programming language

class StudentInfo {
public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner([Link]);
List<Student> students = new ArrayList<>();

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


[Link]("Enter name of student " + (i + 1) + ": ");
String name = [Link]();
[Link]("Enter age of student " + (i + 1) + ": ");
int age = [Link]();
[Link]();
[Link](new Student(name, age));
}

for (int i = 0; i < [Link]() - 1; i++) {


for (int j = i + 1; j < [Link](); j++) {
if ([Link](i).age < [Link](j).age) {
Student temp = [Link](i);
[Link](i, [Link](j));
[Link](j, temp);
}
}
}

for (Student student : students) {


new DisplayStudentThread([Link]).start();
}
}
}

[Link] Item class having Item_Code, Name, Price, and Stock in hand as data [Link]
appropriate member functions. Write a Java program that accepts details of N Item and display
items details in ascending order of their stock.
Ans:-

import [Link].*;

class Item {
String itemCode;
String name;
double price;
int stock;

public Item(String itemCode, String name, double price, int stock) {


[Link] = itemCode;
[Link] = name;
[Link] = price;
[Link] = stock;
}

107-YOGIRAJ KACHHAD 14
Java Programming language

public void display() {


[Link]("Item Code: " + itemCode);
[Link]("Name: " + name);
[Link]("Price: " + price);
[Link]("Stock: " + stock);
}
}

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

[Link]("Enter the number of items: ");


int n = [Link]();
[Link]();

List<Item> items = new ArrayList<>();

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


[Link]("Enter Item Code for item " + (i + 1) + ": ");
String itemCode = [Link]();
[Link]("Enter Name for item " + (i + 1) + ": ");
String name = [Link]();
[Link]("Enter Price for item " + (i + 1) + ": ");
double price = [Link]();
[Link]("Enter Stock for item " + (i + 1) + ": ");
int stock = [Link]();
[Link]();

[Link](new Item(itemCode, name, price, stock));


}

[Link]([Link](item -> [Link]));

[Link]("\nItems sorted by stock in ascending order:");


for (Item item : items) {
[Link]();
[Link]();
}
}
}

107-YOGIRAJ KACHHAD 15

Common questions

Powered by AI

The application creates threads that override the 'run' method to implement specific logic. Each thread uses 'Thread.sleep(1000)' to introduce a one-second delay between output displays. This delay ensures outputs are printed at consistent intervals, even when threads run concurrently .

The java code defines a class 'FloatingPointException' extending 'Exception'. In the 'main' method, a try block attempts to parse the input string to a Double. If successful and the number has a fractional part, it throws 'FloatingPointException' with a detailed message, effectively intercepting floating-point inputs. This exception is caught, and an appropriate message is printed, ensuring only integer inputs are considered valid .

The application uses the 'join()' method on each thread ('thread1', 'thread2', and 'thread3') after starting them. The 'join()' method causes the main thread to wait until the respective thread completes execution, ensuring that all threads finish their tasks before displaying the final message 'All threads have completed execution' .

The program uses try-catch blocks to catch NumberFormatException when the user enters non-numeric values. It checks if the base or height values are less than or equal to zero and prompts the user to enter positive numbers. The user is given options to retry inputs or exit after each error message, ensuring valid numeric input before calculating the area .

The program sorts an array of STUDENT objects by comparing their names using the compareTo method. It uses a nested loop to perform a simple bubble sort. After sorting, it iterates through the sorted array and displays each student's information using Thread.sleep(10) to introduce a short delay between displays .

The application defines a custom exception class 'FloatingPointException' which is thrown when the input is a floating-point number. The 'checkForFloatingPoint' method tries to parse the input string as a Double. If parsing is successful, it throws the 'FloatingPointException' with a specific error message. The exception is caught in the main method, and the corresponding error message is displayed .

The program defines a loop that iterates through the length of the longer string. In each iteration, it appends the character from the first string if available, followed by the character from the second string if available, to a result 'StringBuilder'. This approach ensures that characters from both strings are alternately included in the merged output .

The program implements a singly linked list with methods 'create', 'insert', 'delete', and 'display'. 'Create' and 'insert' methods add new nodes to the end of the list. 'Delete' method searches for the node containing the specified data and removes it by adjusting the pointers. 'Display' method traverses the list, printing the data of each node in order .

The program uses a simple comparison-based sorting method, likely bubble sort or selection sort, involving nested loops. It iterates through the list of books and compares the price of each book, swapping them to ensure that books with higher prices appear before those with lower prices .

The program employs a class 'Employee' with attributes id, name, and salary. It creates an array of five 'Employee' objects from user input. It leverages encapsulation by defining attributes as private and providing a constructor for initialization. The program identifies the employee with the maximum salary using a simple iteration and comparison and displays that employee's information .

You might also like