Top Java Programs and How to Solve Them: Job Interview Guide (Part 1)

Throughout this page, we will explore a curated collection of top Java programs commonly encountered in job interviews. Whether you are a beginner looking to enhance your Java skills or an experienced developer preparing for technical interviews, these Java programs will serve as an excellent resource to strengthen your understanding of core programming concepts and showcase your problem-solving abilities.

So, let’s dive into the world of Java programming and explore these top Java programs that will expand your knowledge and enhance your problem-solving capabilities. Whether you are a job seeker, a programming enthusiast, or simply eager to learn, this collection of Java programs is an invaluable resource that will enable you to master the art of programming in Java.

If you’re preparing for a Java job interview, don’t miss our Java Job Interview Questions page. Also, explore Part 2 of our “Top Java Programs and How to Solve Them” for additional code examples.

Fibonacci Series

To begin, let’s create a Java program that generates the Fibonacci series. The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones. For example, the series starts as 0, 1, 1, 2, 3, 5, 8, and so on.

Your task is to write a Java program that takes an integer input from the user and generates the Fibonacci series up to that given number. The program should display the series as output.

1. Ask the user to enter a positive integer.
2. Generate and display the Fibonacci series up to the entered number.

Example

If the user enters 8 as the number of terms, the program should generate the Fibonacci series as follows:

```0, 1, 1, 2, 3, 5, 8, 13
```

Solution 1

To generate the Fibonacci series up to a given number of terms, follow these instructions:

1. Read the number of terms, let’s call it `n`, from the user.
2. Declare three variables `firstTerm`, `secondTerm`, and `nextTerm`, and initialize `firstTerm` to 0 and `secondTerm` to 1.
3. Print `firstTerm` and `secondTerm` as the initial terms of the series.
4. Start a loop from 3 to `n` (inclusive) and perform the following steps:
• Calculate `nextTerm` as the sum of `firstTerm` and `secondTerm`.
• Print `nextTerm`.
• Update `firstTerm` to `secondTerm`.
• Update `secondTerm` to `nextTerm`.
5. Exit the loop.
6. The program has now generated and displayed the Fibonacci series up to `n` terms.
```import java.util.Scanner;

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

System.out.print("Enter the number of terms: ");
int n = input.nextInt();

int firstTerm = 0, secondTerm = 1;

System.out.print("Fibonacci Series: " + firstTerm + ", " + secondTerm);

for (int i = 3; i <= n; i++) {
int nextTerm = firstTerm + secondTerm;
System.out.print(", " + nextTerm);

firstTerm = secondTerm;
secondTerm = nextTerm;
}

input.close();
}
}
```

Solution 2

To generate the Fibonacci series up to a given number, we can define a recursive function that calculates the nth term of the series and utilize a loop to print the series.

1. Define a recursive function, let’s call it `fibonacci`, that takes an integer `n` as a parameter and returns the `n`th term of the Fibonacci series.
2. If `n` is 0 or 1, return `n` as it represents the base cases of the Fibonacci series.
3. Otherwise, recursively call the `fibonacci` function with `n-1` and `n-2` as parameters, and return the sum of the results.
4. In the `main` method, read the number of terms, `n`, from the user.
5. Use a loop to iterate from 0 to `n-1` and print the Fibonacci series by calling the `fibonacci` function for each iteration.
```import java.util.Scanner;

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

System.out.print("Enter the number of terms: ");
int n = input.nextInt();

System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + ", ");
}

input.close();
}

public static int fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
```

Note: Recursive solutions are elegant but may not be as efficient as iterative solutions for larger values of `n` due to the repeated calculations involved.

A Prime Number

In this task, you need to write a Java program that determines whether a given number is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

1. Prompt the user to enter a positive integer.
2. Validate the input to ensure it is a positive integer.
3. Implement the logic to check if the entered number is prime or not.
4. Display an appropriate message to indicate whether the number is prime or not.

Example

If the input is 13, the program should generate the following output:

`13 is a prime number.`

Solution

To solve this task, we will use a simple iterative approach to check whether a number is prime.

