Java Most Important Coding Interview and  Questions

Java Most Important Coding Interview and Questions

#SDET #JavaCoding #InterviewPrep

1. Reverse a String: Write a Java program to reverse a given string.

public class ReverseString {
    public static void main(String[] args) {
        String input = "Hello";
        String reversed = new StringBuilder(input).reverse().toString();
        System.out.println("Reversed String: " + reversed);
    }
}
        

2. Find the Largest Element in an Array: Find and print the largest element in an array.

public class LargestElement {
    public static void main(String[] args) {
        int[] arr = {3, 5, 7, 2, 8};
        int max = arr[0];
        for (int i : arr) {
            if (i > max) max = i;
        }
        System.out.println("Largest Element: " + max);
    }
}
        

3. Check for Palindrome: Determine if a given string is a palindrome.

public class PalindromeCheck {
    public static boolean isPalindrome(String str) {
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left++) != str.charAt(right--)) return false;
        }
        return true;
    }
    public static void main(String[] args) {
        String input = "madam";
        System.out.println("Is Palindrome: " + isPalindrome(input));
    }
}
        

4. Factorial Calculation: Write a function to calculate the factorial of a number.

public class Factorial {
    public static int factorial(int n) {
        if (n == 0) return 1;
        return n * factorial(n - 1);
    }
    public static void main(String[] args) {
        int num = 5;
        System.out.println("Factorial: " + factorial(num));
    }
}
        

5. Fibonacci Series: Generate the first n numbers in the Fibonacci sequence.

public class Fibonacci {
    public static void main(String[] args) {
        int n = 10;
        int a = 0, b = 1;
        System.out.print("Fibonacci Series: " + a + " " + b);
        for (int i = 2; i < n; i++) {
            int c = a + b;
            System.out.print(" " + c);
            a = b;
            b = c;
        }
    }
}
        

6. Check for Prime Number: Write a program to check if a given number is prime.

public class PrimeCheck {
    public static boolean isPrime(int n) {
        if (n <= 1) return false;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) return false;
        }
        return true;
    }
    public static void main(String[] args) {
        int num = 17;
        System.out.println("Is Prime: " + isPrime(num));
    }
}
        

7. String Anagrams: Determine if two strings are anagrams of each other.

import java.util.Arrays;
public class AnagramCheck {
    public static boolean areAnagrams(String str1, String str2) {
        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        return Arrays.equals(arr1, arr2);
    }
    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";
        System.out.println("Are Anagrams: " + areAnagrams(str1, str2));
    }
}
        

8. Array Sorting: Implement sorting algorithms like bubble sort, merge sort, or quicksort.

public class BubbleSort {
    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;
                }
            }
        }
    }
    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        bubbleSort(arr);
        System.out.println("Sorted array: " + Arrays.toString(arr));
    }
}
        

9. Binary Search: Implement a binary search algorithm in a sorted array.

public class BinarySearch {
    public static int binarySearch(int[] arr, int target) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) return mid;
            if (arr[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return -1; // Element not found
    }
    public static void main(String[] args) {
        int[] arr = {2, 3, 4, 10, 40};
        int target = 10;
        int result = binarySearch(arr, target);
        System.out.println("Element found at index: " + result);
    }
}
        

10. Duplicate Elements in an Array: Find and print duplicate elements in an array.

import java.util.HashSet;
public class DuplicateElements {
    public static void findDuplicates(int[] arr) {
        HashSet<Integer> seen = new HashSet<>();
        for (int num : arr) {
            if (!seen.add(num)) {
                System.out.println("Duplicate found: " + num);
            }
        }
    }
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 2, 5, 3};
        findDuplicates(arr);
    }
}
        

11. Linked List Reversal: Reverse a singly-linked list.

class Node {
    int data;
    Node next;
    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class LinkedList {
    Node head;

    public void reverse() {
        Node prev = null;
        Node current = head;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        head = prev;
    }

    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);

        System.out.println("Original List:");
        list.printList();

        list.reverse();

        System.out.println("\nReversed List:");
        list.printList();
    }
}
        

12. Matrix Operations: Perform operations like addition, multiplication, or transpose.

public class MatrixOperations {
    public static void main(String[] args) {
        int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
        int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
        int[][] result = new int[3][3];

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        System.out.println("Matrix Addition Result:");
        for (int[] row : result) {
            for (int element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
}
        

13. Implement a Stack: Create a stack data structure with basic operations (push, pop).

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        // Push elements onto the stack
        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Stack: " + stack);

        // Pop an element from the stack
        int popped = stack.pop();
        System.out.println("Popped element: " + popped);

        System.out.println("Stack after pop: " + stack);
    }
}
        

14. Implement a Queue: Create a queue data structure with basic operations (enqueue, dequeue).

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();

