0% found this document useful (0 votes)
21 views4 pages

Common Java Interview Programs

Uploaded by

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

Common Java Interview Programs

Uploaded by

keerthiv2340
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

15 Most Common Java Interview Programs

1. Reverse a String
public class ReverseString {
public static String reverse(String input) {
return new StringBuilder(input).reverse().toString();
}
}

2. Check Palindrome
public class PalindromeCheck {
public static boolean isPalindrome(String str) {
return [Link](new StringBuilder(str).reverse().toString());
}
}

3. Factorial of a Number
public class Factorial {
public static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
}

4. Fibonacci Series
public class Fibonacci {
public static void printFibonacci(int count) {
int a = 0, b = 1;
for (int i = 0; i < count; i++) {
[Link](a + " ");
int sum = a + b;
a = b;
b = sum;
}
}
}

5. Prime Number Check


public class PrimeCheck {
public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) return false;
}
return true;
}
}

6. Swap Two Numbers without Temp


public class SwapNumbers {
public static void swap(int a, int b) {
[Link]("Before: a=" + a + ", b=" + b);
a = a + b;
b = a - b;
a = a - b;
[Link]("After: a=" + a + ", b=" + b);
}
}

7. Count Digits
public class CountDigits {
public static int countDigits(int n) {
int count = 0;
while (n != 0) {
n /= 10;
count++;
}
return count;
}
}

8. Reverse a Number
public class ReverseNumber {
public static int reverse(int num) {
int rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
}

9. Sum of Digits
public class SumOfDigits {
public static int sumDigits(int num) {
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
}

10. Check Armstrong Number


public class Armstrong {
public static boolean isArmstrong(int num) {
int temp = num, sum = 0, digits = 0;
while (temp != 0) {
digits++;
temp /= 10;
}
temp = num;
while (temp != 0) {
sum += [Link](temp % 10, digits);
temp /= 10;
}
return sum == num;
}
}

11. Find Largest Element in Array


public class LargestInArray {
public static int findMax(int[] arr) {
int max = arr[0];
for (int i : arr) {
if (i > max) max = i;
}
return max;
}
}

12. Linear Search


public class LinearSearch {
public static int search(int[] arr, int key) {
for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) return i;
}
return -1;
}
}

13. Binary Search


