Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Java Lab Manual

Uploaded by

Manish Dhanuk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Java Lab Manual

Uploaded by

Manish Dhanuk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Ques1. Write a program to Print Right Triangle Star Pattern?

Source code:-

import java.util.Scanner;

public class RightTriangleStarPattern {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


int rows = scanner.nextInt();

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}

scanner.close();
}
}

Output:-
*
**
***
****
*****
Ques2. Write a program to Convert Binary to Octal?
Source code:-
import java.util.Scanner;

public class BinaryToOctal {


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

System.out.print("Enter a binary number: ");


String binaryString = scanner.nextLine();
int decimal = Integer.parseInt(binaryString, 2);
String octalString = Integer.toOctalString(decimal);

System.out.println("Octal equivalent: " + octalString);

scanner.close();
}
}

Output:-
Enter a binary number: 1
Octal equivalent: 1
Ques3. Write a program for Linear Search?
Source code:-

import java.util.Scanner;

public class LinearSearch {


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

System.out.print("Enter the number of elements in the array: ");


int n = scanner.nextInt();

int[] array = new int[n];

System.out.println("Enter the elements of the array:");


for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

System.out.print("Enter the element to search for: ");


int target = scanner.nextInt();

int index = linearSearch(array, target);

if (index == -1) {
System.out.println("Element not found in the array.");
} else {
System.out.println("Element found at index: " + index);
}

scanner.close();
}
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return I;
}
}
return -1; // Return -1 if not found
}
}

Output:-
Enter the number of elements in the array: 5
Enter the elements of the array:
10
20
30
40
50
Enter the element to search for: 30
Ques4. Write a program reverse a string in Java?
Source code:-
import java.util.Scanner;

public class ReverseString {


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

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


String inputString = scanner.nextLine();

String reversedString = reverseString(inputString);

System.out.println("Reversed string: " + reversedString);

scanner.close();
}

public static String reverseString(String str) {


StringBuilder stringBuilder = new StringBuilder(str);
return stringBuilder.reverse().toString();
}
}
Output:-
Enter a string: Hello, World!Hello, World!
Reversed string: !dlroW ,olleH
Ques5. Write a program to check if the given number is a prime number?
Source code:-
import java.util.Scanner;
public class PrimeNumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = isPrimeNumber(number);
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}

public static boolean isPrimeNumber(int num) {


if (num <= 1) {
return false; // 0 and 1 are not prime numbers
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Output:-
Enter a number: 17
17 is a prime number.
Ques6. . Write a program to check if a list of integers contains only odd numbers in
Java?
Source code:-
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class OddNumberCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();

// Input numbers
System.out.println("Enter integers (type 'done' to finish):");
while (true) {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("done")) {
break;
}
try {
int number = Integer.parseInt(input);
numbers.add(number);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid integer or 'done' to finish.");
}
}

// Check if all numbers are odd


boolean allOdd = areAllOdd(numbers);

// Output the result


if (allOdd) {
System.out.println("The list contains only odd numbers.");
} else {
System.out.println("The list contains some even numbers.");
}

scanner.close();
}

// Method to check if all numbers are odd


public static boolean areAllOdd(List<Integer> numbers) {
for (int number : numbers) {
if (number % 2 == 0) {
return false; // Found an even number
}
}
return true; // All numbers are odd
}
}
Output:-
Enter integers (type 'done' to finish):
3
5
7
2
done
The list contains some even number.
Ques7. Write a program to check whether a string is a palindrome in Java?
Source code:-
import java.util.Scanner;

public class PalindromeCheck {


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

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


String inputString = scanner.nextLine();

boolean isPalindrome = isPalindrome(inputString);

if (isPalindrome) {
System.out.println("\"" + inputString + "\" is a palindrome.");
} else {
System.out.println("\"" + inputString + "\" is not a palindrome.");
}

scanner.close();
}

// Method to check if a string is a palindrome


public static boolean isPalindrome(String str) {
str = str.replaceAll("\\s+", "").toLowerCase();
String reversedString = new StringBuilder(str).reverse().toString();
return str.equals(reversedString);
}
}
Output:-
Enter a string: A man a plan a canal Panama
"A man a plan a canal Panama" is a palindrome.
Ques8.Write a program to remove spaces from a string in Java?