        // Enqueue elements
        queue.add(10);
        queue.add(20);
        queue.add(30);

        System.out.println("Queue: " + queue);

        // Dequeue an element
        int dequeued = queue.poll();
        System.out.println("Dequeued element: " + dequeued);

        System.out.println("Queue after dequeue: " + queue);
    }
}
        

15. Inheritance and Polymorphism: Implement class hierarchy and demonstrate polymorphism.

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Cat meows");
    }
}

public class InheritancePolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        myAnimal.sound(); // Animal makes a sound
        myDog.sound();    // Dog barks
        myCat.sound();    // Cat meows
    }
}
        

16. Exception Handling: Demonstrate the use of try-catch blocks to handle exceptions.

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int division = 10 / 0;
            System.out.println("Result: " + division);
        } catch (ArithmeticException e) {
            System.out.println("Caught an ArithmeticException: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed");
        }
    }
}
        

17. File I/O: Read from and write to a file using Java’s file I/O capabilities.

import java.io.*;

public class FileIOExample {
    public static void main(String[] args) {
        String data = "Hello, World!";
        try {
            // Write to a file
            FileWriter writer = new FileWriter("example.txt");
            writer.write(data);
            writer.close();

            // Read from a file
            BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
        

18. Multithreading: Create a multithreaded program and demonstrate thread synchronization.

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class MultithreadingExample {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Final count: " + counter.getCount());
    }
}
        

19. Lambda Expressions: Use lambda expressions to implement functional interfaces.

@FunctionalInterface
interface Operation {
    int operate(int a, int b);
}

public class LambdaExample {
    public static void main(String[] args) {
        // Using lambda expressions
        Operation addition = (a, b) -> a + b;
        Operation subtraction = (a, b) -> a - b;

        System.out.println("Addition: " + addition.operate(5, 3));
        System.out.println("Subtraction: " + subtraction.operate(5, 3));
    }
}
        

20. Recursive Algorithms: Solve problems using recursion, like computing factorial or Fibonacci sequence.

public class RecursiveAlgorithms {
    public static int factorial(int n) {
        if (n == 0) return 1;
        return n * factorial(n - 1);
    }

    public static void main(String[] args) {
        int num = 5;
        System.out.println("Factorial of " + num + " is: " + factorial(num));
    }
}
        

21. Swap two Numbers: Swap two numbers without using a third variable.

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        System.out.println("Before swap: a = " + a + ", b = " + b);

        // Swapping without a third variable
        a = a + b; // a now becomes 15
        b = a - b; // b becomes 5
        a = a - b; // a becomes 10

        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}
        

??Comments below if you have any other Coding questions !!

?Follow Kushal Parikh for insightful content on Automation Testing & don't forget to check out my topmate.io link: https://lnkd.in/dEDZxwwF

?? ???????????????? ????/???????? ?????????????? ??????

https://lnkd.in/dYPWn5xE

?? ???????????????? ????/???????? ?????????????????? ?????????????????????? ??????

https://lnkd.in/dskETMfb

?? ???????????????????? ?????????????? ???????????????? ????????????????

https://lnkd.in/dBzp5RAy

?? ?????? ???????????? ?????????????????? ??????

https://lnkd.in/d3ywVEhS

?????????? ??????????????! ??

hashtag#testing hashtag#java hashtag#functional hashtag#coding hashtag#qa hashtag#interview hashtag#testingcommunity

Jatin Kumar

SDET Engineer I at American Express | Ex-BlackRock, Innovecture, Infosys

6 个月
回复
Mayank Rusia

Selenium | TestNG | Java | Cucumber | Jenkins | docker | SQL | Git | Jira | Maven | Extent Reports| API testing using Postman | Manual Testing

6 个月

Will these questions be ok for fresher automation tester & is stack, queue, multi threading questions interviewer asked to freshers candidate??

Kushal Parikh

QA Automation Engineer | SDET | Test Automation Consultant | Selenium | Java | Playwright | SFPC? Certified | Driving Quality Through Automation

6 个月

Please visit the blog for Answers of these questions !! ??

回复

要查看或添加评论,请登录

Kushal Parikh的更多文章

社区洞察

其他会员也浏览了