1. Read the number, let’s call it `num`, from the user.
2. Initialize a boolean variable `isPrime` to `true`.
3. Start a loop from 2 to the square root of `num` (inclusive) and perform the following steps:
• Check if `num` is divisible by the current loop variable. If it is, set `isPrime` to `false`.
4. After the loop, check the value of `isPrime`:
• If `isPrime` is `true`, it means the number is prime.
• If `isPrime` is `false`, it means the number is not prime.
5. Display an appropriate message to the user based on the value of `isPrime`.
```import java.util.Scanner;

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

System.out.print("Enter a positive integer: ");
int num = input.nextInt();

boolean isPrime = true;

if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}

input.close();
}
}
```

String Palindrome

In this task, you need to write a Java program to check whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and letter case.

1. Ask the user to enter a string.
2. Check if the entered string is a palindrome.
3. Display a message indicating whether the string is a palindrome or not.

Example

If the user enters “madam” as the string, the program should determine that it is a palindrome and display the message: “The string ‘madam’ is a palindrome.”

Solution 1

To solve this task, we will compare characters from both ends of the string to check for symmetry.

1. Read the string, let’s call it `str`, from the user.
2. Remove any spaces and convert the string to lowercase for case-insensitive comparison.
3. Initialize two pointers: `start` pointing to the beginning of the string and `end` pointing to the end of the string.
4. Start a loop while `start` is less than or equal to `end` and perform the following steps:
• Compare the characters at indices `start` and `end`.
• If they are not equal, the string is not a palindrome.
• Move `start` one step forward and `end` one step backward.
5. After the loop, if the loop terminated without finding any unequal characters, the string is a palindrome.
6. Display an appropriate message to the user based on the result.
```import java.util.Scanner;

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

System.out.print("Enter a string: ");
String str = input.nextLine();

// Remove spaces and convert to lowercase
str = str.replaceAll("\\s", "").toLowerCase();

int start = 0;
int end = str.length() - 1;
boolean isPalindrome = true;

while (start <= end) {
if (str.charAt(start) != str.charAt(end)) {
isPalindrome = false;
break;
}
start++;
end--;
}

if (isPalindrome) {
System.out.println("The string '" + str + "' is a palindrome.");
} else {
System.out.println("The string '" + str + "' is not a palindrome.");
}

input.close();
}
}
```

Solution 2

We can also utilize the StringBuilder class to reverse the string and compare it with the original. We will do that according to the following approach:

1. Read the string, let’s call it `str`, from the user.
2. Remove any spaces and convert the string to lowercase for case-insensitive comparison.
3. Create a StringBuilder object and initialize it with the reversed version of `str`.
4. Compare the reversed string obtained from the StringBuilder with the original string.
5. If they are equal, the string is a palindrome. Otherwise, it is not.
6. Display an appropriate message to the user based on the result.
```import java.util.Scanner;

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

System.out.print("Enter a string: ");
String str = input.nextLine();

// Remove spaces and convert to lowercase
str = str.replaceAll("\\s", "").toLowerCase();

StringBuilder reversedStr = new StringBuilder(str).reverse();

boolean isPalindrome = str.equals(reversedStr.toString());

if (isPalindrome) {
System.out.println("The string '" + str + "' is a palindrome.");
} else {
System.out.println("The string '" + str + "' is not a palindrome.");
}

input.close();
}
}
```

Armstrong Number

In this task, you need to write a Java program to check whether a given number is an Armstrong number. An Armstrong number is a number that is equal to the cube of its every digit.

1. Ask the user to enter a positive integer.
2. Check if the entered number is an Armstrong number.
3. Display a message indicating whether the number is an Armstrong number or not.

Example

If the user enters 153 as the number, the program should determine that it is an Armstrong number and display the message: “153 is an Armstrong number.” because 153 = 1 + 125 + 27

Solution

To solve this task, we will extract the digits of the number and calculate the sum of their cubes.

1. Read the number, let’s call it `num`, from the user.
2. Declare variables to store the sum of the cubes of the digits and the original number of digits.
3. Create a copy of the original number to count the number of digits.
4. Use a loop to extract each digit from the number:
• Calculate the remainder of `num` divided by 10 to get the last digit.
• Add the cube of the digit to the sum.
• Divide `num` by 10 to remove the last digit.
• Decrement the count of digits.
5. Check if the sum of the cubes is equal to the original number:
• If they are equal, the number is an Armstrong number.
• If they are not equal, the number is not an Armstrong number.
6. Display an appropriate message to the user based on the result.
```import java.util.Scanner;

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

System.out.print("Enter a positive integer: ");
int num = input.nextInt();

int sum = 0;
int originalNumber = num;
int numberOfDigits = String.valueOf(num).length();

while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, numberOfDigits);
num /= 10;
}

boolean isArmstrong = (sum == originalNumber);

if (isArmstrong) {
System.out.println(originalNumber + " is an Armstrong number.");
} else {
System.out.println(originalNumber + " is not an Armstrong number.");
}

input.close();
}
}
```

