Java Practical
Java Practical
Roll No : 2363
1.Write a Java program to print the sum (addition), multiply, subtract, divide
and remainder of two numbers arithmetic
Ans:-
import java.util.Scanner;
class ArithmeticOperation{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter First Number: ");
double num1=sc.nextDouble();
System.out.println("Enter Second Number: ");
double num2=sc.nextDouble();
double sum=num1+num2;
double diffrence=num1-num2;
double product=num1*num2;
double quotient=num1/num2;
double reminder=num1%num2;
System.out.println("Sum: "+sum);
System.out.println("Diffrence: "+diffrence);
System.out.println("Product: "+product);
if(num2 !=0){
System.out.println("Quotient: "+quotient);
System.out.println("Reminder: "+reminder);
}else{
Output:-
Output:-
3. Write a program which design Bank Account class as Saving and Current
Account and manage information accordingly.
Ans:-
abstract class BankAccount {
String accountNumber;
String accountHolderName;
double balance;
public BankAccount(String accountNumber, String accountHolderName, double balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}
public String getAccountNumber() {
return accountNumber;
}
public String getAccountHolderName() {
return accountHolderName;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
public abstract void withdraw(double amount);
savingAccount.withdraw(200.0);
System.out.println();
currentAccount.displayAccountInfo();
currentAccount.deposit(1000.0);
currentAccount.withdraw(800.0);
}
Output:-
4. Write a program that accepts two numbers from command line and add two
numbers if the arguments are numbers else display total number of vowels of
two strings.
Ans:-
class CommandLineArguments {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Please provide exactly two arguments.");
return;
}
try {
double num1 = Double.parseDouble(args[0]);
double num2 = Double.parseDouble(args[1]);
double sum = num1 + num2;
System.out.println("The sum of the two numbers is: " + sum);
} catch (NumberFormatException e) {
int vowelCount = countVowels(args[0]) + countVowels(args[1]);
System.out.println("The total number of vowels in the two strings is: " + vowelCount);
}
}
public static int countVowels(String str) {
int count = 0;
char ch = str.charAt(i);
Output:-
System.out.println(employees[i]);
Thread.sleep(1000);
}
}
}
Output :-
6. Write a program to accept 5 command line argument and then raise the custom
exception if any argument is not from the list
(“BCA”,”MCA”,”BBA”,”MBA”,”OTHER”).
Ans:-
class InvalidArgumentException extends Exception {
public InvalidArgumentException(String message) {
super(message);
}
}
public class CommandLineArguments {
public static void main(String[] args) {
if (args.length != 5) {
System.out.println("Please provide exactly 5 arguments.");
return;
}
String[] validArguments = {"BCA", "MCA", "BBA", "MBA", "OTHER"};
}
public static boolean isValidArgument(String arg, String[] validArguments) {
for (String valid : validArguments) {
if (valid.equals(arg)) {
return true;
}
}
return false;
}
}
Output:-
7. Write a java code which accepts name of 10 students. Sort the names of
students in ascending order. Display the names of students using thread class at
interval of one second.
Ans:-
import java.util.Arrays;
import java.util.Scanner;
class StudentThread extends Thread {
String[] studentNames;
public StudentThread(String[] studentNames) {
this.studentNames = studentNames;
}
public void run() {
for (String studentName : studentNames) {
System.out.println(studentName);
try {
Thread.sleep(1000); // sleep for 1 second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class StudentNameSorter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the names of 10 students:");
Output:-
8.Write java application which accept a string and display the string in reverse
order by interchanging its odd positioned characters with even positioned
characters.
Ans:-
import java.util.Scanner;
public class ReverseAndSwapCharacters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
char[] charArray = input.toCharArray();
for (int i = 0; i < charArray.length - 1; i += 2) {
char temp = charArray[i];
charArray[i] = charArray[i + 1];
charArray[i + 1] = temp;
}
String reversedString = new StringBuilder(new String(charArray)).reverse().toString();
System.out.println("The string after interchanging odd and even positions and reversing: ");
System.out.println(reversedString);
scanner.close();
}
}
Output:-
9. Write an application that executes three threads from one thread class. One
thread displays “JAVA” every 1 second. another display “PAPER” every 2 seconds
and last one display “COLLEGE” every 3 seconds. Create the thread by using
Runnable Interface.
Ans:-
class JavaRunnable implements Runnable {
public void run() {
try {
while (true) {
System.out.println("JAVA");
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
class PaperRunnable implements Runnable {
public void run() {
try {
while (true) {
System.out.println("PAPER");
Thread.sleep(2000); // Sleep for 2 seconds
}
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
class CollegeRunnable implements Runnable {
public void run() {
try {
while (true) {
System.out.println("COLLEGE");
Thread.sleep(3000);
}
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
class ThreadExample {
public static void main(String[] args) {
Runnable javaRunnable = new JavaRunnable();
Runnable paperRunnable = new PaperRunnable();
Runnable collegeRunnable = new CollegeRunnable();
javaThread.start();
paperThread.start();
collegeThread.start();
}
}
Output:-
10. Write a program to input two strings search similar characters from both
string and replace it with ‘*’.
Ans:-
import java.util.Scanner;
class SimReplace{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter second string: ");
String str2 = scanner.nextLine();
System.out.println("Original strings:");
System.out.println("String 1: " + str1);
System.out.println("String 2: " + str2);
modifiedStr.setCharAt(i, '*');
}
}
return modifiedStr.toString();
}
}
Output:-
11. Write a java program that accepts string data. Extract either all vowels or all
Non-vowels from given data according to option selection.
Ans:-
import java.util.Scanner;
public class ExtractVowelsNonVowels {
public static String extractVowels(String input) {
StringBuilder vowels = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (isVowel(ch)) {
vowels.append(ch);
}
}
return vowels.toString();
}
public static String extractNonVowels(String input) {
StringBuilder nonVowels = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (!isVowel(ch)) {
nonVowels.append(ch);
}
}
return nonVowels.toString();
}
result = extractNonVowels(input);
System.out.println("Non-Vowels in the string: " + result);
} else {
System.out.println("Invalid choice!");
}
scanner.close();
}
Output:-
12. Write a java program that accepts string data from user and then provide
options for changing case into any of the following: (UPPERCASE, lowercase, and
Sentence case)
Ans:-
import java.util.Scanner;
class CaseChanger {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.println("Select an option:");
System.out.println("1. Convert to UPPERCASE");
System.out.println("2. Convert to lowercase");
System.out.println("3. Convert to Sentence case");
int option = scanner.nextInt();
scanner.close();
switch (option) {
case 1:
System.out.println("Converted string: " + inputString.toUpperCase());
break;
case 2:
System.out.println("Converted string: " + inputString.toLowerCase());
break;
case 3:
System.out.println("Converted string: " + toSentenceCase(inputString));
break;
default:
System.out.println("Invalid option");
}
}
public static String toSentenceCase(String inputString) {
String[] words = inputString.split("\\s+");
StringBuilder sentenceCase = new StringBuilder();
for (String word : words) {
sentenceCase.append(Character.toUpperCase(word.charAt(0)));
sentenceCase.append(word.substring(1).toLowerCase());
sentenceCase.append(" ");
}
return sentenceCase.toString().trim();
}
}
Output:-
13. Write a program to create singly Link List and perform following operations:
1. Insert a node at desired Location.
2. Delete a node from given Location.
3. Update desired Location.
4. Search
5. Display
Ans:-
import java.util.Scanner;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
public void insertAtDesiredLocation(int data, int location) {
Node newNode = new Node(data);
if (location == 0) {
insertAtBeginning(data);
} else {
Node temp = head;
for (int i = 0; i < location - 1; i++) {
if (temp.next == null) {
System.out.println("Location out of bounds");
return;
}
temp = temp.next;
}
newNode.next = temp.next;
temp.next = newNode;
}
}
public void deleteAtDesiredLocation(int location) {
if (location == 0) {
head = head.next;
} else {
Node temp = head;
for (int i = 0; i < location - 1; i++) {
if (temp.next == null) {
data = scanner.nextInt();
System.out.print("Enter location to update: ");
location = scanner.nextInt();
list.updateAtDesiredLocation(data, location);
break;
case 5:
System.out.print("Enter data to search: ");
data = scanner.nextInt();
if (list.search(data)) {
System.out.println("Data found");
} else {
System.out.println("Data not found");
}
break;
case 6:
System.out.println("Linked list:");
list.display();
break;
case 7:
System.exit(0);
break;
default:
System.out.println("Invalid choice");
}
}
}
Output:-
14. Write a program to create singly circular Link List and perform following
operations:
1. Insert a node at beginning.
2. Insert a node at End.
3. Delete First node.
4. Delete Last node.
5. Display.
Ans:-
import java.util.Scanner;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class CircularLinkedList {
Node head;
Node tail;
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
newNode.next = head;
} else {
newNode.next = head;
head = newNode;
tail.next = head;
}
}
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
newNode.next = head;
} else {
tail.next = newNode;
tail = newNode;
tail.next = head;
}
}
public void deleteFirstNode() {
if (head == null) {
System.out.println("List is empty");
} else if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
tail.next = head;
}
}
public void deleteLastNode() {
if (head == null) {
System.out.println("List is empty");
} else if (head == tail) {
head = null;
tail = null;
} else {
Node temp = head;
while (temp.next != tail) {
temp = temp.next;
}
temp.next = head;
tail = temp;
}
}
public void display() {
if (head == null) {
System.out.println("List is empty");
} else {
Node temp = head;
do {
System.out.print(temp.data + " ");
temp = temp.next;
} while (temp != head);
System.out.println();
}
}
}
class CircleQueue {
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1. Insert at beginning");
System.out.println("2. Insert at end");
System.out.println("3. Delete first node");
System.out.println("4. Delete last node");
System.out.println("5. Display");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter data to insert: ");
int data = scanner.nextInt();
list.insertAtBeginning(data);
break;
case 2:
Output:-