0% found this document useful (0 votes)
17 views

Java Assignment Final

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java Assignment Final

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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 java.util.Scanner;
class DisplayStringsWithB {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No strings provided.");
return;
}
for (String str : args) {
String upperCaseStr = str.toUpperCase();
if (upperCaseStr.startsWith("B")) {
System.out.println(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) {
this.message = message;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new DisplayMessages("BEST");
Thread thread2 = new DisplayMessages("OF");
Thread thread3 = new DisplayMessages("LUCK");

thread1.start();
thread2.start();
thread3.start();

107-YOGIRAJ KACHHAD 1
Java Programming language

thread1.join();
thread2.join();
thread3.join();
System.out.println("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 java.util.Scanner;
class FloatingPointException extends Exception {
public FloatingPointException(String message) {
super(message);
}
}
class CustomExceptionExample {
public static void checkForFloatingPoint(String input) throws FloatingPointException {
try {
Double.parseDouble(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(System.in);
System.out.print("Please enter a number: ");
String userInput = scanner.nextLine();
try {
checkForFloatingPoint(userInput);
System.out.println("You entered a valid number: " + userInput);
} catch (FloatingPointException e) {
System.out.println(e.getMessage());
}
}
}

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 java.util.Scanner;
class Employee {
int id;

107-YOGIRAJ KACHHAD 2
Java Programming language

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

System.out.print("Enter ID: ");


int id = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Salary: ");
double salary = scanner.nextDouble();
scanner.nextLine();
employees[i] = new Employee(id, name, salary);
}
Employee maxSalaryEmployee = employees[0];
for (int i = 1; i < employees.length; i++) {
if (employees[i].salary > maxSalaryEmployee.salary) {
maxSalaryEmployee = employees[i];
}
}
System.out.println("\nEmployee with the maximum salary:");
maxSalaryEmployee.displayInfo();
}
}

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 (args.length == 0) {
System.out.println("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 < inputString.length(); i++) {


char currentChar = Character.toUpperCase(inputString.charAt(i));
System.out.print(currentChar);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("Thread was interrupted");
}
}

System.out.println();
}
}

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 java.util.Scanner;

class TriangleAreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter the base of the triangle: ");
double base = Double.parseDouble(scanner.nextLine());

if (base <= 0) {
System.out.println("Base must be a positive number. Please try again.");
continue;
}

System.out.print("Enter the height of the triangle: ");


double height = Double.parseDouble(scanner.nextLine());

if (height <= 0) {
System.out.println("Height must be a positive number. Please try again.");
continue;
}

double area = (base * height) / 2;

107-YOGIRAJ KACHHAD 4
Java Programming language

System.out.println("The area of the triangle is: " + area);

} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter numeric values for base and height.");
}

System.out.print("Do you want to enter another set of values? (yes/no): ");


String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("no")) {
break;
}
}
scanner.close();
}
}

7. Write a java program that creates Singly Link List to perform create, insert, delete and display
node using menu driven program.
Ans:-

import java.util.Scanner;

class SinglyLinkedList {
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}

Node head = null;

public void create(int data) {


Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = 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 (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}

public void delete(int data) {


if (head == null) {
System.out.println("List is empty.");
return;
}
if (head.data == data) {
head = head.next;
return;
}
Node temp = head;
while (temp.next != null && temp.next.data != data) {
temp = temp.next;
}
if (temp.next == null) {
System.out.println("Node with value " + data + " not found.");
} else {
temp.next = temp.next.next;
}
}

public void display() {


if (head == null) {
System.out.println("List is empty.");
return;
}
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}

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

107-YOGIRAJ KACHHAD 6
Java Programming language

System.out.println("2. Insert");
System.out.println("3. Delete");
System.out.println("4. Display");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter data to create a node: ");
int createData = scanner.nextInt();
list.create(createData);
break;
case 2:
System.out.print("Enter data to insert a node: ");
int insertData = scanner.nextInt();
list.insert(insertData);
break;
case 3:
System.out.print("Enter data to delete a node: ");
int deleteData = scanner.nextInt();
list.delete(deleteData);
break;
case 4:
list.display();
break;
case 5:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("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 java.util.Scanner;

class MergeStrings {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first string: ");

107-YOGIRAJ KACHHAD 7
Java Programming language

String str1 = scanner.nextLine();


System.out.print("Enter second string: ");
String str2 = scanner.nextLine();

StringBuilder result = new StringBuilder();


int length = Math.max(str1.length(), str2.length());

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


if (i < str1.length()) {
result.append(str1.charAt(i));
}
if (i < str2.length()) {
result.append(str2.charAt(i));
}
}

System.out.println("Merged string: " + result.toString());


}
}

9.Write 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 java.util.Scanner;

class FloatingPointException extends Exception {


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

class CustomExceptionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scanner.nextLine();

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

107-YOGIRAJ KACHHAD 8
Java Programming language

10.Create 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 java.util.Scanner;

class STUDENT {
int roll;
String name;

STUDENT(int roll, String name) {


this.roll = roll;
this.name = name;
}
}

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

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


System.out.print("Enter roll number for student " + (i + 1) + ": ");
int roll = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter name for student " + (i + 1) + ": ");
String name = scanner.nextLine();
students[i] = new STUDENT(roll, name);
}

for (int i = 0; i < students.length - 1; i++) {


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

for (STUDENT student : students) {


System.out.println("Roll: " + student.roll + ", Name: " + student.name);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}

107-YOGIRAJ KACHHAD 9
Java Programming language

}
}
}