Deadlock is a situation in concurrent programming where two or more threads are blocked forever, waiting for each other to release resources. It occurs when each thread holds a resource and waits for another resource that is held by another thread, creating a cyclic dependency. To avoid deadlock in Java, it is important to follow certain practices and utilize synchronization constructs effectively.

Let’s consider a classic example of a deadlock involving two threads and two resources.

```public class DeadlockExample {
private static final Object resource1 = new Object();
private static final Object resource2 = new Object();

public static void main(String[] args) {
synchronized (resource1) {
try {
Thread.sleep(100);  // Introduce a delay to allow the second thread to acquire resource 2
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource2) {
}
}
});

synchronized (resource2) {
synchronized (resource1) {
}
}
});

}
}
```

In this example, we have two threads, `thread1` and `thread2`, both competing for two resources: `resource1` and `resource2`. Each thread acquires one resource and waits for the other resource to be released, leading to a deadlock situation.

Solution

To solve the deadlock in this scenario, we can apply a technique called “resource ordering.” By enforcing a consistent order for acquiring the resources, we can break the circular dependency and avoid deadlock.

To implement resource ordering, we can modify the code as follows:

```public class DeadlockSolution {
private static final Object resource1 = new Object();
private static final Object resource2 = new Object();

public static void main(String[] args) {
synchronized (resource1) {
try {
Thread.sleep(100);  // Introduce a delay to allow the second thread to acquire resource 2
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource2) {
}
}
});

synchronized (resource1) {
synchronized (resource2) {
}
}
});

}
}
```

In this solution, both threads acquire `resource1` first before attempting to acquire `resource2`. This consistent ordering of resource acquisition ensures that no circular dependency is formed, breaking the potential deadlock situation.

By following this modified code structure, you can avoid the deadlock that would have occurred in the initial code example.

Here are some best practices to avoid deadlock in Java:

1. Avoid circular resource dependencies: Ensure that your code does not create a circular dependency between resources. If a thread holds one resource and requires another resource, make sure that the acquisition of resources happens in a consistent order across all threads.
2. Use a proper resource acquisition order: Establish a consistent order for acquiring resources and make sure all threads follow the same order. This can help prevent the formation of resource cycles. If multiple threads require multiple resources, they should always acquire the resources in the same order.
3. Use timeouts with resource acquisition: When acquiring resources, use timeouts to avoid indefinite waiting. If a thread cannot acquire a resource within a specified time, it can release any resources it has acquired and retry later, preventing potential deadlock situations.
4. Avoid nested locks: Minimize the use of nested locks. If a thread holds one lock and needs to acquire another lock, it increases the risk of deadlock. Consider using higher-level synchronization constructs, such as concurrent collections or thread-safe classes, to reduce the need for explicit locking.
5. Release resources in a timely manner: Ensure that acquired resources are released as soon as they are no longer needed. This practice prevents resource hoarding and allows other threads to acquire the resources when necessary.
6. Use thread-safe classes and synchronization: Utilize built-in synchronization mechanisms and thread-safe classes provided by Java, such as synchronized blocks, locks, and concurrent data structures. These constructs help manage concurrent access to shared resources and minimize the chances of deadlock.

Note: Despite following these best practices, deadlock can still occur in complex scenarios. It is important to thoroughly analyze and test your code to identify and resolve any potential deadlock situations.

By incorporating these best practices into your Java code, you can minimize the risk of encountering deadlock situations and promote smoother execution of concurrent programs.

Factorial

