Core Java Interview Questions For Freshers: Master the Fundamentals with Confidence! Set -2

Core Java Interview Questions For Freshers: Master the Fundamentals with Confidence! Set -2

100 + Core Java Interview Questions For Freshers: Empower Your Knowledge

Are you freshly graduated and ready to launch a career as a Java developer? Or are you a seasoned programmer looking to transition to Java? In any case, you’ll almost certainly have to face the obstacle of a job interview. We’ve collected a comprehensive list of 100+ Core Java interview questions spanning a wide range of topics to help you prepare for and ace that interview. This tutorial will give you the information and confidence you need to ace your Java interview.

Here are “ Core Java Interview Questions For Freshers ” 50 theoretical questions ranging from basic to advanced, as well as 50 code problems covering “Basic Java Concepts,” “Variables and Data Types,” and “Operators and Expressions.

College Notes – for all university students – Updategadh
College Notes – for university students | Discover the ultimate exam preparation resources at CollegeNotes!
updategadh.com

Topic :-Basic Java Concepts, Variables and Data Types, Operators and Expressions, Garbage Collection, Design Patterns ,File Handling.

Core Java Interview Questions For Freshers Set -2

Write a Java program to find the sum of two numbers.

  1. Find the sum of two numbers:
import java.util.Scanner;

public class SumOfTwoNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        double num1 = sc.nextDouble();
        System.out.print("Enter the second number: ");
        double num2 = sc.nextDouble();

        double sum = num1 + num2;
        System.out.println("Sum: " + sum);
    }
}

# 2 Calculate the area of a circle in Java given its radius.

  1. Calculate the area of a circle given its radius:
import java.util.Scanner;

public class CircleArea {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the radius of the circle: ");
        double radius = sc.nextDouble();

        double area = Math.PI * radius * radius;
        System.out.println("Area of the circle: " + area);
    }
}

# 3 Implement a program to convert temperature from Fahrenheit to Celsius.

  1. Convert temperature from Fahrenheit to Celsius:
import java.util.Scanner;

public class FahrenheitToCelsius {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter temperature in Fahrenheit: ");
        double fahrenheit = sc.nextDouble();

        double celsius = (fahrenheit - 32) * 5/9;
        System.out.println("Temperature in Celsius: " + celsius);
    }
}

#4 Create a Java program to check whether a given number is prime or not.

  1. Check whether a given number is prime or not:
public class PrimeCheck {
    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int num = 17; // Replace with your number to check
        if (isPrime(num)) {
            System.out.println(num + " is a prime number.");
        } else {
            System.out.println(num + " is not a prime number.");
        }
    }
}

# 5 Write code to reverse a string in Java.

  1. Reverse a string:
public class ReverseString {
    public static String reverse(String str) {
        StringBuilder reversed = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed.append(str.charAt(i));
        }
        return reversed.toString();
    }

    public static void main(String[] args) {
        String original = "Hello, World!";
        String reversed = reverse(original);
        System.out.println("Reversed String: " + reversed);
    }
}
Core Java Interview Questions For Freshers: Master the Fundamentals with Confidence!
Core Java Interview Questions For Freshers |
updategadh.com

#6 Implement a program to find the factorial of a number using recursion.

  1. Factorial Using Recursion
    Question: Implement a program to find the factorial of a number using recursion.
   public static int factorial(int n) {
       if (n == 0) {
           return 1;
       } else {
           return n * factorial(n - 1);
       }
   }

Calculate the sum of natural numbers up to a given limit using a loop.

  1. Sum of Natural Numbers Using a Loop
    Question: Calculate the sum of natural numbers up to a given limit using a loop.
   public static int sumOfNaturalNumbers(int limit) {
       int sum = 0;
       for (int i = 1; i <= limit; i++) {
           sum += i;
       }
       return sum;
   }

Write code to check if a given string is a palindrome or not.

  1. Palindrome Check
    Question: Write code to check if a given string is a palindrome or not.
   public static boolean isPalindrome(String str) {
       str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
       int left = 0;
       int right = str.length() - 1;
       while (left < right) {
           if (str.charAt(left) != str.charAt(right)) {
               return false;
           }
           left++;
           right--;
       }
       return true;
   }

Implement a Java program to count the number of vowels in a string.

  1. Count Vowels in a String
    Question: Implement a Java program to count the number of vowels in a string.
   public static int countVowels(String str) {
       str = str.toLowerCase();
       int count = 0;
       for (int i = 0; i < str.length(); i++) {
           char ch = str.charAt(i);
           if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
               count++;
           }
       }
       return count;
   }

