0% found this document useful (0 votes)
8 views55 pages

java practical assignment(krishna)

The document contains a Java practical assignment for a Bachelor of Computer Application student, Shah Krishna Chiragbhai, detailing various programming tasks. It includes code examples for arithmetic operations, sorting arrays, managing bank accounts, processing command line arguments, displaying employee details, validating command line inputs, sorting student names, reversing strings, and executing multiple threads. Each task demonstrates fundamental Java programming concepts and object-oriented design.

Uploaded by

harshil4466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views55 pages

java practical assignment(krishna)

The document contains a Java practical assignment for a Bachelor of Computer Application student, Shah Krishna Chiragbhai, detailing various programming tasks. It includes code examples for arithmetic operations, sorting arrays, managing bank accounts, processing command line arguments, displaying employee details, validating command line inputs, sorting student names, reversing strings, and executing multiple threads. Each task demonstrates fundamental Java programming concepts and object-oriented design.

Uploaded by

harshil4466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Roll no :- 2231

BACHELOR OF COMPUTER APPLICATION

NAME :- SHAH KRISHNA CHIRAGBHAI

ROLL NO :- 2231

DIVISION :- C

CLASS :- S.Y.B.C.A

SUBJECT :- Java practical assignment

SASCMA BCA COLLAGE,SURAT


Page | 1
Roll no :- 2231

SASCMA BCA COLLAGE,SURAT


Page | 2
Roll no :- 2231

1. Write a Java program to print the sum (addition), multiply, subtract, divide
and remainder of two numbers arithmetic

import java.util.Scanner;

public class ArithmeticOperations

public static void main(String[]args)

Scanner scanner=new Scanner(System.in);

System.out.print("Enter the first number: "); double

num1=scanner.nextDouble();