In this task, you need to write a Java program to calculate the factorial of a given number. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`.

1. Ask the user to enter a non-negative integer.
2. Calculate the factorial of the entered number.
3. Display the factorial value to the user.

Example

If the user enters 5 as the number, the program should calculate the factorial as 5! = 5 x 4 x 3 x 2 x 1 = 120 and display the message: “The factorial of 5 is 120.”

Solution 1

To solve this task, we will use a loop to multiply the numbers from 1 to the given number to calculate the factorial.

1. Read the number, let’s call it `num`, from the user.
2. Initialize a variable `factorial` with a value of 1.
3. Use a loop to multiply the numbers from 1 to `num` with the `factorial` variable.
4. Update the `factorial` value in each iteration of the loop.
5. After the loop ends, the `factorial` variable will hold the factorial value of the given number.
6. Display the factorial value to the user.
```import java.util.Scanner;

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

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

int factorial = 1;

for (int i = 1; i <= num; i++) {
factorial *= i;
}

System.out.println("The factorial of " + num + " is " + factorial);

input.close();
}
}
```

Solution 2

To solve this task using recursion, we will define a recursive method to calculate the factorial.

1. Read the number, let’s call it `num`, from the user.
2. Define a recursive method, let’s call it `calculateFactorial`, that takes an integer parameter `n`.
3. In the `calculateFactorial` method:
• If `n` is 0 or 1, return 1 as the base case of the factorial.
• Otherwise, recursively call the `calculateFactorial` method with `n-1` and multiply the result by `n`.
4. Call the `calculateFactorial` method with the given number `num` and store the result in a variable `factorial`.
5. Display the factorial value to the user.
```import java.util.Scanner;

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

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

int factorial = calculateFactorial(num);

System.out.println("The factorial of " + num + " is " + factorial);

input.close();
}

private static int calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * calculateFactorial(n - 1);
}
}
```

Reverse a String

In this task, you need to write a Java program to reverse a given string. The reverse of a string is obtained by reversing the order of its characters.

1. Ask the user to enter a string.
2. Reverse the entered string.
3. Display the reversed string to the user.

Example

If the user enters “Hello” as the string, the program should reverse it as “olleH” and display the message: “The reversed string is olleH.”

Solution

To solve this task, we will convert the string into a character array and reverse the order of the characters.

1. Read the string, let’s call it `str`, from the user.
2. Convert the string into a character array using the `toCharArray()` method.
3. Initialize two variables, `start` with a value of 0 and `end` with a value of the last index of the character array.
4. Use a loop to swap the characters at the `start` and `end` positions until `start` becomes greater than or equal to `end`.
5. Increment `start` and decrement `end` in each iteration of the loop.
6. After the loop ends, the character array will contain the reversed string.
7. Create a new string from the reversed character array using the `String` constructor.
8. Display the reversed string to the user.
```import java.util.Scanner;

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

System.out.print("Enter a string: ");
String str = input.nextLine();

char[] charArray = str.toCharArray();
int start = 0;
int end = charArray.length - 1;

while (start < end) {
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}

String reversedStr = new String(charArray);

System.out.println("The reversed string is " + reversedStr);

input.close();
}
}
```

Remove Duplicates from an Array

In this task, you need to write a Java program to remove duplicates from an array without utilizing the Collections API. The program should create a new array that contains only the unique elements from the original array, preserving their order.

1. Create an array of integers.
2. Remove duplicates from the array.
3. Create a new array that contains only the unique elements from the original array, in the same order.
4. Display the new array to the user.

Example

If the original array is [5, 2, 7, 2, 9, 5], the program should remove the duplicates and create a new array as [5, 2, 7, 9]. It should then display the message: “The array without duplicates is [5, 2, 7, 9].”

Solution

To solve this task, we will iterate through the original array and use an additional boolean array to keep track of the presence of elements. We will create a new array that only includes unique elements.

1. Create the original array with the desired elements.
2. Create a boolean array, `isDuplicate`, with the same size as the original array and initialize all elements to `false`.
3. Initialize a variable, `count`, with a value of 0, to keep track of the number of unique elements.
4. Iterate through the original array using a loop:
• For each element, check if it is a duplicate by checking the corresponding element in the `isDuplicate` array.
• If the element is not a duplicate, set the `isDuplicate` value to `true` and increment `count`.
5. Create a new array, `newArray`, with a size of `count`.
6. Iterate through the original array again:
• For each element, if it is not a duplicate, add it to the `newArray` at the corresponding position and increment the position index.
7. Display the `newArray` to the user.
```import java.util.Arrays;