Find the factorial of a number without using recursion.

  1. Factorial Without Recursion
    Question: Find the factorial of a number without using recursion.
   public static int factorial(int n) {
       int fact = 1;
       for (int i = 1; i <= n; i++) {
           fact *= i;
       }
       return fact;
   }

Calculate the average of an array of integers in Java.

  1. Average of an Array
    Question: Calculate the average of an array of integers in Java.
   public static double calculateAverage(int[] arr) {
       int sum = 0;
       for (int num : arr) {
           sum += num;
       }
       return (double) sum / arr.length;
   }

Write code to find the maximum and minimum elements in an array.

  1. Maximum and Minimum Elements in an Array
    Question: Write code to find the maximum and minimum elements in an array.
   public static int findMax(int[] arr) {
       int max = arr[0];
       for (int num : arr) {
           if (num > max) {
               max = num;
           }
       }
       return max;
   }

   public static int findMin(int[] arr) {
       int min = arr[0];
       for (int num : arr) {
           if (num < min) {
               min = num;
           }
       }
       return min;
   }

Implement a Java program to check if a number is even or odd.

  1. Even or Odd Check
    Question: Implement a Java program to check if a number is even or odd.
   public static boolean isEven(int num) {
       return num % 2 == 0;
   }


Create a Java program to find the largest among three numbers.

  1. Largest Among Three Numbers
    Question: Create a Java program to find the largest among three numbers.
   public static int findLargest(int num1, int num2, int num3) {
       return Math.max(Math.max(num1, num2), num3);
   }

Create a program to print the Fibonacci series up to a given limit.

public static void printFibonacci(int n) {
    int first = 0, second = 1;
    for (int i = 0; i < n; i++) {
        System.out.print(first + " ");
        int next = first + second;
        first = second;
        second = next;
    }
}

Calculate the sum of all even numbers up to a given limit using a loop.

public static int sumOfEvenNumbers(int limit) {
    int sum = 0;
    for (int i = 2; i <= limit; i += 2) {
        sum += i;
    }
    return sum;
}

Write code to find the GCD (Greatest Common Divisor) of two numbers.

public static int findGCD(int a, int b) {
    if (b == 0) {
        return a;
    }
    return findGCD(b, a % b);
}