11.Write 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 java.util.Scanner;

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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.println("Choose an option:");
System.out.println("1. Extract Vowels");
System.out.println("2. Extract Non-Vowels");
int choice = scanner.nextInt();
scanner.nextLine(); // consume newline

System.out.println("Choose case:");
System.out.println("1. Uppercase");
System.out.println("2. Lowercase");
int caseChoice = scanner.nextInt();

StringBuilder result = new StringBuilder();


for (char c : input.toCharArray()) {
if (choice == 1 && isVowel(c)) {
result.append(c);
} else if (choice == 2 && !isVowel(c) && Character.isLetter(c)) {
result.append(c);
}
}

if (caseChoice == 1) {
System.out.println(result.toString().toUpperCase());
} else {
System.out.println(result.toString().toLowerCase());
}
}

public static boolean isVowel(char c) {


c = Character.toLowerCase(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}

107-YOGIRAJ KACHHAD 10
Java Programming language

12.Write 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 java.util.Scanner;
class ChangeCase {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.println("Choose an option:");
System.out.println("1. UPPERCASE");
System.out.println("2. lowercase");
System.out.println("3. Sentence case");
System.out.println("4. TOGGLE CASE");
int choice = scanner.nextInt();

String result = "";

switch (choice) {
case 1:
result = input.toUpperCase();
break;
case 2:
result = input.toLowerCase();
break;
case 3:
result = input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
break;
case 4:
StringBuilder toggleCase = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isUpperCase(c)) {
toggleCase.append(Character.toLowerCase(c));
} else {
toggleCase.append(Character.toUpperCase(c));
}
}
result = toggleCase.toString();
break;
default:
System.out.println("Invalid choice");
return;
}

System.out.println("Result: " + result);

107-YOGIRAJ KACHHAD 11
Java Programming language

}
}

13.Write 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 java.util.*;

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

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


this.title = title;
this.author = author;
this.publication = publication;
this.price = price;
}
}

class BookInfo {
public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of books: ");
int n = scanner.nextInt();
scanner.nextLine();

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

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


System.out.print("Enter title of book " + (i + 1) + ": ");
String title = scanner.nextLine();
System.out.print("Enter author of book " + (i + 1) + ": ");
String author = scanner.nextLine();
System.out.print("Enter publication of book " + (i + 1) + ": ");
String publication = scanner.nextLine();
System.out.print("Enter price of book " + (i + 1) + ": ");
double price = scanner.nextDouble();
scanner.nextLine();
books.add(new Book(title, author, publication, price));
}

for (int i = 0; i < books.size() - 1; i++) {


for (int j = i + 1; j < books.size(); j++) {
if (books.get(i).price < books.get(j).price) {

107-YOGIRAJ KACHHAD 12
Java Programming language

Book temp = books.get(i);


books.set(i, books.get(j));
books.set(j, temp);
}
}
}

for (Book book : books) {


System.out.println("Title: " + book.title);
System.out.println("Author: " + book.author);
System.out.println("Publication: " + book.publication);
System.out.println("Price: " + book.price);
Thread.sleep(1000);
}
}
}

14.Write 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 java.util.*;

class Student {
String name;
int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}
}

class DisplayStudentThread extends Thread {


private String name;

public DisplayStudentThread(String name) {


this.name = name;
}

@Override
public void run() {
try {
System.out.println(name);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

107-YOGIRAJ KACHHAD 13
Java Programming language

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

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


System.out.print("Enter name of student " + (i + 1) + ": ");
String name = scanner.nextLine();
System.out.print("Enter age of student " + (i + 1) + ": ");
int age = scanner.nextInt();
scanner.nextLine();
students.add(new Student(name, age));
}

for (int i = 0; i < students.size() - 1; i++) {


for (int j = i + 1; j < students.size(); j++) {
if (students.get(i).age < students.get(j).age) {
Student temp = students.get(i);
students.set(i, students.get(j));
students.set(j, temp);
}
}
}

for (Student student : students) {


new DisplayStudentThread(student.name).start();
}
}
}

15.Design Item class having Item_Code, Name, Price, and Stock in hand as data member.Add
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 java.util.*;

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

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


this.itemCode = itemCode;
this.name = name;
this.price = price;
this.stock = stock;
}

107-YOGIRAJ KACHHAD 14
Java Programming language

public void display() {


System.out.println("Item Code: " + itemCode);
System.out.println("Name: " + name);
System.out.println("Price: " + price);
System.out.println("Stock: " + stock);
}
}

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

System.out.print("Enter the number of items: ");


int n = scanner.nextInt();
scanner.nextLine();

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

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


System.out.print("Enter Item Code for item " + (i + 1) + ": ");
String itemCode = scanner.nextLine();
System.out.print("Enter Name for item " + (i + 1) + ": ");
String name = scanner.nextLine();
System.out.print("Enter Price for item " + (i + 1) + ": ");
double price = scanner.nextDouble();
System.out.print("Enter Stock for item " + (i + 1) + ": ");
int stock = scanner.nextInt();
scanner.nextLine();

items.add(new Item(itemCode, name, price, stock));


}

items.sort(Comparator.comparingInt(item -> item.stock));

System.out.println("\nItems sorted by stock in ascending order:");


for (Item item : items) {
item.display();
System.out.println();
}
}
}

107-YOGIRAJ KACHHAD 15

You might also like