public class RemoveDuplicatesFromArray {
public static void main(String[] args) {
int[] originalArray = {5, 2, 7, 2, 9, 5};
int length = originalArray.length;

boolean[] isDuplicate = new boolean[length];
int count = 0;

for (int i = 0; i < length; i++) {
if (!isDuplicate[i]) {
isDuplicate[i] = true;
count++;
for (int j = i + 1; j < length; j++) {
if (originalArray[j] == originalArray[i]) {
isDuplicate[j] = true;
}
}
}
}

int[] newArray = new int[count];
int index = 0;

for (int i = 0; i < length; i++) {
if (!isDuplicate[i]) {
newArray[index] = originalArray[i];
index++;
}
}

System.out.println("The array without duplicates is " + Arrays.toString(newArray));
}
}
```

Printing Patterns (Square Pattern)

In this task, you need to write a Java program to print a square pattern of asterisks (*). The size of the square is determined by the user input.

1. Ask the user to enter the size of the square.
2. Print a square pattern of asterisks with the specified size.

Example

If the user enters 5 as the size, the program should print the following pattern:

```*****
*****
*****
*****
*****
```

Solution

To solve this task, we will use nested loops to iterate through rows and columns and print asterisks accordingly.

1. Read the size of the square, let’s call it `size`, from the user.
2. Use two nested loops:
• The outer loop controls the rows and iterates from 1 to `size`.
• The inner loop controls the columns and also iterates from 1 to `size`.
3. Print an asterisk (*) in each iteration of the inner loop.
4. After printing all asterisks in a row, move to the next line.
5. Repeat steps 3-4 until all rows are printed.
```import java.util.Scanner;

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

System.out.print("Enter the size of the square: ");
int size = input.nextInt();

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

input.close();
}
}
```

Printing Patterns (Pyramid Pattern)

In this task, you need to write a Java program to print a pyramid pattern of asterisks (*). The number of rows in the pyramid is determined by the user input.

1. Ask the user to enter the number of rows for the pyramid.
2. Print a pyramid pattern of asterisks with the specified number of rows.

Example

If the user enters 5 as the number of rows, the program should print the following pattern:

```    *
***
*****
*******
*********
```

Solution

To solve this task, we will use nested loops to iterate through rows and columns and print spaces and asterisks accordingly.

1. Read the number of rows for the pyramid, let’s call it `rows`, from the user.
2. Use two nested loops:
• The outer loop controls the rows and iterates from 1 to `rows`.
• The inner loop controls the columns and iterates from 1 to `rows - i` (where `i` is the current row number).
3. Print spaces (” “) in each iteration of the inner loop to align the asterisks properly.
4. Print asterisks (*) in each iteration of the inner loop. The number of asterisks in a row is calculated as `2*i - 1`.
5. After printing all spaces and asterisks in a row, move to the next line.
6. Repeat steps 3-5 until all rows are printed.
```import java.util.Scanner;

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

System.out.print("Enter the number of rows for the pyramid: ");
int rows = input.nextInt();

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();
}

input.close();
}
}
```

GCD of Two Numbers

In this task, you need to write a Java program to calculate the greatest common divisor (GCD) of two numbers. The GCD is the largest positive integer that divides both numbers without leaving a remainder.

1. Ask the user to enter two positive integers.
2. Calculate and display the GCD of the entered numbers.

Example

If the user enters 24 and 36 as the numbers, the program should calculate the GCD as 12 and display the message: “The GCD of 24 and 36 is 12.”

Solution

To solve this task, we will use the Euclidean algorithm, which recursively finds the GCD of two numbers.

1. Read the two positive integers, let’s call them `num1` and `num2`, from the user.
2. Define a recursive method, let’s call it `calculateGCD`, that takes two integer parameters: `a` and `b`.
3. In the `calculateGCD` method:
• Check if `b` is 0. If true, return `a` as the GCD.
• Otherwise, recursively call the `calculateGCD` method with `b` and the remainder of `a` divided by `b`.
4. Call the `calculateGCD` method with `num1` and `num2`, and store the result in a variable `gcd`.
5. Display the GCD value to the user.
```import java.util.Scanner;

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

System.out.print("Enter the first positive integer: ");
int num1 = input.nextInt();

System.out.print("Enter the second positive integer: ");
int num2 = input.nextInt();

int gcd = calculateGCD(num1, num2);

System.out.println("The GCD of " + num1 + " and " + num2 + " is " + gcd);

input.close();
}

private static int calculateGCD(int a, int b) {
if (b == 0) {
return a;
}

return calculateGCD(b, a % b);
}
}
```

The Square Root of a Number

In this task, you need to write a Java program to calculate the square root of a number without utilizing the `Math.sqrt()` function. The program should use the Newton’s method to approximate the square root.

1. Ask the user to enter a positive number.
2. Calculate and display the square root of the entered number.

Example

If the user enters 25 as the number, the program should calculate the square root as 5 and display the message: “The square root of 25 is 5.”

Solution 1

To solve this task, we will use the Newton’s method to iteratively approximate the square root of a number.

1. Read the positive number, let’s call it `number`, from the user.
2. Initialize variables: `guess` with an initial value of `number / 2`, `error` with a value greater than the desired accuracy (e.g., 0.0001), and `sqrt` with a value of 0.
3. Use a loop to refine the approximation of the square root:
• Calculate `sqrt` as `(guess + number / guess) / 2`.
• Calculate the absolute value of the difference between `sqrt` and `guess`.
• If the difference is less than or equal to `error`, exit the loop.
• Update `guess` with the new calculated value of `sqrt`.
4. Display the calculated square root (`sqrt`) to the user.
```import java.util.Scanner;

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

System.out.print("Enter a positive number: ");
double number = input.nextDouble();

double guess = number / 2;
double error = 0.0001;
double sqrt = 0;

while (Math.abs(sqrt - guess) > error) {
sqrt = (guess + number / guess) / 2;
guess = sqrt;
}

System.out.println("The square root of " + number + " is " + sqrt);

input.close();
}
}
```

Solution 2

We can also use the Babylonian method (also known as Heron’s method) to approximate the square root through iterative calculations.

1. Read the positive number, let’s call it `number`, from the user.
2. Initialize variables: `guess` with an initial value of `number / 2`, `error` with a value greater than the desired accuracy (e.g., 0.0001), and `sqrt` with a value of 0.
3. Use a loop to refine the approximation of the square root:
• Calculate `sqrt` as the average of `guess` and `number / guess`.
• Update `guess` with the new calculated value of `sqrt`.
• Calculate the absolute value of the difference between `sqrt` and `guess`.
• If the difference is less than or equal to `error`, exit the loop.
4. Display the calculated square root (`sqrt`) to the user.
```import java.util.Scanner;

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

System.out.print("Enter a positive number: ");
double number = input.nextDouble();

double guess = number / 2;
double error = 0.0001;
double sqrt = 0;

while (Math.abs(sqrt - guess) > error) {
sqrt = (guess + number / guess) / 2;
guess = sqrt;
}

System.out.println("The square root of " + number + " is " + sqrt);

input.close();
}
}
```

Leap Year

In this task, you need to write a Java program to check whether a given year is a leap year or not. A leap year is a year that is divisible by 4, except for years that are divisible by 100 but not divisible by 400.

1. Ask the user to enter a year.
2. Check and display whether the entered year is a leap year or not.

Example

If the user enters 2024 as the year, the program should display the message: “2024 is a leap year.”

Solution

To solve this task, we will use conditional statements to check the given conditions for leap years.

1. Read the year, let’s call it `year`, from the user.
2. Use conditional statements to check whether the year is a leap year:
• If the year is divisible by 400, it is a leap year.
• If the year is divisible by 100 but not divisible by 400, it is not a leap year.
• If the year is divisible by 4 but not divisible by 100, it is a leap year.
• Otherwise, it is not a leap year.
3. Display the result to the user.
```import java.util.Scanner;

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

System.out.print("Enter a year: ");
int year = input.nextInt();

boolean isLeapYear = false;

if (year % 400 == 0) {
isLeapYear = true;
} else if (year % 100 == 0) {
isLeapYear = false;
} else if (year % 4 == 0) {
isLeapYear = true;
} else {
isLeapYear = false;
}

if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}

input.close();
}
}
```

Conclusion

In conclusion, we have explored a compilation of top Java programs frequently encountered in job interviews. These programs serve as excellent tools to assess your Java programming skills, logical thinking, and problem-solving abilities. By understanding the task requirements and studying the provided solutions, you have gained valuable insights into tackling a variety of programming challenges.

As you continue your journey in mastering Java, I encourage you to check out the Java Interview Questions page. There, you will find additional valuable content, designed to further enhance your preparation and excel in your job interviews.