System.out.print("Enter the second number:

"); double num2=scanner.nextDouble();

double sum=num1+num2;

double difference=num1-num2;

double product=num1*num2;

double quotient=num1/num2;

double remainder=num1%num2;

System.out.println("Sum: "+ sum);


System.out.println("Difference:" + difference);

SASCMA BCA COLLAGE,SURAT


Page | 3
Roll no :- 2231

System.out.println("Product:" + product );

System.out.println("Quotient: " + quotient );

System.out.println("Remainder: " + remainder);

scanner.close();

2. Write a Java program to sort array elements.

SASCMA BCA COLLAGE,SURAT


Page | 4
Roll no :- 2231

import java.util.Arrays;

public class SortArray

public static void main(String[] args)

int[] numbers={34,12,5,87,56,9};

System.out.println("Original array: " + Arrays.toString(numbers));

Arrays.sort(numbers);

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

SASCMA BCA COLLAGE,SURAT


Page | 5
Roll no :- 2231

3. Write a program which design Bank Account class as Saving and Current
Account and manage information accordingly.
SASCMA BCA COLLAGE,SURAT
Page | 6
Roll no :- 2231

// Base class for Bank Account

class BankAccount { protected

String accountHolder; protected

double balance;

// Constructor public BankAccount(String accountHolder,

double balance) { this.accountHolder = accountHolder;

this.balance = balance;

// Deposit method public void

deposit(double amount) { if

(amount > 0) { balance +=

amount;

System.out.println("Deposited: " + amount + ". Current balance: " + balance);

} else {

System.out.println("Deposit amount must be positive.");

// Withdraw method public void

withdraw(double amount) { if (amount

> 0 && amount <= balance) { balance

-= amount;

System.out.println("Withdrawn: " + amount

+ ". Current balance: " + balance);

SASCMA BCA COLLAGE,SURAT


Page | 7
Roll no :- 2231

} else {

System.out.println("Insufficient funds or invalid withdrawal amount.");

// Get balance method

public double getBalance()

{ return balance;

// Account information method

public void accountInfo() {

System.out.println("Account Holder: " + accountHolder + ", Balance: " + balance);

// Saving Account class class

SavingAccount extends BankAccount {

private double

interestRate;

// Constructor public SavingAccount(String accountHolder, double balance,

double interestRate) { super(accountHolder, balance); this.interestRate =

interestRate;

// Apply interest method

SASCMA BCA COLLAGE,SURAT


Page | 8
Roll no :- 2231

public void applyInterest() { double interest =

(balance * interestRate) / 100; balance +=

interest;

System.out.println("Interest applied: " + interest + ". Current balance: " + balance);

// Account information

method @Override public void

accountInfo() {

System.out.println("Saving Account | Account Holder: " + accountHolder + ", Balance: " +


balance + ", Interest Rate: " + interestRate + "%");

// Current Account class class

CurrentAccount extends BankAccount

{ private double overdraftLimit;

// Constructor public CurrentAccount(String accountHolder, double balance,

double overdraftLimit) { super(accountHolder, balance); this.overdraftLimit =

overdraftLimit;

// Withdraw method (with overdraft limit)

@Override public void withdraw(double amount) { if

(amount > 0 && (balance + overdraftLimit) >= amount)

{ balance -= amount;

SASCMA BCA COLLAGE,SURAT


Page | 9
Roll no :- 2231

System.out.println("Withdrawn: " + amount + ". Current balance: " + balance);

} else {

System.out.println("Exceeds overdraft limit or invalid withdrawal amount.");

// Account information

method @Override public void

accountInfo() {

System.out.println("Current Account | Account Holder: " + accountHolder + ", Balance: "


+ balance + ", Overdraft Limit: " + overdraftLimit);

// Main class to test the program

public class BankSystem { public

static void main(String[] args) {

// Saving Account example

SavingAccount savingAccount = new SavingAccount("John Doe", 1000,

4); savingAccount.deposit(500); savingAccount.withdraw(200);

savingAccount.applyInterest(); savingAccount.accountInfo();

System.out.println(); // To separate the output

// Current Account example

CurrentAccount currentAccount = new CurrentAccount("Jane Doe", 2000,

500); currentAccount.deposit(1000); currentAccount.withdraw(2500); // Exceeds

SASCMA BCA COLLAGE,SURAT


Page | 10
Roll no :- 2231

balance, but under overdraft limit currentAccount.withdraw(5000); // Exceeds

overdraft limit currentAccount.accountInfo();

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.

public class CommandLineProcessor {

SASCMA BCA COLLAGE,SURAT


Page | 11
Roll no :- 2231

public static void main(String[] args) {

if (args.length != 2) {

System.out.println("Please provide exactly two arguments.");

return;

// Check if both arguments are numbers

try {

double num1 = Double.parseDouble(args[0]);

double num2 = Double.parseDouble(args[1]);

// If both are numbers, add them

double sum = num1 + num2;

System.out.println("Sum of the numbers: " + sum);

} catch (NumberFormatException e) {

// If not numbers, count vowels in the strings int

vowelCount = countVowels(args[0]) + countVowels(args[1]);

System.out.println("Total number of vowels: " + vowelCount);

// Method to count vowels in a string

public static int countVowels(String str) {

int count = 0;

String vowels = "aeiouAEIOU"; for

(int i = 0; i < str.length(); i++) { if

(vowels.indexOf(str.charAt(i)) != -1)

{ count++;

SASCMA BCA COLLAGE,SURAT


Page | 12
Roll no :- 2231

return count;

5. Write a program that stores details of 5 employees and display this


information after every one second

import java.util.Timer;

import java.util.TimerTask;

SASCMA BCA COLLAGE,SURAT


Page | 13
Roll no :- 2231

class Employee

{ int id;

String name;

String department;

// Constructor public Employee(int id, String name,

String department) {

this.id = id; this.name =

name; this.department =

department;

// Method to display employee details

public void display() {

System.out.println("ID: " + id + ", Name: " + name + ", Department: " + department);

public class EmployeeDetailsDisplay

public static void main(String[] args)

// Create an array of 5 Employee objects Employee[]

employees = new Employee[5]; employees[0] = new

Employee(1, "John Doe", "Finance"); employees[1] =

new

Employee(2, "Jane Smith", "Marketing"); employees[2] = new


SASCMA BCA COLLAGE,SURAT
Page | 14
Roll no :- 2231

Employee(3, "Bob Johnson", "IT"); employees[3] = new

Employee(4, "Alice Brown", "HR"); employees[4] = new

Employee(5, "Charlie Davis", "Operations");

// Use Timer to display employee details every second

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask()

int currentEmployee = 0;

@Override

public void run()

// Display the current employee details

if (currentEmployee < employees.length)

employees[currentEmployee].display();

currentEmployee++;

} else {

timer.cancel(); // Stop the timer after displaying all employees

}, 0, 1000); // Delay of 0ms, and repeat every 1000ms (1 second)

SASCMA BCA COLLAGE,SURAT


Page | 15
Roll no :- 2231

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”).

// Define the custom exception class class

InvalidArgumentException extends Exception


SASCMA BCA COLLAGE,SURAT
Page | 16
Roll no :- 2231

public InvalidArgumentException(String message)

super(message); // Call the constructor of Exception with the error message

public class CommandLineArgumentValidator

public static void main(String[] args)

// Predefined list of valid arguments

String[] validArguments = {"BCA", "MCA", "BBA", "MBA", "OTHER"};

// Check if exactly 5 arguments are

passed if (args.length != 5) {

System.out.println("Please provide exactly 5 arguments.");

return;

// Iterate through all arguments and check if they are valid

for (String arg : args)

try

SASCMA BCA COLLAGE,SURAT


Page | 17
Roll no :- 2231

// Validate the argument if

(!isValidArgument(arg, validArguments))

throw new InvalidArgumentException("Invalid argument: " + arg);

} catch (InvalidArgumentException e)

// Handle the exception by printing the error message

System.out.println(e.getMessage()); return; // Exit the

program after finding the first invalid argument

// If all arguments are valid, print a success message

System.out.println("All arguments are valid.");

// Method to check if the argument is valid public static

boolean isValidArgument(String arg, String[] validArguments)

for (String validArg : validArguments)

if (validArg.equals(arg))

return true; // Argument is valid

SASCMA BCA COLLAGE,SURAT


Page | 18
Roll no :- 2231

return false; // Argument is invalid

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.

SASCMA BCA COLLAGE,SURAT


Page | 19
Roll no :- 2231

import java.util.Scanner; import

java.util.Arrays;

class DisplayThread extends Thread

private String[] names;

// Constructor to pass the sorted names array

public DisplayThread(String[] names)

this.names = names;

@Override

public void run()

try

for (String name : names)

System.out.println(name);

Thread.sleep(1000); // Sleep for 1 second before displaying next name

} catch (InterruptedException e)

e.printStackTrace();

SASCMA BCA COLLAGE,SURAT


Page | 20
Roll no :- 2231

public class StudentNames

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

String[] studentNames = new String[10];

// Accept names of 10 students

System.out.println("Enter the names of 10 students:");

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

studentNames[i] = scanner.nextLine();

// Sort the names in ascending order

Arrays.sort(studentNames);

// Create a thread to display the names at 1-second intervals

DisplayThread displayThread = new DisplayThread(studentNames);

displayThread.start(); // Start the thread

SASCMA BCA COLLAGE,SURAT


Page | 21
Roll no :- 2231

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.

SASCMA BCA COLLAGE,SURAT


Page | 22
Roll no :- 2231

import java.util.Scanner;

public class ReverseAndSwapString

// Method to reverse and swap odd and even positioned characters

public static String reverseAndSwap(String str)

char[] chars = str.toCharArray();

int length = chars.length;

// Loop through the string, swapping the odd and even indexed characters

for (int i = 0; i < length - 1; i += 2)

char temp = chars[i];

chars[i] = chars[i + 1]; chars[i

+ 1] = temp;

// Reverse the string after swapping

String reversedString = new StringBuilder(new String(chars)).reverse().toString();

return reversedString;

public static void main(String[] args)

// Scanner to accept input from user


SASCMA BCA COLLAGE,SURAT
Page | 23
Roll no :- 2231

Scanner scanner = new Scanner(System.in);

// Accept string from the user

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

String inputString = scanner.nextLine();

// Get the result by calling the reverseAndSwap method

String result = reverseAndSwap(inputString);

// Display the result

System.out.println("Result after reversing and swapping: " + result);

scanner.close();

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.

SASCMA BCA COLLAGE,SURAT


Page | 24
Roll no :- 2231

public class ThreadExample

public static void main(String[] args)

// Create Runnable for each thread

Runnable javaRunnable = new Runnable()

@Override

public void run()

while (true)

try {

Thread.sleep(1000); // Sleep for 1 second

System.out.println("JAVA");

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

};

Runnable paperRunnable = new Runnable()

@Override

public void run()

SASCMA BCA COLLAGE,SURAT


Page | 25
Roll no :- 2231

while (true)

try {

Thread.sleep(2000); // Sleep for 2 seconds

System.out.println("PAPER");

} catch (InterruptedException e)

Thread.currentThread().interrupt();

};

Runnable collegeRunnable = new Runnable()

@Override

public void run()

while (true)

try

Thread.sleep(3000); // Sleep for 3 seconds

System.out.println("COLLEGE");

} catch (InterruptedException e)

SASCMA BCA COLLAGE,SURAT


Page | 26
Roll no :- 2231

Thread.currentThread().interrupt();

};

// Create threads for each Runnable

Thread javaThread = new Thread(javaRunnable);

Thread paperThread = new Thread(paperRunnable);

Thread collegeThread = new Thread(collegeRunnable);

// Start the threads

javaThread.start();

paperThread.start();

collegeThread.start();

SASCMA BCA COLLAGE,SURAT


Page | 27
Roll no :- 2231

SASCMA BCA COLLAGE,SURAT


Page | 28
Roll no :- 2231

10. Write a program to input two strings search similar characters from both
string and replace it with ‘*’.

import java.util.Scanner;

public class StringSimilarity

// Method to replace similar characters with '*' public

static String replaceSimilarChars(String str1, String str2)

// Convert both strings to character arrays for easy

comparison char[] arr1 = str1.toCharArray();char[] arr2 =

str2.toCharArray();

// Iterate through both arrays and replace common characters with

'*' for (int i = 0; i < arr1.length; i++) { for (int j = 0; j <

arr2.length; j++) { if (arr1[i] == arr2[j]) { arr1[i] =

'*'; // Replace common character in str1 with '*' arr2[j]

= '*'; // Replace common character in str2 with '*'

// Convert the arrays back to strings and return the modified strings

return new String(arr1) + "\n" + new String(arr2);

SASCMA BCA COLLAGE,SURAT


Page | 29
Roll no :- 2231

public static void main(String[] args)

// Create a Scanner object to read input

Scanner scanner = new Scanner(System.in);

// Input the two strings

System.out.print("Enter first string:

"); String str1 = scanner.nextLine();

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

String str2 = scanner.nextLine();

// Call the method to replace similar characters

String result = replaceSimilarChars(str1, str2);

// Output the result

System.out.println("Modified strings:");

System.out.println(result);

// Close the scanner

scanner.close();

SASCMA BCA COLLAGE,SURAT


Page | 30
Roll no :- 2231

SASCMA BCA COLLAGE,SURAT


Page | 31
Roll no :- 2231

11. Write a java program that accepts string data. Extract either all vowels or
all Non-vowels from given data according to option selection.

import java.util.Scanner;

public class VowelNonVowelExtractor

// Method to check if a character is a vowel

public static boolean isVowel(char ch)

ch = Character.toLowerCase(ch); // Convert to lowercase to handle both uppercase and


lowercase

return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';

// Method to extract vowels or non-vowels based on the option selected

public static String extractVowels(String data, boolean extractVowels)

StringBuilder result = new StringBuilder();

for (int i = 0; i < data.length(); i++)

char ch = data.charAt(i);

if (Character.isAlphabetic(ch))

SASCMA BCA COLLAGE,SURAT


Page | 32
Roll no :- 2231

if (extractVowels && isVowel(ch))

result.append(ch); // Add vowel

} else if (!extractVowels && !isVowel(ch))

result.append(ch); // Add non-vowel

return result.toString();

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

// Prompt user for input string

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

String inputString = scanner.nextLine();

// Prompt user for selection

System.out.println("Select an

option:"); System.out.println("1.

Extract vowels");

System.out.println("2. Extract non-

vowels"); System.out.print("Enter 1 or 2: "); int

option

= scanner.nextInt();
SASCMA BCA COLLAGE,SURAT
Page | 33
Roll no :- 2231

// Validate the option

if (option == 1)

String vowels = extractVowels(inputString, true);

System.out.println("Vowels: " + vowels);

} else if (option == 2)

String nonVowels = extractVowels(inputString,

false); System.out.println("Non-vowels: " +

nonVowels);

} else {

System.out.println("Invalid option. Please select 1 or 2.");

scanner.close();

SASCMA BCA COLLAGE,SURAT


Page | 34
Roll no :- 2231

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)

import java.util.Scanner;

public class StringCaseConverter

// Method to convert a string to UPPERCASE

public static String toUpperCase(String input)

return input.toUpperCase();

// Method to convert a string to lowercase

public static String toLowerCase(String input)

return input.toLowerCase();

// Method to convert a string to Sentence case

public static String toSentenceCase(String input)

// Trim the input and convert the first letter to uppercase, others to

lowercase StringBuilder result = new StringBuilder(); boolean capitalizeNext

= true;

for (char ch : input.trim().toCharArray())


SASCMA BCA COLLAGE,SURAT
Page | 35
Roll no :- 2231

SASCMA BCA COLLAGE,SURAT


Page | 36
Roll no :- 2231

if (capitalizeNext && Character.isLetter(ch))

result.append(Character.toUpperCase(ch));

capitalizeNext = false;

} else {

result.append(Character.toLowerCase(ch));

// Set capitalizeNext to true if a period is encountered, which ends a sentence.

if (ch == '.') {

capitalizeNext = true;

return result.toString();

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

// Prompt user for input string

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

String inputString = scanner.nextLine();

// Display options to user

System.out.println("Select an option to change the case of the string:");

SASCMA BCA COLLAGE,SURAT


Page | 37
Roll no :- 2231

System.out.println("1. UPPERCASE");

System.out.println("2. lowercase");

System.out.println("3. Sentence case");

System.out.print("Enter 1, 2 or 3: "); int

option = scanner.nextInt();

// Perform the operation based on the selected option

String result = "";

switch (option)

{ case 1:

result = toUpperCase(inputString);

break;

case 2:

result = toLowerCase(inputString);

break;

case 3:

result = toSentenceCase(inputString);

break;

default:

System.out.println("Invalid option. Please select 1, 2 or 3.");

break;

if (!result.isEmpty())

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

SASCMA BCA COLLAGE,SURAT


Page | 38
Roll no :- 2231

scanner.close();

13. Write a program to create singly Link List and perform following operations:
SASCMA BCA COLLAGE,SURAT
Page | 39
Roll no :- 2231

1. Insert a node at desired Location.

2. Delete a node from given Location.

3. Update desired Location.

4. Search

5. Display

import java.util.Scanner;

class SinglyLinkedList

// Node class represents each element in the linked

list static class Node { int data;

Node next;

public Node(int data)

this.data = data;

this.next = null;

private Node head;

// Constructor to initialize the linked list

public SinglyLinkedList()

SASCMA BCA COLLAGE,SURAT


Page |
310
Roll no :- 2231

{ head =

null;

// Insert a node at a desired location public

void insertAtLocation(int data, int position)

Node newNode = new Node(data);

if (position == 1) { // Insert at the beginning

newNode.next = head; head = newNode;

return;

Node current = head; for (int i = 1; i < position

- 1 && current != null; i++)

current = current.next;

if (current == null) {

System.out.println("Position is out of bounds.");

return;

newNode.next = current.next;

current.next = newNode;

SASCMA BCA COLLAGE,SURAT


Page | 40
Roll no :- 2231

// Delete a node from a given location

public void deleteAtLocation(int position)

if (head == null) {

System.out.println("List is empty.");

return;

if (position == 1) { // Deleting the first node

head = head.next; return;

Node current = head; for (int i = 1; i < position

- 1 && current != null; i++)

current = current.next;

if (current == null || current.next == null)

System.out.println("Position is out of bounds.");

return;

current.next = current.next.next;

SASCMA BCA COLLAGE,SURAT


Page | 41
Roll no :- 2231

// Update a node at a desired location public

void updateAtLocation(int data, int position)

Node current = head; for (int i = 1; i

< position && current != null; i++)

current = current.next;

if (current == null) {

System.out.println("Position is out of bounds.");

return;

current.data = data;

// Search for a node by its value

public void search(int value)

Node current = head;

int position = 1; while

(current != null)

if (current.data == value)

SASCMA BCA COLLAGE,SURAT


Page | 42
Roll no :- 2231

System.out.println("Node with value " + value + " found at position " + position);

return;

current = current.next;

position++;

System.out.println("Node with value " + value + " not found.");

// Display the linked list

public void display()

if (head == null)

System.out.println("The list is

empty."); return;

Node current = head;

while (current != null)

System.out.print(current.data + " -> ");

current = current.next;

System.out.println("null");

SASCMA BCA COLLAGE,SURAT


Page | 43
Roll no :- 2231

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

SinglyLinkedList list = new SinglyLinkedList();

while (true) {

System.out.println("\nSelect an operation:");

System.out.println("1. Insert a node at desired location");

System.out.println("2. Delete a node from given location");

System.out.println("3. Update node at desired location");

System.out.println("4. Search for a node");

System.out.println("5. Display the list");

System.out.println("6. Exit");

System.out.print("Enter choice: "); int

choice = scanner.nextInt();

switch (choice)

{ case 1:

System.out.print("Enter data to insert:

"); int dataInsert = scanner.nextInt();

System.out.print("Enter position to insert: ");

int positionInsert = scanner.nextInt();

list.insertAtLocation(dataInsert, positionInsert);

break;

case 2:

SASCMA BCA COLLAGE,SURAT


Page | 44
Roll no :- 2231

System.out.print("Enter position to delete: ");

int positionDelete = scanner.nextInt();

list.deleteAtLocation(positionDelete);

break;

case 3:

System.out.print("Enter data to update: ");

int dataUpdate = scanner.nextInt();

System.out.print("Enter position to update: "); int

positionUpdate = scanner.nextInt();

list.updateAtLocation(dataUpdate, positionUpdate);

break;

case 4:

System.out.print("Enter value to search: ");

int valueSearch = scanner.nextInt();

list.search(valueSearch); break;

case 5: list.display(); break;

case 6:

System.out.println("Exiting program...");

scanner.close(); return; default:

System.out.println("Invalid choice. Please try again.");

SASCMA BCA COLLAGE,SURAT


Page | 45
Roll no :- 2231

SASCMA BCA COLLAGE,SURAT


Page | 46
Roll no :- 2231

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.

// Java program to implement Singly Circular Linked List

class SinglyCircularLinkedList

// Node class

static class Node

int data;

Node next;

// Constructor to create a new

node Node(int data) { this.data = data;

this.next = null;

// Head of the list

Node head = null; // 1.

Insert a node at the

beginning public void

SASCMA BCA COLLAGE,SURAT


Page | 47
Roll no :- 2231

insertAtBeginning(int

data)

Node newNode = new Node(data);

if (head == null) { head =

newNode; newNode.next = head; //

Circular link

} else {

Node temp = head;

while (temp.next != head)

temp = temp.next;

temp.next = newNode; newNode.next

= head; head = newNode; // Update head to

new node

// 2. Insert a node at the end public

void insertAtEnd(int data) { Node

newNode = new Node(data);

if (head == null) { head =

newNode; newNode.next = head; //

Circular link

} else {

Node temp = head;

while (temp.next != head)


SASCMA BCA COLLAGE,SURAT
Page | 48
Roll no :- 2231

SASCMA BCA COLLAGE,SURAT


Page | 49
Roll no :- 2231

temp = temp.next;

temp.next = newNode;

newNode.next = head;

// 3. Delete the first node

public void deleteFirstNode()

if (head == null) {

System.out.println("List is empty.");

return;

} else if (head.next == head) {

head = null;

} else {

Node temp = head;

while (temp.next != head)

{ temp = temp.next;

head = head.next;

temp.next = head;

SASCMA BCA COLLAGE,SURAT


Page |
410
Roll no :- 2231

// 4. Delete the last node

public void deleteLastNode() {

if (head == null) {

System.out.println("List is empty.");

return;

} else if (head.next == head) {

head = null;

} else {

Node temp = head;

while (temp.next != head)

{ temp = temp.next;

Node temp2 = head;

while (temp2.next != temp)

{ temp2 = temp2.next;

temp2.next = head; // Delete last node

// 5. Display the list

public void display() {

if (head == null) {

System.out.println("List is empty.");

return;

Node temp = head;

SASCMA BCA COLLAGE,SURAT


Page | 50
Roll no :- 2231

do {

System.out.print(temp.data + " ");

temp = temp.next;

} while (temp != head);

System.out.println();

public static void main(String[] args) {

SinglyCircularLinkedList list = new SinglyCircularLinkedList();

// Inserting nodes

list.insertAtBeginning(10);

list.insertAtEnd(20);

list.insertAtBeginning(5);

list.insertAtEnd(30);

// Display list

System.out.print("List after insertions:

"); list.display();

// Deleting nodes

list.deleteFirstNode();

list.deleteLastNode();

// Display list after deletions

System.out.print("List after deletions:

");

SASCMA BCA COLLAGE,SURAT


Page | 51
Roll no :- 2231

list.display();

SASCMA BCA COLLAGE,SURAT


Page | 52
Roll no :- 2231

SASCMA BCA COLLAGE,SURAT


Page | 53

You might also like