Java coding interview questions for Fresher job.
For fresher-level Java coding interviews, interviewers often focus on assessing your basic programming skills, problem-solving abilities, and understanding of core Java concepts.Here are some coding questions that you might encounter:
Part 1: Basic Java Programs with explanation
- First Java Program to print “Hellow World”
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
Output:
Hellow World!
Explanation:
- public class HelloWorld: Defines a class named HelloWorld.
- public static void main(String[] args): This is the main method, where the execution of the program begins.
- out.println(“Hello, World!”);: Prints the string “Hello, World!” to the console.
- WAP to find the sum of Two Numbers?
public class SumOfTwoNumbers {
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
System.out.println(“Sum of ” + num1 + ” and ” + num2 + ” is: ” + sum);
}
}
Output:
Sum of 5 and 10 is: 15
Explanation:
- int num1 = 5; and int num2 = 10;: Declare and initialize two integer variables.
- int sum = num1 + num2;: Calculate the sum of num1 and num2.
- out.println(“Sum of ” + num1 + ” and ” + num2 + ” is: ” + sum);:
- Prints the sum.
- WAP to Calculates the factorial of the given number?
public class Factorial {
public static void main(String[] args) {
int n = 5;
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println(“Factorial of ” + n + ” is: ” + factorial);
}
}
Output:
Factorial of 5 is: 120
Explanation:
- int n = 5;: The number for which factorial is calculated.
- long factorial = 1;: Initialize a variable to store the factorial value.
- for (int i = 1; i <= n; i++): Loop to multiply numbers from 1 to n.
- factorial *= i;: Multiply each iteration’s value to calculate the factorial.
- out.println(“Factorial of ” + n + ” is: ” + factorial);:
- Prints the factorial.
- WAP to find whether the given String is Palindrome or not?
public class PalindromeCheck {
public static void main(String[] args) {
String str = “mom”;
String reversed = “”;
for (int i = str.length() – 1; i >= 0; i–) {
reversed += str.charAt(i);
}
boolean isPalindrome = str.equalsIgnoreCase(reversed);
System.out.println(str + ” is a palindrome: ” + isPalindrome);
}
}
Output:
mom
Explanation:
- String str = “level”;: The string to check for palindrome.
- String reversed = “”;: Initialize an empty string to store the reversed version.
- for (int i = str.length() – 1; i >= 0; i–): Loop to reverse the string.
- reversed += str.charAt(i);: Append characters in reverse order to reversed.
- boolean isPalindrome = str.equalsIgnoreCase(reversed);: Check if the original and reversed strings are equal.
- out.println(str + ” is a palindrome: ” + isPalindrome);:
- Prints the palindrome result.
- Write Java Program to find whether the given number is Prime or not?
public class PrimeNumber {
public static void main(String[] args) {
int number = 17;
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); ++i) {
if (number % i == 0) {
isPrime = false;
break;
}
}
System.out.println(number + ” is ” + (isPrime ? “prime” : “not prime”));
}
}
Explanation:
- The program defines a class named
- Inside the main method:
- An integer variable number is initialized with the value 17.
- A boolean variable isPrime is initialized with the value true.
- A for loop is used to check if the number is divisible by any integer from 2 to the square root of the number.
- If it is divisible, the isPrime flag is set to false, and the loop breaks.
- The result is printed to the console.
Using Recursion:
public class PrimeChecker {
public static boolean isPrime(int n) {
return isPrimeRecursive(n, n – 1);
}
private static boolean isPrimeRecursive(int n, int divisor) {
// Base cases
if (n <= 1) {
return false;
}
// If divisor reaches 1, the number is prime
if (divisor == 1) {
return true;
}
// If n is divisible by the current divisor, it’s not prime
if (n % divisor == 0) {
return false;
}
// Recursively check the next divisor
return isPrimeRecursive(n, divisor – 1);
}
public static void main(String[] args) {
// Example usage
int number = 17; // Replace this with the number you want to check
boolean result = isPrime(number);
if (result) {
System.out.println(number + ” is a prime number.”);
} else {
System.out.println(number + ” is not a prime number.”);
}
}
}
Explanation:
- The isPrime method is the entry point for checking whether a number is prime. It initializes the recursive call with the number to be checked and the initial divisor (n – 1).
- The isPrimeRecursive method is the recursive function that performs the prime checking.
- Base cases are similar to the Python implementation. If n is less than or equal to 1, it’s not a prime number. If the current divisor reaches 1, the number is
- The method checks for divisibility and makes a recursive call with the updated divisor until a base case is met.
- In the main method, you can replace the number variable with the actual number you want to check for primality.
6 Write Java Program to find Fibonacci Series Number.
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10;
int first = 0, second = 1;
System.out.print(“Fibonacci Series up to ” + n + “: “);
for (int i = 0; i < n; ++i) {
System.out.print(first + ” “);
int next = first + second;
first = second;
second = next;
}
}
}
Explanation:
- The program defines a class named
- Inside the main method:
- An integer variable n is initialized with the value 10.
- Two variables first and second are initialized with the values 0 and 1, respectively.
- A for loop is used to print the Fibonacci series up to the specified value of n.
- The loop calculates the next Fibonacci number in each iteration and updates the first and second variables.
- How to find the factorial of the given number?
import java.util.Scanner;
public class FactorialExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a non-negative integer: “);
int number = sc.nextInt();
long factorial = 1; // Use long to handle larger factorials
if (number < 0) {
System.out.println(“Factorial is not defined for negative numbers.”);
} else {
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println(“Factorial of ” + number + ” is: ” + factorial);
}
}
}
Explanation:
Import the Scanner class:
import java.util.Scanner;
This allows us to get user input from the console.
Create a class and main method:
public class FactorialExample {
public static void main(String[] args) {
This is where the program execution begins.
Create a Scanner object:
Scanner sc = new Scanner(System.in);
This object is used to read input from the user.
Prompt the user to enter a number:
System.out.print(“Enter a non-negative integer: “);
Read the input number:
int number = sc.nextInt();
Initialize a variable to store the factorial:
long factorial = 1;
Use long to handle larger factorials.
Check for negative input:
if (number < 0) {
System.out.println(“Factorial is not defined for negative numbers.”);
}
Calculate the factorial using a for loop:
for (int i = 1; i <= number; i++) {
factorial *= i;
This loop multiplies the factorial by each number from 1 to the input number.
}
Print the factorial:
System.out.println(“Factorial of ” + number + ” is: ” + factorial);
Sometimes interviewer used to ask the same program like “How can you find Factorial number using Recursion”
Using Recursion:
public class FactorialExample2 {
static long factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n – 1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a non-negative integer: “);
int number = sc.nextInt();
long result = factorial(number);
System.out.println(“Factorial of ” + number + ” is: ” + result);
}
}
Explanation:
Create a class and main method:
public class FactorialExample2 { … }
Define a recursive function to calculate factorial:
static long factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
}
else {
return n * factorial(n – 1); // Recursive call
}
}
Get user input:
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a non-negative integer: “);
int number = sc.nextInt();
Call the recursive function and print the result:
long result = factorial(number);
System.out.println(“Factorial of ” + number + ” is: ” + result);
- WAP to reverse a String?
public class ReverseString {
public static void main(String[] args) {
String original = “Hello”;
String reversed = “”;
for (int i = original.length() – 1; i >= 0; i–) {
reversed += original.charAt(i);
}
System.out.println(“Original: ” + original);
System.out.println(“Reversed: ” + reversed);
}
}
Output:
Original: Hello
Reversed: olleH
Explanation:
- String original = “Hello”;: The original string to be reversed.
- String reversed = “”;: An empty string to store the reversed version.
- for (int i = original.length() – 1; i >= 0; i–): Loop through the characters in reverse order.
- reversed += original.charAt(i);: Append each character to the reversed string.
- Print the original and reversed strings.
- WAP to calculate the average of Numbers
public class AverageCalculator {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println(“Average: ” + average);
}
}
Output:
Average: 30.0
Explanation:
- int[] numbers = {10, 20, 30, 40, 50};: An array of numbers.
- int sum = 0;: Variable to store the sum of numbers.
- for (int num : numbers) { sum += num; }: Loop through the array to calculate the sum.
- double average = (double) sum / numbers.length;: Calculate the average.
- Print the average.
- WAP to find the given number is ArmStrong number or not?
public class ArmstrongNumberCheck {
public static void main(String[] args) {
int num = 153;
int originalNum = num;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, 3);
num /= 10;
}
boolean isArmstrong = originalNum == sum;
System.out.println(originalNum + ” is an Armstrong number: ” + isArmstrong);
}
}
Output:
153 is an Armstrong number: true
Explanation:
- int num = 153;: The number to check.
- int originalNum = num;: Save the original number.
- int sum = 0;: Variable to store the sum of cubes of digits.
- while (num > 0) { sum += Math.pow(num % 10, 3); num /= 10; }: Calculate the sum of cubes of digits.
- boolean isArmstrong = originalNum == sum;: Check if the original number is equal to the sum.
- Print the result.
Conditional and Loops Java Programs
- WAP to find whether the given number is Even or Odd number
public class EvenOddCheck {
public static void main(String[] args) {
int number = 15;
if (number % 2 == 0) {
System.out.println(number + ” is an even number.”);
} else {
System.out.println(number + ” is an odd number.”);
}
}
}
Output:
15 is an odd number
- WAP to find whether the given number is positive or negative or zero
public class PositiveNegativeZeroCheck {
public static void main(String[] args) {
int number = -5;
if (number > 0) {
System.out.println(number + ” is a positive number.”);
} else if (number < 0) {
System.out.println(number + ” is a negative number.”);
} else {
System.out.println(number + ” is zero.”);
}
}
}
Output:
5 is positive number
- WAP to Calculates the sum of the first n natural numbers using a for loop.
public class SumWithForLoop {
public static void main(String[] args) {
int n = 5;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println(“Sum of first ” + n + ” natural numbers is: ” + sum);
}
}
Output:
Sum of first 5 natural number is 15
- WAP to prints the multiplication table of a given number using a for loop.
public class MultiplicationTable {
public static void main(String[] args) {
int tableOf = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(tableOf + ” x ” + i + ” = ” + (tableOf * i));
}
}
}
- WAP to prints the name of the month based on the provided month variable.
public class MonthSwitch {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1:
System.out.println(“January”);
break;
case 2:
System.out.println(“February”);
break;
case 3:
System.out.println(“March”);
break;
case 4:
System.out.println(“April”);
break;
case 5:
System.out.println(“May”);
break;
case 6:
System.out.println(“June”);
break;
case 7:
System.out.println(“July”);
break;
case 8:
System.out.println(“August”);
break;
case 9:
System.out.println(“September”);
break;
case 10:
System.out.println(“October”);
break;
case 11:
System.out.println(“November”);
break;
case 12:
System.out.println(“December”);
break;
default:
System.out.println(“Invalid month”);
}
}
}
Output:
August
- WAP to performs a basic mathematical operation based on the provided operator variable.
public class CalculatorSwitch {
public static void main(String[] args) {
int num1 = 10;
int num2 = 5;
char operator = ‘*’;
switch (operator) {
case ‘+’:
System.out.println(“Sum: ” + (num1 + num2));
break;
case ‘-‘:
System.out.println(“Difference: ” + (num1 – num2));
break;
case ‘*’:
System.out.println(“Product: ” + (num1 * num2));
break;
case ‘/’:
if (num2 != 0) {
System.out.println(“Quotient: ” + (num1 / num2));
} else {
System.out.println(“Cannot divide by zero”);
}
break;
default:
System.out.println(“Invalid operator”);
}
}
}
Output:
10
Constructor Programs:
- Write a Java program demonstrates the use of a default constructor.
public class DefaultConstructorExample {
public static void main(String[] args) {
// Creating an object of the class
MyClass obj = new MyClass();
obj.displayMessage();
}
}
class MyClass {
// Default Constructor
public MyClass() {
System.out.println(“Default Constructor called.”);
}
public void displayMessage() {
System.out.println(“Hello from MyClass!”);
}
}
- Write a java program to demonstrate of Parametrized Constructor
public class ConstructorOverloadingExample {
public static void main(String[] args) {
// Creating objects with different constructors
Student student1 = new Student();
Student student2 = new Student(“Alice”);
Student student3 = new Student(“Bob”, 20);
student1.displayDetails();
student2.displayDetails();
student3.displayDetails();
}
}
class Student {
String name;
int age;
// Default Constructor
public Student() {
name = “Unknown”;
age = 0;
}
// Parameterized Constructor with one parameter
public Student(String n) {
name = n;
age = 0;
}
// Parameterized Constructor with two parameters
public Student(String n, int a) {
name = n;
age = a;
}
public void displayDetails() {
System.out.println(“Name: ” + name);
System.out.println(“Age: ” + age);
System.out.println(“————“);
}
}
- Write a Java Program to demonstrate Constructor Overloading
public class ConstructorOverloadingExample {
public static void main(String[] args) {
// Creating objects with different constructors
Student student1 = new Student();
Student student2 = new Student(“Alice”);
Student student3 = new Student(“Bob”, 20);
student1.displayDetails();
student2.displayDetails();
student3.displayDetails();
}
}
class Student {
String name;
int age;
// Default Constructor
public Student() {
name = “Unknown”;
age = 0;
}
// Parameterized Constructor with one parameter
public Student(String n) {
name = n;
age = 0;
}
// Parameterized Constructor with two parameters
public Student(String n, int a) {
name = n;
age = a;
}
public void displayDetails() {
System.out.println(“Name: ” + name);
System.out.println(“Age: ” + age);
System.out.println(“————“);
}
}
OOPS Java Programs:
- Write a java program demonstrates the basic concepts of classes and objects by defining a Car class and creating instances of it.
// Class definition
class Car {
// Attributes
String brand;
String model;
int year;
// Method to display car details
void displayDetails() {
System.out.println(“Brand: ” + brand);
System.out.println(“Model: ” + model);
System.out.println(“Year: ” + year);
}
}
// Main class
public class CarExample {
public static void main(String[] args) {
// Creating objects of the class
Car car1 = new Car();
Car car2 = new Car();
// Setting values for car1
car1.brand = “Toyota”;
car1.model = “Camry”;
car1.year = 2022;
// Setting values for car2
car2.brand = “Honda”;
car2.model = “Civic”;
car2.year = 2021;
// Displaying details of both cars
car1.displayDetails();
System.out.println(“——————“);
car2.displayDetails();
}
}
Output:
Brand: Toyota
Model: Camry
Year: 2022
- Write a Java program demonstrates inheritance
// Base class
class Animal {
void eat() {
System.out.println(“Animal is eating.”);
}
}
// Derived class (subclass)
class Dog extends Animal {
void bark() {
System.out.println(“Dog is barking.”);
}
}
public class InheritanceDemo {
public static void main(String[] args) {
// Creating an object of the subclass
Dog myDog = new Dog();
// Accessing methods from both base and derived classes
myDog.eat();
myDog.bark();
}
}
Output:
Animal is eating.
Dog is barking.
- Write a java program to demonstrate the encapsulation
// Encapsulated class
class Student {
// Private fields
private String name;
private int age;
// Public methods for accessing and modifying private fields
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
public int getAge() {
return age;
}
public void setAge(int a) {
if (a > 0) {
age = a;
}
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
// Creating an object of the encapsulated class
Student myStudent = new Student();
// Accessing and modifying private fields using public methods
myStudent.setName(“Alice”);
myStudent.setAge(20);
// Retrieving information using public methods
System.out.println(“Name: ” + myStudent.getName());
System.out.println(“Age: ” + myStudent.getAge());
}
}
Output:
Name: Alice
Age: 20
- Write a java program of runtime polymorphism using method overriding
// Base class
class Animal {
// Method to make a sound
public void makeSound() {
System.out.println(“Some generic sound”);
}
}
// Derived class 1
class Dog extends Animal {
// Overriding the makeSound method
@Override
public void makeSound() {
System.out.println(“Bark bark!”);
}
}
// Derived class 2
class Cat extends Animal {
// Overriding the makeSound method
@Override
public void makeSound() {
System.out.println(“Meow meow!”);
}
}
public class PolymorphismExample {
public static void main(String[] args) {
// Creating objects of different classes
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
// Calling the makeSound method on different objects
myAnimal.makeSound(); // Output: Some generic sound
myDog.makeSound(); // Output: Bark bark!
myCat.makeSound(); // Output: Meow meow!
}
}
Output:
Some generic sound
Bark bark!
Meow meow!
Arrays Programs:
- Write a java program calculates the sum and average of elements in an array.
public class SumAndAverage {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
int sum = 0;
// Calculating sum
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println(“Sum: ” + sum);
System.out.println(“Average: ” + average);
}
}
Output:
Sum: 75
Average: 15.0
- Java program finds the maximum and minimum values in an array.
public class MaxMinInArray {
public static void main(String[] args) {
int[] numbers = {12, 5, 8, 15, 2};
int max = numbers[0];
int min = numbers[0];
// Finding maximum and minimum
for (int num : numbers) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
System.out.println(“Maximum: ” + max);
System.out.println(“Minimum: ” + min);
}
}
Output:
Maximum: 15
Minimum: 2
- Java program demonstrates how to copy elements from one array to another.
public class ArrayCopyExample {
public static void main(String[] args) {
int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = new int[sourceArray.length];
// Copying array elements
for (int i = 0; i < sourceArray.length; i++) {
destinationArray[i] = sourceArray[i];
}
// Displaying the copied array
System.out.print(“Copied Array: “);
for (int num : destinationArray) {
System.out.print(num + ” “);
}
}
}
Output:
Copied Array: 1 2 3 4 5
- Java program performs a linear search to find a target element in an array.
public class LinearSearch {
public static void main(String[] args) {
int[] numbers = {4, 8, 2, 10, 5};
int target = 10;
boolean found = false;
// Linear search
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
found = true;
break;
}
}
if (found) {
System.out.println(“Element ” + target + ” found in the array.”);
} else {
System.out.println(“Element ” + target + ” not found in the array.”);
}
}
}
Output:
Element 10 found in the array.
- Java program implements the Bubble Sort algorithm to sort an array.
public class BubbleSort {
public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 5, 6};
// Bubble sort
for (int i = 0; i < numbers.length – 1; i++) {
for (int j = 0; j < numbers.length – i – 1; j++) {
if (numbers[j] > numbers[j + 1]) {
// Swap if needed
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
// Displaying the sorted array
System.out.print(“Sorted Array: “);
for (int num : numbers) {
System.out.print(num + ” “);
}
}
}
Output:
Sorted Array: 1 2 5 5 6 9
- WAP to find the Duplicate Numbers in Array?
import java.util.Arrays;
public class FindDuplicate {
public static int findDuplicate(int[] nums) {
// Step 1: Sort the array
Arrays.sort(nums);
// Step 2: Check for adjacent elements
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i – 1]) {
// Found the duplicate
return nums[i];
}
}
// No duplicate found
return -1; // or throw an exception, depending on your requirements
}
public static void main(String[] args) {
// Example usage
int[] nums = {3, 1, 3, 4, 2}; // Replace this with your array
int duplicate = findDuplicate(nums);
System.out.println(“The duplicate number is: ” + duplicate);
}
}
Explanation:
Sort the Array:
- Use Arrays.sort(nums) to sort the array in ascending order.
Check for Adjacent Elements:
- Iterate through the sorted array.
- If you find two adjacent elements that are equal, you’ve found the duplicate.
Return the Duplicate:
- Return the duplicate number.
- WAP to find the Missing Number in an Array?
public class FindMissingNumber {
public static int findMissingNumber(int[] nums) {
// Step 1: Calculate the expected sum of first n natural numbers
int n = nums.length + 1; // n is the size of the array + 1 (since one number is missing)
int expectedSum = n * (n + 1) / 2;
// Step 2: Calculate the actual sum of the elements in the array
int actualSum = 0;
for (int num : nums) {
actualSum += num;
}
// Step 3: Return the missing number
return expectedSum – actualSum;
}
public static void main(String[] args) {
// Example usage
int[] nums = {3, 0, 1}; // Replace this with your array
int missingNumber = findMissingNumber(nums);
System.out.println(“The missing number is: ” + missingNumber);
}
}
Explanation:
Calculate the Expected Sum:
- Use the formula n * (n + 1) / 2 to calculate the expected sum of the first n natural numbers, where n is the size of the array + 1.
Calculate the Actual Sum:
- Iterate through the array and calculate the sum of its elements.
Return the Missing Number:
- Subtract the actual sum from the expected sum to find the missing number.
- WAP to find String Palindrome without using built in function?
public class ReverseString {
public static String reverseStringIterative(String input) {
// Step 1: Convert the string to a char array
char[] charArray = input.toCharArray();
// Step 2: Use two pointers to swap characters from the beginning and end
int start = 0;
int end = charArray.length – 1;
while (start < end) {
// Swap characters
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
// Move pointers towards the center
start++;
end–;
}
// Step 3: Convert the char array back to a string
return new String(charArray);
}
public static void main(String[] args) {
// Example usage
String input = “Hello, World!”;
String reversedString = reverseStringIterative(input);
System.out.println(“Original String: ” + input);
System.out.println(“Reversed String: ” + reversedString);
}
}
Explanation:
Convert to Char Array:
- Convert the input string to a char array using toCharArray().
Use Two Pointers to Swap:
- Initialize two pointers, start at the beginning of the array and end at the end.
- Swap the characters at the start and end positions and move the pointers towards the center until they meet.
Convert Back to String:
- Convert the modified char array back to a string using the String constructor.
Example Usage:
- In the main method, an example string “Hello, World!” is used.
- The reversed string is then printed to the console.
- How to find Largest and Smallest numbers in an Array?
public class FindLargestSmallest {
public static void main(String[] args) {
int[] numbers = {55, 32, 45, 98, 82, 11, 9, 39, 50};
int largest = numbers[0];
int smallest = numbers[0];
for (int number : numbers) {
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}
System.out.println(“Largest Number: ” + largest);
System.out.println(“Smallest Number: ” + smallest);
}
}
Recursive Approach:
public class FindLargestSmallestRecursive {
public static void findLargestSmallest(int[] arr, int start, int largest, int smallest) {
if (start == arr.length) {
System.out.println(“Largest Number: ” + largest);
System.out.println(“Smallest Number: ” + smallest);
return;
}
if (arr[start] > largest) {
largest = arr[start];
}
if (arr[start] < smallest) {
smallest = arr[start];
}
findLargestSmallest(arr, start + 1, largest, smallest);
}
public static void main(String[] args) {
int[] numbers = {55, 32, 45, 98, 82, 11, 9, 39, 50};
findLargestSmallest(numbers, 0, numbers[0], numbers[0]);
}
}
Using sort:
public class FindLargestSmallestSorting {
public static void main(String[] args) {
int[] numbers = {55, 32, 45, 98, 82, 11, 9, 39, 50};
Arrays.sort(numbers);
System.out.println(“Largest Number: ” + numbers[numbers.length – 1]);
System.out.println(“Smallest Number: ” + numbers[0]);
}
}
- Java program removes duplicates from an array.
import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 2, 4, 10, 12, 6};
int length = numbers.length;
// Removing duplicates
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (numbers[i] == numbers[j]) {
// Shift elements to the left
for (int k = j; k < length – 1; k++) {
numbers[k] = numbers[k + 1];
}
length–;
j–;
}
}
}
// Displaying the array without duplicates
System.out.println(“Array without duplicates: ” + Arrays.toString(Arrays.copyOf(numbers, length)));
}
}
Output:
2,4,6,8,10,12
- Java program calculates the transpose of a matrix.
public class MatrixTranspose {
public static void main(String[] args) {
int[][] originalMatrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] transposeMatrix = new int[3][3];
// Transposing the matrix
for (int i = 0; i < originalMatrix.length; i++) {
for (int j = 0; j < originalMatrix[i].length; j++) {
transposeMatrix[j][i] = originalMatrix[i][j];
}
}
// Displaying the transpose matrix
for (int[] row : transposeMatrix) {
for (int num : row) {
System.out.print(num + ” “);
}
System.out.println();
}
}
}
Output:
1 4 7
2 5 8
3 6 9
- java program performs matrix addition.
public class MatrixAddition {
public static void main(String[] args) {
int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int[][] result = new int[3][3];
// Matrix addition
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Displaying the result matrix
for (int[] row : result) {
for (int num : row) {
System.out.print(num + ” “);
}
System.out.println();
}
}
}
Output:
10 10 10
10 10 10
10 10 10
- Java Program to perform MergeSort on an array
public class MergeSort {
public static void main(String[] args) {
int[] array = {38, 27, 43, 3, 9, 82, 10};
mergeSort(array, 0, array.length – 1);
System.out.println(“Sorted Array: ” + Arrays.toString(array));
}
static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
static void merge(int[] arr, int left, int mid, int right) {
int n1 = mid – left + 1;
int n2 = right – mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
// Copy data to temporary arrays
for (int i = 0; i < n1; i++) {
leftArray[i] = arr[left + i];
}
for (int j = 0; j < n2; j++) {
rightArray[j] = arr[mid + 1 + j];
}
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}
// Copy remaining elements of leftArray, if any
while (i < n1) {
arr[k] = leftArray[i];
i++;
k++;
}
// Copy remaining elements of rightArray, if any
while (j < n2) {
arr[k] = rightArray[j];
j++;
k++;
}
}
}
Output:
Sorted Array: [3, 9, 10, 27, 38, 43, 82]
- Java Program implements binary search on a sorted array.
public class BinarySearch {
public static void main(String[] args) {
int[] sortedArray = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int target = 12;
int result = binarySearch(sortedArray, target);
if (result != -1) {
System.out.println(“Element ” + target + ” found at index ” + result);
} else {
System.out.println(“Element ” + target + ” not found in the array.”);
}
}
static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length – 1;
while (left <= right) {
int mid = left + (right – left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid – 1;
}
}
return -1;
}
}
Output:
Element 12 found at index 5
- Check if two arrays contains same elements?
import java.util.Arrays;
public class CheckSameElements {
public static boolean areArraysEqual(int[] arr1, int[] arr2) {
// Step 1: Sort both arrays
Arrays.sort(arr1);
Arrays.sort(arr2);
// Step 2: Compare each element of the sorted arrays
return Arrays.equals(arr1, arr2);
}
public static void main(String[] args) {
// Example usage
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {5, 4, 3, 2, 1};
boolean result = areArraysEqual(array1, array2);
if (result) {
System.out.println(“The arrays contain the same elements.”);
} else {
System.out.println(“The arrays do not contain the same elements.”);
}
}
}
Output:
The arrays contain the same elements.
Explanation:
Sort both Arrays:
- Use Arrays.sort to sort both arrays.
Compare Elements:
- Use Arrays.equals to compare the sorted arrays element by element.
Example Usage:
- In the main method, two example arrays, {1, 2, 3, 4, 5} and {5, 4, 3, 2, 1}, are used.
- The program then prints whether the arrays contain the same elements.
String java Programs:
- Java program to extract characters:
public class ExtractCharacters {
public static void main(String[] args) {
String str = “Hello”;
char firstChar = str.charAt(0);
char lastChar = str.charAt(str.length() – 1);
System.out.println(“First character: ” + firstChar);
System.out.println(“Last character: ” + lastChar);
}
}
**Output:**
First character: H
Last character: o
- java program for checking equality
public class StringEquality {
public static void main(String[] args) {
String str1 = “Hello”;
String str2 = “Hello”;
String str3 = new String(“Hello”);
boolean eq1 = str1 == str2; // true (same reference)
boolean eq2 = str1 == str3; // false (different references)
boolean eq3 = str1.equals(str3); // true (content equality)
System.out.println(“eq1: ” + eq1);
System.out.println(“eq2: ” + eq2);
System.out.println(“eq3: ” + eq3);
}
}
**Output:**
eq1: true
eq2: false
eq3: true
- Java program to spilt the given string
public class SplitString {
public static void main(String[] args) {
String sentence = “This is a sentence with multiple words.”;
String[] words = sentence.split(” “);
for (String word : words) {
System.out.println(word);
}
}
}
**Output:**
This
is
a
sentence
with
multiple
words.
- Java program how to use regrular expression in String
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexExample {
public static void main(String[] args) {
String email = “john.doe@example.com”;
Pattern pattern = Pattern.compile(“.+@.+\\..+”); // Pattern for email
Matcher matcher = pattern.matcher(email);
if (matcher.matches()) {
System.out.println(“Valid email”);
} else {
System.out.println(“Invalid email”);
}
}
}
**Output:**
Valid email
- Java program to reverse words in the given string
public class ReverseWords {
public static void main(String[] args) {
String sentence = “This is a Java string example”;
String[] words = sentence.split(” “);
StringBuilder reversedSentence = new StringBuilder();
for (int i = words.length – 1; i >= 0; i–) {
reversedSentence.append(words[i]).append(” “);
}
System.out.println(“Reversed sentence: ” + reversedSentence.toString().trim());
}
}
**Output:**
Reversed sentence: example string Java a is This
- Java program to Parsing a String into an Integer or Double
public class NumberParsing {
public static void main(String[] args) {
String numStr = “12345”;
int numInt = Integer.parseInt(numStr);
System.out.println(“Integer value: ” + numInt);
String decimalStr = “3.14159”;
double numDouble = Double.parseDouble(decimalStr);
System.out.println(“Double value: ” + numDouble);
}
}
**Output:**
Integer value: 12345
Double value: 3.14159
- Find the first non-repeated character in a string: Given a string, you need to find the first non-repeated character in it. For example, if the input is “aabccdeef”, the output should be “d”.
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeatedCharacter {
public static char findFirstNonRepeatedChar(String input) {
// Create a LinkedHashMap to store character frequencies in insertion order
Map<Character, Integer> charFrequencyMap = new LinkedHashMap<>();
// Iterate through the string to calculate character frequencies
for (char c : input.toCharArray()) {
charFrequencyMap.put(c, charFrequencyMap.getOrDefault(c, 0) + 1);
}
// Iterate through the map to find the first non-repeated character
for (Map.Entry<Character, Integer> entry : charFrequencyMap.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
// If no non-repeated character is found, return a special character or throw an exception
return ‘\0’;
}
public static void main(String[] args) {
// Example usage
String input = “aabccdeef”;
char firstNonRepeatedChar = findFirstNonRepeatedChar(input);
if (firstNonRepeatedChar != ‘\0’) {
System.out.println(“First non-repeated character: ” + firstNonRepeatedChar);
} else {
System.out.println(“No non-repeated character found.”);
}
}
}
Explanation:
LinkedHashMap for Insertion Order:
- Use a LinkedHashMap (charFrequencyMap) to store character frequencies while maintaining the order of insertion.
Calculate Character Frequencies:
- Iterate through the input string to calculate the frequency of each character and store it in the charFrequencyMap.
Find the First Non-Repeated Character:
- Iterate through the map entries to find the first character with a frequency of 1.
Example Usage:
- In the main method, an example string “aabccdeef” is used.
- The first non-repeated character is then printed to the console.
- Check if a string contains only digits: Given a string, you need to check if it contains only digits. For example, “123” contains only digits, while “12A3” does not.
using Regular Expressions:
public class CheckDigitsInString {
public static boolean containsOnlyDigits(String input) {
// Use the matches method with the regular expression \d+ to check for digits
return input.matches(“\\d+”);
}
public static void main(String[] args) {
// Example usage
String str1 = “123”;
String str2 = “12A3”;
System.out.println(str1 + ” contains only digits: ” + containsOnlyDigits(str1));
System.out.println(str2 + ” contains only digits: ” + containsOnlyDigits(str2));
}
}
Explanation:
Regular Expression:
- The regular expression \d+ matches one or more digits.
matches Method:
- The matches method of the String class checks if the entire string matches the specified regular expression.
Example Usage:
- In the main method, two example strings, “123” and “12A3,” are used.
- The program then prints whether each string contains only digits.
2nd Approach:
public class CheckDigits {
public static boolean isAllDigits(String text) {
// Iterate through each character in the string:
for (int i = 0; i < text.length(); i++) {
// Check if the current character is not a digit:
if (!Character.isDigit(text.charAt(i))) {
// If a non-digit character is found, return false:
return false;
}
}
// If all characters are digits, return true:
return true;
}
public static void main(String[] args) {
String text1 = “12345”;
String text2 = “123AB5”;
String text3 = “”; // Empty string
System.out.println(“String ‘” + text1 + “‘ contains only digits: ” + isAllDigits(text1));
System.out.println(“String ‘” + text2 + “‘ contains only digits: ” + isAllDigits(text2));
System.out.println(“String ‘” + text3 + “‘ contains only digits: ” + isAllDigits(text3));
}
}
Output:
String ‘12345’ contains only digits: true
String ‘123AB5’ contains only digits: false
String ” contains only digits: true
Explanation:
isAllDigits Function:
- Takes a string text as input.
- Uses a for loop to iterate through each character in the string.
- Inside the loop, uses Character.isDigit(text.charAt(i)) to check if the current character is a digit.
- If any character is not a digit, it returns false.
- If the loop completes without finding any non-digit characters, it returns true.
main Method:
- Creates three test strings: text1 (all digits), text2 (mixed with letters), and text3 (empty string).
- Calls the isAllDigits function for each string and prints the results.
- Capitalize the first letter of each word in a string: Given a string, you need to capitalize the first letter of each word in it. For example, if the input is “hello world”, the output should be “Hello World”.
public class CapitalizeFirstLetter {
public static String capitalizeFirstLetter(String input) {
// Split the string into words
String[] words = input.split(“\\s+”); // “\\s+” matches one or more whitespace characters
// Capitalize the first letter of each word
for (int i = 0; i < words.length; i++) {
if (!words[i].isEmpty()) { // Check if the word is not empty
words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase();
}
}
// Join the words back into a single string
return String.join(” “, words);
}
public static void main(String[] args) {
// Example usage
String input = “hello world”;
String capitalizedString = capitalizeFirstLetter(input);
System.out.println(“Original string: ” + input);
System.out.println(“Capitalized string: ” + capitalizedString);
}
}
Output:
Original string: hello world
Capitalized string: Hello World
Explanation:
Split into Words:
- Use the split method to split the input string into an array of words. The regular expression “\s+” matches one or more whitespace characters.
Capitalize First Letter:
- Iterate through the array of words and capitalize the first letter of each word using substring. Convert the rest of the letters to lowercase.
Join Back into a String:
- Use String.join to join the words back into a single string, separating them with a space.
Example Usage:
- In the main method, an example string “hello world” is used.
- The program then prints the original string and the capitalized string.
Exception Handling Programs:
- java program to Handle ArithmeticException
public class DivideByZero {
public static void main(String[] args) {
int num1 = 10, num2 = 0;
try {
int result = num1 / num2;
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Error: Division by zero”);
}
}
}
**Output:**
Error: Division by zero
- Java program to handle ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBounds {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[5]); // Attempting to access an invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Error: Array index out of bounds”);
}
}
}
**Output:**
Error: Array index out of bounds
- Java Program to handle NullPointerException
public class NullPointerExample {
public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length()); // Attempting to access a null object
} catch (NullPointerException e) {
System.out.println(“Error: Null pointer exception”);
}
}
}
**Output:**
Error: Null pointer exception
- Java program to use Multiple Catch Blocks
public class MultipleCatches {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
int num1 = 10, num2 = 0;
try {
System.out.println(numbers[5]);
int result = num1 / num2;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Array index out of bounds”);
} catch (ArithmeticException e) {
System.out.println(“Division by zero”);
} finally {
System.out.println(“This block always executes”);
}
}
}
**Output:**
Array index out of bounds
This block always executes
- Java Program Throwing a Custom Exception
class NegativeAgeException extends Exception {
public NegativeAgeException(String message) {
super(message);
}
}
public class CustomException {
public static void main(String[] args) {
int age = -25;
try {
if (age < 0) {
throw new NegativeAgeException(“Age cannot be negative”);
}
System.out.println(“Age is valid”);
} catch (NegativeAgeException e) {
System.out.println(e.getMessage());
}
}
}
**Output:**
Age cannot be negative
Collection Framework Programs
- Java Program on ArrayList
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add(“Red”);
colors.add(“Green”);
colors.add(“Blue”);
System.out.println(“Original list: ” + colors);
// Accessing elements
String firstColor = colors.get(0);
System.out.println(“First color: ” + firstColor);
// Removing an element
colors.remove(1);
System.out.println(“List after removing: ” + colors);
}
}
Output:
Original list: [Red, Green, Blue]
First color: Red
List after removing: [Red, Blue]
- Java Program to use LinkedList:
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.addFirst(5); // Add at the beginning
numbers.addLast(15); // Add at the end
System.out.println(“Linked list: ” + numbers);
// Retrieving the first and last elements
int first = numbers.getFirst();
int last = numbers.getLast();
System.out.println(“First: ” + first + “, Last: ” + last);
}
}
Output:
Linked list: [5, 10, 15]
First: 5, Last: 15
- Java program to use HashSet
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> names = new HashSet<>();
names.add(“Alice”);
names.add(“Bob”);
names.add(“Alice”); // Duplicate, won’t be added
System.out.println(“Unique names: ” + names);
// Checking if a name exists
boolean containsJohn = names.contains(“John”);
System.out.println(“Contains John: ” + containsJohn);
}
}
Output:
Unique names: [Alice, Bob]
Contains John: false
- Java program to use TreeSet:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(4);
numbers.add(2);
numbers.add(7);
System.out.println(“Sorted numbers: ” + numbers);
// Getting the first and last elements
int first = numbers.first();
int last = numbers.last();
System.out.println(“First: ” + first + “, Last: ” + last);
}
}
Output:
Sorted numbers: [2, 4, 7]
First: 2, Last: 7
- Java program to use HashMap
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();
scores.put(“Alice”, 95);
scores.put(“Bob”, 80);
System.out.println(“Scores: ” + scores);
// Retrieving a value
int aliceScore = scores.get(“Alice”);
System.out.println(“Alice’s score: ” + aliceScore);
}
}
Output:
Scores: {Alice=95, Bob=80}
Alice’s score: 95
- Java program to use TreeMap
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, String> countries = new TreeMap<>();
countries.put(“US”, “United States”);
countries.put(“UK”, “United Kingdom”);
System.out.println(“Sorted countries: ” + countries);
// Getting the first key-value pair
String firstEntry = countries.firstEntry().toString();
System.out.println(“First entry: ” + firstEntry);
}
}
Output:
Sorted countries: {UK=United Kingdom, US=United States}
First entry: UK=United Kingdom
Multiple Threading Programs:
- Write a Java program demonstrates the synchronization of two threads (EvenThread and OddThread) to print even and odd numbers alternatively.
class NumberPrinter implements Runnable {
private static final Object lock = new Object();
private static int count = 1;
@Override
public void run() {
synchronized (lock) {
while (count <= 10) {
if ((count % 2 == 0 && Thread.currentThread().getName().equals(“EvenThread”))
|| (count % 2 != 0 && Thread.currentThread().getName().equals(“OddThread”))) {
System.out.println(Thread.currentThread().getName() + “: ” + count++);
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class EvenOddNumberPrinter {
public static void main(String[] args) {
NumberPrinter printer = new NumberPrinter();
Thread evenThread = new Thread(printer, “EvenThread”);
Thread oddThread = new Thread(printer, “OddThread”);
evenThread.start();
oddThread.start();
}
}
output:
EvenThread: 1
OddThread: 2
EvenThread: 3
OddThread: 4
EvenThread: 5
OddThread: 6
EvenThread: 7
OddThread: 8
EvenThread: 9
OddThread: 10
- In ths Java Program each thread has its own copy of a variable stored in ThreadLocal. Changes made by one thread do not affect the value seen by other threads.
public class ThreadLocalExample {
private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
Runnable task = () -> {
int value = (int) (Math.random() * 100);
threadLocal.set(value);
System.out.println(Thread.currentThread().getName() + ” – Local value: ” + threadLocal.get());
};
Thread thread1 = new Thread(task, “Thread-1”);
Thread thread2 = new Thread(task, “Thread-2”);
thread1.start();
thread2.start();
}
}
Output:
Thread-1 – Local value: 16
Thread-2 – Local value: 71
In this Java Program two threads (Thread-1 and Thread-2) attempt to acquire locks on two resources in reverse order, leading to a deadlock scenario.
public class DeadlockExample {
static class Resource {
synchronized void method1(Resource r) {
System.out.println(Thread.currentThread().getName() + ” acquired lock on Resource 1″);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.method2(this);
System.out.println(Thread.currentThread().getName() + ” released lock on Resource 1″);
}
synchronized void method2(Resource r) {
System.out.println(Thread.currentThread().getName() + ” acquired lock on Resource 2″);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.method1(this);
System.out.println(Thread.currentThread().getName() + ” released lock on Resource 2″);
}
}
public static void main(String[] args) {
final Resource resource1 = new Resource();
final Resource resource2 = new Resource();
Thread thread1 = new Thread(() -> resource1.method1(resource2), “Thread-1”);
Thread thread2 = new Thread(() -> resource2.method1(resource1), “Thread-2”);
thread1.start();
thread2.start();
}
}
Output:
Thread-1 acquired lock on Resource 1
Thread-2 acquired lock on Resource 2
Multiple Threading Programs:
Write a Java program demonstrates the synchronization of two threads (EvenThread and OddThread) to print even and odd numbers alternatively.
class NumberPrinter implements Runnable {
private static final Object lock = new Object();
private static int count = 1;
@Override
public void run() {
synchronized (lock) {
while (count <= 10) {
if ((count % 2 == 0 && Thread.currentThread().getName().equals(“EvenThread”))
|| (count % 2 != 0 && Thread.currentThread().getName().equals(“OddThread”))) {
System.out.println(Thread.currentThread().getName() + “: ” + count++);
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class EvenOddNumberPrinter {
public static void main(String[] args) {
NumberPrinter printer = new NumberPrinter();
Thread evenThread = new Thread(printer, “EvenThread”);
Thread oddThread = new Thread(printer, “OddThread”);
evenThread.start();
oddThread.start();
}
}
output:
EvenThread: 1
OddThread: 2
EvenThread: 3
OddThread: 4
EvenThread: 5
OddThread: 6
EvenThread: 7
OddThread: 8
EvenThread: 9
OddThread: 10
In ths Java Program each thread has its own copy of a variable stored in ThreadLocal. Changes made by one thread do not affect the value seen by other threads.
public class ThreadLocalExample {
private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
Runnable task = () -> {
int value = (int) (Math.random() * 100);
threadLocal.set(value);
System.out.println(Thread.currentThread().getName() + ” – Local value: ” + threadLocal.get());
};
Thread thread1 = new Thread(task, “Thread-1”);
Thread thread2 = new Thread(task, “Thread-2”);
thread1.start();
thread2.start();
}
}
Output:
Thread-1 – Local value: 16
Thread-2 – Local value: 71
- In this Java Program two threads (Thread-1 and Thread-2) attempt to acquire locks on two resources in reverse order, leading to a deadlock scenario.
public class DeadlockExample {
static class Resource {
synchronized void method1(Resource r) {
System.out.println(Thread.currentThread().getName() + ” acquired lock on Resource 1″);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.method2(this);
System.out.println(Thread.currentThread().getName() + ” released lock on Resource 1″);
}
synchronized void method2(Resource r) {
System.out.println(Thread.currentThread().getName() + ” acquired lock on Resource 2″);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.method1(this);
System.out.println(Thread.currentThread().getName() + ” released lock on Resource 2″);
}
}
public static void main(String[] args) {
final Resource resource1 = new Resource();
final Resource resource2 = new Resource();
Thread thread1 = new Thread(() -> resource1.method1(resource2), “Thread-1”);
Thread thread2 = new Thread(() -> resource2.method1(resource1), “Thread-2”);
thread1.start();
thread2.start();
}
}
Output:
Thread-1 acquired lock on Resource 1
Thread-2 acquired lock on Resource 2
Start Pattern Programs:
- Java program to Print a Pyramid pattern
public class StarPattern3 {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows – i; j++) {
System.out.print(” “);
}
for (int k = 1; k <= 2 * i – 1; k++) {
System.out.print(“* “);
}
System.out.println();
}
}
}
Output:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
- Java Program to Print an Inverted Right-Angled Triangle
public class StarPattern2 {
public static void main(String[] args) {
int rows = 5;
for (int i = rows; i >= 1; i–) {
for (int j = 1; j <= i; j++) {
System.out.print(“* “);
}
System.out.println();
}
}
}
Output:
* * * * *
* * * *
* * *
* *
*
- Java Program to Print a Right-Angled Triangle
public class StarPattern1 {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(“* “);
}
System.out.println();
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
- Java Program to Print a Diamond Pattern
public class StarPattern5 {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows – i; j++) {
System.out.print(” “);
}
for (int k = 1; k <= 2 * i – 1; k++) {
System.out.print(“* “);
}
System.out.println();
}
for (int i = rows – 1; i >= 1; i–) {
for (int j = 1; j <= rows – i; j++) {
System.out.print(” “);
}
for (int k = 1; k <= 2 * i – 1; k++) {
System.out.print(“* “);
}
System.out.println();
}
}
}
Output:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
- Java program to Print a Hollow Pyramid
public class StarPattern4 {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows – i; j++) {
System.out.print(” “);
}
for (int k = 1; k <= 2 * i – 1; k++) {
if (k == 1 || k == 2 * i – 1 || i == rows) {
System.out.print(“* “);
} else {
System.out.print(” “);
}
}
System.out.println();
}
}
}
Output:
*
* *
* *
* *
* * * * * * * * *
Files Programs:
- Java program to Reading from a Text File
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFromFile {
public static void main(String[] args) {
String fileName = “sample.txt”;
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Content of ‘simple.txt’ file:
Hello, this is a sample text file.
It contains multiple lines.
We will read and print each line.
Expected Output:
Hello, this is a sample text file.
It contains multiple lines.
We will read and print each line.
- Java Program to Write a Text file
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
String fileName = “output.txt”;
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
bw.write(“This is a line written to the file.”);
bw.newLine();
bw.write(“Another line.”);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Content of ‘Output.txt’:
This is a line written to the file.
Another line.
- Java program to reverse a linked list
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
// Method to reverse the linked list
public void reverse() {
Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next; // Save the next node
current.next = prev; // Reverse the link
// Move to the next nodes
prev = current;
current = next;
}
head = prev; // Update the head to the last node (previous first node)
}
// Method to print the linked list
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + ” “);
temp = temp.next;
}
System.out.println();
}
// Method to add a new node to the linked list
public void addNode(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
}
public class ReverseLinkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.addNode(4);
System.out.println(“Original Linked List:”);
list.printList();
list.reverse();
System.out.println(“Reversed Linked List:”);
list.printList();
}
}
Output:
Original Linked List:
4 3 2 1
Reversed Linked List:
1 2 3 4
- Java program to Find the maximum subarray sum.
public class MaxSubarraySum {
public static int maxSubarraySum(int[] nums) {
int currentSum = nums[0];
int maxSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(“Original Array: ” + arrayToString(nums));
int result = maxSubarraySum(nums);
System.out.println(“Maximum Subarray Sum: ” + result);
}
private static String arrayToString(int[] nums) {
StringBuilder sb = new StringBuilder(“[“);
for (int i = 0; i < nums.length; i++) {
sb.append(nums[i]);
if (i < nums.length – 1) {
sb.append(“, “);
}
}
sb.append(“]”);
return sb.toString();
}
}
Output:
Original Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Maximum Subarray Sum: 6
Explanation:
The maxSubarraySum method uses Kadane’s algorithm to find the maximum subarray sum.
It initializes currentSum and maxSum with the first element of the array.
It then iterates through the array, updating currentSum to either the current element or the sum of the current element and the previous currentSum.
The maxSum is updated whenever a new maximum subarray sum is found.