Source code:-
import java.util.Scanner;

public class RemoveSpaces {


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

// Input the string from which spaces will be removed


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Remove spaces from the string


String resultString = removeSpaces(inputString);

// Output the result


System.out.println("String without spaces: \"" + resultString + "\"");

scanner.close();
}

// Method to remove spaces from a string


public static String removeSpaces(String str) {
return str.replaceAll("\\s+", ""); // Remove all whitespace characters
}
}
Output:-
Enter a string: Hello, how are you?
String without spaces: "Hello,howareyou?"
Ques9. Write a program to remove leading and trailing spaces from a string in Java?
Source code:-
import java.util.Scanner;

public class TrimSpaces {


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

// Input the string with potential leading and trailing spaces


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Remove leading and trailing spaces


String trimmedString = trimSpaces(inputString);

// Output the result


System.out.println("String after trimming: \"" + trimmedString + "\"");

scanner.close();
}

// Method to remove leading and trailing spaces from a string


public static String trimSpaces(String str) {
return str.trim(); // Remove leading and trailing whitespace
}
}
Output:-
Enter a string: Hello, World!
String after trimming: "Hello, World!"
Ques10. Write a program to sort an array in Java?
Source code:-
import java.util.Arrays;
import java.util.Scanner;

public class SortArray {


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

System.out.print("Enter the number of elements in the array: ");


int n = scanner.nextInt();

int[] array = new int[n];

System.out.println("Enter the elements of the array:");


for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

Arrays.sort(array);
System.out.println("Sorted array: " + Arrays.toString(array));
scanner.close();
}
}
Output:-
Enter the number of elements in the array: 5
Enter the elements of the array:
3
1
4
1
5
Sorted array: [1, 1, 3, 4, 5]
Ques11. Write a program to create a deadlock scenario programmatically in Java?
Source code:-
public class DeadlockExample {

public static void main(String[] args) {


final Object lock1 = new Object();
final Object lock2 = new Object();

// Thread 1
Thread thread1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1: Holding lock 1...");

try {
// Simulate some work with lock 1
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Thread 1: Waiting for lock 2...");

synchronized (lock2) {
System.out.println("Thread 1: Acquired lock 2!");
}
}
});

// Thread 2
Thread thread2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("Thread 2: Holding lock 2...");
try {
// Simulate some work with lock 2
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Thread 2: Waiting for lock 1...");

synchronized (lock1) {
System.out.println("Thread 2: Acquired lock 1!");
}
}
});

thread1.start();
thread2.start();
}
}
Output:-
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...
Ques12. Write a program to find the factorial of an integer in Java?
Source code:-
import java.util.Scanner;

public class FactorialCalculator {


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

// Input the integer


System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();

if (number < 0) {
System.out.println("Factorial is not defined for negative integers.");
} else {
// Calculate factorial using iterative method
long iterativeFactorial = factorialIterative(number);
System.out.println("Factorial (iterative) of " + number + " is: " +
iterativeFactorial);

// Calculate factorial using recursive method


long recursiveFactorial = factorialRecursive(number);
System.out.println("Factorial (recursive) of " + number + " is: " +
recursiveFactorial);
}

scanner.close();
}

// Iterative method to calculate factorial


public static long factorialIterative(int num) {
long result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}

// Recursive method to calculate factorial


public static long factorialRecursive(int num) {
if (num == 0) {
return 1; // Base case
} else {
return num * factorialRecursive(num - 1); // Recursive call
}
}
}
Output:-
Enter a non-negative integer: 5
Factorial (iterative) of 5 is: 120
Factorial (recursive) of 5 is: 120
Ques.13 Write a program to you reverse a linked list in Java?
Source code:-
class Node {
int data;
Node next;

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

class LinkedList {
Node head;
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
} public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
} public void reverse() {
Node previous = null;
Node current = head;
Node next = null;

while (current != null) {


next = current.next; // Store the next node
current.next = previous; // Reverse the current node's pointer
previous = current; // Move previous to current
current = next; // Move to the next node
}
head = previous; // Update head to the new first node
}
}
public class LinkedListReversal {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);

System.out.println("Original Linked List:");