Implement a Java program to reverse a linked list.

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public ListNode reverseLinkedList(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

Create code to find the first ‘n’ prime numbers.

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

public static void printFirstNPrimes(int n) {
    int count = 0;
    int num = 2;
    while (count < n) {
        if (isPrime(num)) {
            System.out.print(num + " ");
            count++;
        }
        num++;
    }
}
Core Java Interview Questions For Freshers
Core Java Interview Questions For Freshers

Write a program to check if a given year is a leap year or not.

public static boolean isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

Implement a program to find the sum of digits of a number.

public static int sumOfDigits(int num) {
    int sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
   

Create code to calculate the power of a number using recursion.

public static double power(double base, int exponent) {
    if (exponent == 0) {
        return 1;
    } else if (exponent > 0) {
        return base * power(base, exponent - 1);
    } else {
        return 1.0 / (base * power(base, -exponent - 1));
    }
}

Write a Java program to find the intersection of two arrays.

public static int[] findIntersection(int[] arr1, int[] arr2) {
    List<Integer> intersectionList = new ArrayList<>();
    Set<Integer> set = new HashSet<>();
    for (int num : arr1) {
        set.add(num);
    }
    for (int num : arr2) {
        if (set.contains(num)) {
            intersectionList.add(num);
        }
    }
    int[] intersection = new int[intersectionList.size()];
    for (int i = 0; i < intersectionList.size(); i++) {
        intersection[i] = intersectionList.get(i);
    }
    return intersection;
}

Implement a program to find the LCM (Least Common Multiple) of two numbers.

public static int findLCM(int a, int b) {
    return a * b / findGCD(a, b);
}

Create code to find the second largest element in an array.

public static int findSecondLargest(int[] arr) {
    int firstMax = Integer.MIN_VALUE;
    int secondMax = Integer.MIN_VALUE;
    for (int num : arr) {
        if (num > firstMax) {
            secondMax = firstMax;
            firstMax = num;
        } else if (num > secondMax && num != firstMax) {
            secondMax = num;
        }
    }
    return secondMax;
}

Write a program to rotate an array to the right by ‘k’ steps.

public static void rotateArrayRight(int[] arr, int k) {
    int n = arr.length;
    k = k % n; // Handle cases where k is larger than array size
    int[] result = new int[n];
    for (int i = 0; i < n; i++) {
        result[(i + k) % n] = arr[i];
    }
    System.arraycopy(result, 0, arr, 0, n);
}

Implement a Java program to check if a string contains all unique characters.

public static boolean hasUniqueCharacters(String str) {
    Set<Character> set = new HashSet<>();
    for (char ch : str.toCharArray()) {
        if (set.contains(ch)) {
            return false;
        }
        set.add(ch);
    }
    return true;
}

Calculate the sum of all elements in a 2D array.

See also  Top 10 : Technical interview Questions with Quick Answer for Job
YouTube player
Core Java Interview Questions For Freshers
public static int sumOf2DArray(int[][] arr) {
    int sum = 0;
    for (int[] row : arr) {
        for (int num : row) {
            sum += num;
        }
    }
    return sum;
}

Write code to sort an array of integers in ascending order.

public static void bubbleSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

Create a program to find the number of words in a string.

public static int countWords(String str) {
    String[] words = str.split("\\s+");
    return words.length;
}

Implement a Java program to find the missing number in an array of integers.

public static int findMissingNumber(int[] arr, int n) {
    int expectedSum = n * (n + 1) / 2;
    int actualSum = 0;
    for (int num : arr) {
        actualSum += num;
    }
    return expectedSum - actualSum;
}

Calculate the square root of a number using the Newton-Raphson method.

public static double sqrtNewtonRaphson(double x) {
    if (x < 0) {
        throw new IllegalArgumentException("Cannot calculate square root of a negative number");
    }
    double approx = x;
    while (Math.abs(approx * approx - x) > 1e-6) {
        approx = 0.5 * (approx + x / approx);
    }
    return approx;
}
Complete Java Course with Real Projects – Updategadh
Complete Java Course
updategadh.com

Write code to merge two sorted arrays into a single sorted array.

public static int[] mergeSortedArrays(int[] arr1, int[] arr2) {
    int n1 = arr1.length;
    int n2 = arr2.length;
    int[] result = new int[n1 + n2];
    int i = 0, j = 0, k = 0;

    while (i < n1 && j < n2) {
        if (arr1[i] < arr2[j]) {
            result[k++] = arr1[i++];
        } else {
            result[k++] = arr2[j++];
        }
    }

    while (i < n1) {
        result[k++] = arr1[i++];
    }

    while (j < n2) {
        result[k++] = arr2[j++];
    }

    return result;
}

Create a program to find the longest substring without repeating characters.

public static String findLongestSubstringWithoutRepeats(String s) {
    int n = s.length();
    int start = 0;
    int maxLen = 0;
    int maxStart = 0;
    Map<Character, Integer> charIndexMap = new HashMap<>();

    for (int i = 0; i < n; i++) {
        char ch = s.charAt(i);
        if (charIndexMap.containsKey(ch) && charIndexMap.get(ch) >= start) {
            start = charIndexMap.get(ch) + 1;
        }
        charIndexMap.put(ch, i);
        if (i - start + 1 > maxLen) {
            maxLen = i - start + 1;
            maxStart = start;
        }
    }

    return s.substring(maxStart, maxStart + maxLen);
}

Implement a Java program to check if a number is a perfect number or not.

public static boolean isPerfectNumber(int num) {
    if (num <= 1) return false;
    int sum = 1;
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            sum += i;
            if (i != num / i) {
                sum += num / i;
            }
        }
    }
    return sum == num;
}

Write a program to find the common elements between two arrays.

public static int[] findCommonElements(int[] arr1, int[] arr2) {
    Set<Integer> set1 = new HashSet<>();
    Set<Integer> set2 = new HashSet<>();
    for (int num : arr1) {
        set1.add(num);
    }
    for (int num : arr2) {
        set2.add(num);
    }
    set1.retainAll(set2);
    int[] common = new int[set1.size()];
    int index = 0;
    for (int num : set1) {
        common[index++] = num;
    }
    return common;
}

Create code to find the majority element in an array.

public static int findMajorityElement(int[] arr) {
    int candidate = 0;
    int count = 0;
    for (int num : arr) {
        if (count == 0) {
            candidate = num;
            count = 1;
        } else if (num == candidate) {
            count++;
        } else {
            count--;
        }
    }
    return candidate;
}

Implement a Java program to perform matrix multiplication.

public static int[][] matrixMultiply(int[][] A, int[][] B) {
    int m = A.length;
    int n = A[0].length;
    int p = B[0].length;

    int[][] result = new int[m][p];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < p; j++) {
            for (int k = 0; k < n; k++) {
                result[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    return result;
}

Write code to count the number of occurrences of a character in a string.

public static int countOccurrences(String str, char ch) {
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == ch) {
            count++;
        }
    }
    return count;
}
Show 43 Comments

43 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *