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 are getting ready for a Java Job Interview, then check out these Java Job Interview Questions as well.

## Fibonacci Series

### Task

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.

### Task Instructions

- Ask the user to enter a positive integer.
- 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:

- Read the number of terms, let’s call it
`n`

, from the user. - Declare three variables
`firstTerm`

,`secondTerm`

, and`nextTerm`

, and initialize`firstTerm`

to 0 and`secondTerm`

to 1. - Print
`firstTerm`

and`secondTerm`

as the initial terms of the series. - 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`

.

- Calculate
- Exit the loop.
- 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.

- 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. - If
`n`

is 0 or 1, return`n`

as it represents the base cases of the Fibonacci series. - Otherwise, recursively call the
`fibonacci`

function with`n-1`

and`n-2`

as parameters, and return the sum of the results. - In the
`main`

method, read the number of terms,`n`

, from the user. - 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

### Task

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.

### Task Instructions

- Prompt the user to enter a positive integer.
- Validate the input to ensure it is a positive integer.
- Implement the logic to check if the entered number is prime or not.
- 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.

- Read the number, let’s call it
`num`

, from the user. - Initialize a boolean variable
`isPrime`

to`true`

. - 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`

.

- Check if
- 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.

- If
- Display an appropriate message to the user based on the value of
`isPrime`

.

import java.util.Scanner; public class PrimeNumber { 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

### Task

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.

### Task Instructions

- Ask the user to enter a string.
- Check if the entered string is a palindrome.
- 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.

- Read the string, let’s call it
`str`

, from the user. - Remove any spaces and convert the string to lowercase for case-insensitive comparison.
- Initialize two pointers:
`start`

pointing to the beginning of the string and`end`

pointing to the end of the string. - 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.

- Compare the characters at indices
- After the loop, if the loop terminated without finding any unequal characters, the string is a palindrome.
- 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:

- Read the string, let’s call it
`str`

, from the user. - Remove any spaces and convert the string to lowercase for case-insensitive comparison.
- Create a StringBuilder object and initialize it with the reversed version of
`str`

. - Compare the reversed string obtained from the StringBuilder with the original string.
- If they are equal, the string is a palindrome. Otherwise, it is not.
- 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

### Task

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.

### Task Instructions

- Ask the user to enter a positive integer.
- Check if the entered number is an Armstrong number.
- 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.

- Read the number, let’s call it
`num`

, from the user. - Declare variables to store the sum of the cubes of the digits and the original number of digits.
- Create a copy of the original number to count the number of digits.
- 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.

- Calculate the remainder of
- 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.

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

## Avoiding Deadlock

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.

### Task

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) { Thread thread1 = new Thread(() -> { synchronized (resource1) { System.out.println("Thread 1 acquired resource 1"); try { Thread.sleep(100); // Introduce a delay to allow the second thread to acquire resource 2 } catch (InterruptedException e) { e.printStackTrace(); } synchronized (resource2) { System.out.println("Thread 1 acquired resource 2"); } } }); Thread thread2 = new Thread(() -> { synchronized (resource2) { System.out.println("Thread 2 acquired resource 2"); synchronized (resource1) { System.out.println("Thread 2 acquired resource 1"); } } }); thread1.start(); thread2.start(); } }

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) { Thread thread1 = new Thread(() -> { synchronized (resource1) { System.out.println("Thread 1 acquired resource 1"); try { Thread.sleep(100); // Introduce a delay to allow the second thread to acquire resource 2 } catch (InterruptedException e) { e.printStackTrace(); } synchronized (resource2) { System.out.println("Thread 1 acquired resource 2"); } } }); Thread thread2 = new Thread(() -> { synchronized (resource1) { System.out.println("Thread 2 acquired resource 1"); synchronized (resource2) { System.out.println("Thread 2 acquired resource 2"); } } }); thread1.start(); thread2.start(); } }

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.

### Best Practices to Avoid Deadlock

Here are some best practices to avoid deadlock in Java:

**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.**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.**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.**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.**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.**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

### Task

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`

.

### Task Instructions

- Ask the user to enter a non-negative integer.
- Calculate the factorial of the entered number.
- 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.

- Read the number, let’s call it
`num`

, from the user. - Initialize a variable
`factorial`

with a value of 1. - Use a loop to multiply the numbers from 1 to
`num`

with the`factorial`

variable. - Update the
`factorial`

value in each iteration of the loop. - After the loop ends, the
`factorial`

variable will hold the factorial value of the given number. - 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.

- Read the number, let’s call it
`num`

, from the user. - Define a recursive method, let’s call it
`calculateFactorial`

, that takes an integer parameter`n`

. - 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`

.

- If
- Call the
`calculateFactorial`

method with the given number`num`

and store the result in a variable`factorial`

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

### Task

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.

### Task Instructions

- Ask the user to enter a string.
- Reverse the entered string.
- 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.

- Read the string, let’s call it
`str`

, from the user. - Convert the string into a character array using the
`toCharArray()`

method. - Initialize two variables,
`start`

with a value of 0 and`end`

with a value of the last index of the character array. - Use a loop to swap the characters at the
`start`

and`end`

positions until`start`

becomes greater than or equal to`end`

. - Increment
`start`

and decrement`end`

in each iteration of the loop. - After the loop ends, the character array will contain the reversed string.
- Create a new string from the reversed character array using the
`String`

constructor. - 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

### Task

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.

### Task Instructions

- Create an array of integers.
- Remove duplicates from the array.
- Create a new array that contains only the unique elements from the original array, in the same order.
- 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.

- Create the original array with the desired elements.
- Create a boolean array,
`isDuplicate`

, with the same size as the original array and initialize all elements to`false`

. - Initialize a variable,
`count`

, with a value of 0, to keep track of the number of unique elements. - 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`

.

- For each element, check if it is a duplicate by checking the corresponding element in the
- Create a new array,
`newArray`

, with a size of`count`

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

- For each element, if it is not a duplicate, add it to the
- 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)

### Task

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.

### Task Instructions

- Ask the user to enter the size of the square.
- 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.

- Read the size of the square, let’s call it
`size`

, from the user. - 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`

.

- The outer loop controls the rows and iterates from 1 to
- Print an asterisk (*) in each iteration of the inner loop.
- After printing all asterisks in a row, move to the next line.
- 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)

### Task

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.

### Task Instructions

- Ask the user to enter the number of rows for the pyramid.
- 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.

- Read the number of rows for the pyramid, let’s call it
`rows`

, from the user. - 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).

- The outer loop controls the rows and iterates from 1 to
- Print spaces (” “) in each iteration of the inner loop to align the asterisks properly.
- Print asterisks (*) in each iteration of the inner loop. The number of asterisks in a row is calculated as
`2*i - 1`

. - After printing all spaces and asterisks in a row, move to the next line.
- 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

### Task

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.

### Task Instructions

- Ask the user to enter two positive integers.
- 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.

- Read the two positive integers, let’s call them
`num1`

and`num2`

, from the user. - Define a recursive method, let’s call it
`calculateGCD`

, that takes two integer parameters:`a`

and`b`

. - 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`

.

- Check if
- Call the
`calculateGCD`

method with`num1`

and`num2`

, and store the result in a variable`gcd`

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

### Task

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.

### Task Instructions

- Ask the user to enter a positive number.
- 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.

- Read the positive number, let’s call it
`number`

, from the user. - 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. - 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`

.

- Calculate
- 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.

- Read the positive number, let’s call it
`number`

, from the user. - 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. - 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.

- Calculate
- 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

### Task

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.

### Task Instructions

- Ask the user to enter a year.
- 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.

- Read the year, let’s call it
`year`

, from the user. - 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.

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

## Frequently asked questions

**How can practicing these Java programs help in job interviews?**

Practicing these Java programs can significantly help in job interviews by showcasing your proficiency in Java programming, problem-solving abilities, and understanding of fundamental programming concepts.

By working through these programs, you gain hands-on experience in solving common coding challenges, which demonstrates your practical skills to potential employers. Additionally, these programs provide opportunities to apply key Java concepts, such as loops, conditionals, recursion, and data manipulation, which are frequently assessed in technical interviews.**Are there alternative solutions or variations to the programs provided in this page?**

Yes, there are often alternative solutions or variations to the programs provided in this page. The programs presented here offer one way to solve the given tasks, but programming is a creative endeavor, and there are often multiple approaches to tackle a problem.

Depending on the specific requirements, constraints, or personal coding style, programmers may come up with alternative solutions or variations that achieve the same results. Exploring different approaches can further expand your problem-solving skills and deepen your understanding of Java programming.**Is Java OK for coding interviews?**

Yes, Java is a popular and widely accepted language for coding interviews. Java offers a strong foundation in object-oriented programming, which aligns well with the principles commonly assessed in coding interviews. It provides a robust set of libraries, extensive documentation, and a vast developer community, making it suitable for tackling a wide range of programming challenges.

However, it’s important to note that the choice of programming language for coding interviews ultimately depends on the company and the specific role. It’s advisable to research the company’s preferences and requirements beforehand to tailor your preparation accordingly.**Is knowing Java enough to get a job?**

Knowing Java is undoubtedly an essential skill for securing a job in the software development industry. Java is widely used in various domains, including web development, mobile app development, enterprise software, and more. Its versatility and extensive ecosystem make it a sought-after language by many employers.

However, it’s important to note that while knowing Java is a crucial requirement, it may not be sufficient on its own to guarantee a job. Employers often look for a combination of technical skills, practical experience, problem-solving abilities, and a strong understanding of software development principles.