linkedList.display();
linkedList.reverse();
System.out.println("Reversed Linked List:");
linkedList.display();
}}
Output:-
Original Linked List:
1 -> 2 -> 3 -> 4 -> 5 -> null
Reversed Linked List:
5 -> 4 -> 3 -> 2 -> 1 -> null
Ques14. . Write a program to implement a binary search in Java?
Source code:-
import java.util.Scanner;

public class BinarySearch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

int[] array = new int[n];

System.out.println("Enter the sorted elements of the array:");


for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

System.out.print("Enter the target value: ");


int target = scanner.nextInt();
int index = binarySearch(array, target);

if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}

scanner.close();
}
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Calculate the middle index

if (array[mid] == target) {
return mid; // Target found
}
if (array[mid] < target) {
left = mid + 1;
} // If target is smaller, ignore the right half
else {
right = mid - 1;
}
}

return -1; // Target not found


}
}
Output:-
Enter the number of elements in the array: 5
Enter the sorted elements of the array:
1
3
5
7
9
Enter the target value: 5
Ques15. Write a program to program that illustrates merge sort?

Source code:-
import java.util.Arrays;
import java.util.Scanner;
public class MergeSort {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input array size


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Initialize the array


int[] array = new int[n];

// Input array elements


System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

// Perform merge sort


mergeSort(array, 0, array.length - 1);

// Output the sorted array


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

scanner.close();
}

// Merge sort method


public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
// Find the middle point
int mid = left + (right - left) / 2;

// Sort the first half


mergeSort(array, left, mid);
// Sort the second half
mergeSort(array, mid + 1, right);

// Merge the sorted halves


merge(array, left, mid, right);
}
}

// Merge method to combine two sorted halves


public static void merge(int[] array, int left, int mid, int right) {
// Find sizes of two subarrays to be merged
int n1 = mid - left + 1;
int n2 = right - mid;

// Create temp arrays


int[] leftArray = new int[n1];
int[] rightArray = new int[n2];

// Copy data to temp arrays


System.arraycopy(array, left, leftArray, 0, n1);
System.arraycopy(array, mid + 1, rightArray, 0, n2);
// Initial indexes of first and second subarrays
int i = 0, j = 0;

// Initial index of merged subarray


int k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}

// Copy remaining elements of leftArray[] if any


while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}

// Copy remaining elements of rightArray[] if any


while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
}
Output:-
Enter the number of elements in the array: 5
Enter the elements of the array:
38
27
43
3
9
Ques16. Write a program to checks if two arrays contain the same elements?
Source code:-
import java.util.Arrays;
import java.util.Scanner;

public class ArrayElementCheck {


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

// Input first array


System.out.print("Enter the number of elements in the first array: ");
int n1 = scanner.nextInt();
int[] array1 = new int[n1];
System.out.println("Enter the elements of the first array:");
for (int i = 0; i < n1; i++) {
array1[i] = scanner.nextInt();
}

// Input second array


System.out.print("Enter the number of elements in the second array: ");
int n2 = scanner.nextInt();
int[] array2 = new int[n2];
System.out.println("Enter the elements of the second array:");
for (int i = 0; i < n2; i++) {
array2[i] = scanner.nextInt();
}

// Check if the arrays contain the same elements


boolean areEqual = haveSameElements(array1, array2);

// Output the result


if (areEqual) {
System.out.println("The two arrays contain the same elements.");
} else {
System.out.println("The two arrays do not contain the same elements.");
}

scanner.close();
} // Method to check if two arrays have the same elements
public static boolean haveSameElements(int[] array1, int[] array2) {
// If lengths are different, arrays can't be the same
if (array1.length != array2.length) {
return false;
} // Sort both arrays
Arrays.sort(array1);
Arrays.sort(array2); // Compare the sorted arrays
return Arrays.equals(array1, array2);
}
}
Output:-
Enter the number of elements in the first array: 5
Enter the elements of the first array:
3
1
4
2
5
Enter the number of elements in the second array: 5
Enter the elements of the second array:
54
4
3
2
1
The two arrays contain the same elements.
Ques17. Write a program to the sum of all elements in an integer array in Java?
Source code:-
import java.util.Arrays;
import java.util.Scanner;