public class BinarySearch {
public static int search(int[] arr, int key) {
int low = 0, high = [Link] - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
}

14. Check Even or Odd


public class EvenOdd {
public static boolean isEven(int n) {
return n % 2 == 0;
}
}

15. Print Multiplication Table


public class MultiplicationTable {
public static void printTable(int n) {
for (int i = 1; i <= 10; i++) {
[Link](n + " x " + i + " = " + (n * i));
}
}
}

Common questions

Powered by AI

Linear search, as shown in 'public class LinearSearch { public static int search(int[] arr, int key) { for (int i = 0; i < arr.length; i++) { if (arr[i] == key) return i; } return -1; } }', has a time complexity of O(n) because it checks each element in succession. Binary search, 'public class BinarySearch { public static int search(int[] arr, int key) { int low = 0, high = arr.length - 1; ... } }', reduces time complexity to O(log n) by dividing the search interval in half repeatedly. Linear search is preferred for unsorted datasets and small arrays due to its simplicity, while binary search is optimal for large, sorted datasets, providing faster results due to its decreased operations per search.

The iterative method 'public class SumOfDigits { public static int sumDigits(int num) { int sum = 0; while (num != 0) { sum += num % 10; num /= 10; } return sum; } }' processes each digit of the number by repeatedly using modulo and division operations until the number becomes zero. This iterative method avoids the risk of stack overflow associated with recursive solutions, as it does not rely on repeated function calls which can exhaust stack memory, particularly when handling very large numbers.

The method 'public class PalindromeCheck { public static boolean isPalindrome(String str) { return str.equals(new StringBuilder(str).reverse().toString()); } }' uses string manipulation by reversing the input string and checking for equality with the original. This approach leverages the StringBuilder class to create a reversed version of the string. However, the method is limited by the maximum string length that can be handled, which is bounded by memory constraints. Additionally, converting very large numbers into strings for palindrome checking can introduce inefficiencies compared to numeric checks that avoid such conversions.

The implementation 'public class BinarySearch { public static int search(int[] arr, int key) { int low = 0, high = arr.length - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == key) return mid; if (arr[mid] < key) low = mid + 1; else high = mid - 1; } return -1; } }' can encounter integer overflow when calculating the mid index if the sum of low and high exceeds the maximum value for integers. This can result in negative indices or incorrect behavior. A common mitigation strategy is to compute mid using 'int mid = low + (high - low) / 2;' to avoid the overflow problem by ensuring the addition does not exceed integer limits.

The method 'public class CountDigits { public static int countDigits(int n) { int count = 0; while (n != 0) { n /= 10; count++; } return count; } }' calculates the number of digits by dividing the number by 10 iteratively. This algorithm has a time complexity of O(n), where n is the number of digits in the number because each division reduces the number by one digit. This approach is scalable for numbers of moderate size but becomes inefficient for minuscule performance requirements compared to using logarithmic calculations (e.g., log10(n) + 1) to instantly determine digit count, which is more optimal for large integers and offers O(1) complexity.

The algorithm 'public class SwapNumbers { public static void swap(int a, int b) { a = a + b; b = a - b; a = a - b; } }' avoids using a temporary variable by exploiting arithmetic operations to rearrange the value assignments. However, this method can suffer from overflow or underflow if the sum of the two numbers exceeds the maximum value for the integer type in the programming language. An alternative is to use bitwise XOR operations to perform the swap, which inherently avoids overflow and is a safer method when working with limits near the integer boundaries.

Using a for-loop as done in 'public class Fibonacci { public static void printFibonacci(int count) { int a = 0, b = 1; for (int i = 0; i < count; i++) { System.out.print(a + " "); int sum = a + b; a = b; b = sum; } } }' avoids the overhead of recursive calls and the associated stack usage, leading to a more memory-efficient solution. Recursive generation often leads to redundant calculations and higher memory consumption due to recursive call stacks, while the iterative approach only uses constant space for the variables a and b, achieving better performance and lower memory usage.

The recursive approach to calculating a factorial, as shown in 'public class Factorial { public static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } }', involves calling the function repeatedly until the base case is reached, which uses the call stack to hold each call until it can be resolved. This can lead to increased stack usage and potential stack overflows for very large numbers due to excessive depth of recursion. In contrast, an iterative approach calculates the factorial using a loop and a single variable to hold the intermediate results, significantly reducing stack usage and improving efficiency for large inputs.

The approach 'public class PrimeCheck { public static boolean isPrime(int num) { if (num <= 1) return false; for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) return false; } return true; } }' uses trial division up to the square root of the number, which reduces unnecessary checks beyond the square root, reducing time complexity to O(√n). Despite this efficiency, improvements like implementing the 6k ± 1 optimization can be made, where only numbers of the form 6k ± 1 need to be verified as potential factors, further reducing the number of iterations required for large primes.

The algorithm 'public class Armstrong { public static boolean isArmstrong(int num) { int temp = num, sum = 0, digits = 0; while (temp != 0) { digits++; temp /= 10; } temp = num; while (temp != 0) { sum += Math.pow(temp % 10, digits); temp /= 10; } return sum == num; } }' calculates the sum of each digit raised to the power of the total number of digits, comparing it to the original number. Although it does not directly calculate digital roots, it leverages a similar principle of summing powers of digits to identify Armstrong numbers. This methodology could be adapted to solve other problems that involve manipulation and validation based on the properties of digits and their distributions, making it applicable in cryptographic computations and digital verification algorithms.

You might also like