public class ArrayElementCheck {


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

// Input first array


System.out.print("Enter the number of elements in the first array: ");
int n1 = scanner.nextInt();
int[] array1 = new int[n1];
System.out.println("Enter the elements of the first array:");
for (int i = 0; i < n1; i++) {
array1[i] = scanner.nextInt();
}

// Input second array


System.out.print("Enter the number of elements in the second array: ");
int n2 = scanner.nextInt();
int[] array2 = new int[n2];
System.out.println("Enter the elements of the second array:");
for (int i = 0; i < n2; i++) {
array2[i] = scanner.nextInt();
}

// Check if the arrays contain the same elements


boolean areEqual = haveSameElements(array1, array2);

// Output the result


if (areEqual) {
System.out.println("The two arrays contain the same elements.");
} else {
System.out.println("The two arrays do not contain the same elements.");
}

scanner.close();
}

// Method to check if two arrays have the same elements


public static boolean haveSameElements(int[] array1, int[] array2) {
// If lengths are different, arrays can't be the same
if (array1.length != array2.length) {
return false;
} // Sort both arrays
Arrays.sort(array1);
Arrays.sort(array2) // Compare the sorted arrays
return Arrays.equals(array1, array2);
}
}
Output:-
Enter the number of elements in the first array: 5
Enter the elements of the first array:
3
1
4
2
5
Enter the number of elements in the second array: 5
Enter the elements of the second array:
5
4
3
2
1
Ques18. Write a program to find the second largest number in an array in Java?
Source code:-
import java.util.Scanner;

public class SecondLargestInArray {


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

// Input array size


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Initialize the array


int[] array = new int[n];

// Input array elements


System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

// Find the second largest number


int secondLargest = findSecondLargest(array);

// Output the result


if (secondLargest != Integer.MIN_VALUE) {
System.out.println("The second largest number is: " + secondLargest);
} else {
System.out.println("There is no second largest number (all elements may be the
same).");
}

scanner.close();
}

// Method to find the second largest number in the array


public static int findSecondLargest(int[] array) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;

for (int num : array) {


if (num > largest) {
secondLargest = largest; // Update second largest
largest = num; // Update largest
} else if (num > secondLargest && num < largest) {
secondLargest = num; // Update second largest
}
}

return secondLargest;
}
}
Output:-
Enter the number of elements in the array: 5
Enter the elements of the array:
3
1
4
2
5
Ques19. . Write a program to shuffle an array in Java?
Source code:-
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class ShuffleArray {


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

// Input array size


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Initialize the array


int[] array = new int[n];

// Input array elements


System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

// Shuffle the array


shuffleArray(array);

// Output the shuffled array


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

scanner.close();
}

// Method to shuffle the array using Fisher-Yates algorithm


public static void shuffleArray(int[] array) {
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
// Generate a random index between 0 and i
int j = random.nextInt(i + 1);
// Swap array[i] with the element at random index
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
Output:-
Enter the number of elements in the array: 5
Enter the elements of the array:
1
2
3
4
5
Ques20. . Write a program to find a string in a text file in Java?
Source code:-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class StringFinderInFile {


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

// Input the filename and the string to search


System.out.print("Enter the filename (with path if not in the same directory): ");
String filename = scanner.nextLine();

System.out.print("Enter the string to search for: ");


String searchString = scanner.nextLine();

// Search for the string in the file


boolean found = findStringInFile(filename, searchString);

if (found) {
System.out.println("The string \"" + searchString + "\" was found in the file.");
} else {
System.out.println("The string \"" + searchString + "\" was not found in the
file.");
}

scanner.close();
}

// Method to search for a string in a text file


public static boolean findStringInFile(String filename, String searchString) {
boolean found = false;

try (BufferedReader br = new BufferedReader(new FileReader(filename))) {


String line;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
if (line.contains(searchString)) {
System.out.println("Found at line " + lineNumber + ": " + line);
found = true;
}
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}

return found;
}
}
Output:-
Enter the filename (with path if not in the same directory): Hello, world!
This is a sample text file.
We are testing string search.
Goodbye!Hello, world!

This is a sample text file.

We are testing string search.

Goodbye!
Enter the string to search for: Error reading the file: Hello, world! (No such file or
directory)
The string "" was not found in the file.

You might also like