Java interview questions on spring boot rest API

Java interview questions on spring boot rest API

Java interview questions on spring boot rest API

1. REST

REST is an architectural style for networked applications with the following constraints:

  • Client-Server: Separates clients and servers for scalability.
  • Stateless: No client context is stored on the server between requests.
  • Cacheable: Responses must be cacheable for efficiency.
  • Uniform Interface: Standardized URIs, HTTP methods, and resource representations.
  • Layered System: Components operate independently in layers.
  • Code on Demand (optional): Allows downloading and executing code.

A common misconception is that REST is a software model, whereas it is an architectural style.

2. HTTP Methods

  • GET (Read)
  • POST (Create)
  • PUT (Replace)
  • DELETE (Remove)
  • PATCH (Partial update) → Used for updating specific fields rather than the whole object.

3. Idempotency

  • Idempotent methods: GET, PUT, DELETE (multiple requests result in the same outcome).
  • Non-idempotent methods: POST, PATCH (can cause changes with each request).
  • Example: PUT prevents duplicate side effects like charging a user twice for a service.

JAX-RS Annotations

4. Annotations

  • @Path("/resource") → Defines the URI path.
  • @GET, @POST → HTTP methods.
  • @Produces(MediaType.APPLICATION_JSON) → Specifies response format.
  • @Consumes(MediaType.APPLICATION_JSON) → Specifies request format.

5. Parameters

  • @PathParam → Extracts URL path segment (/users/{id} → id).
  • @QueryParam → Extracts URL query parameter (/users?name=John → name).
  • @FormParam → Extracts HTML form data.
  • @HeaderParam → Extracts HTTP header values.

6. Request Body

  • Use @RequestBody (Spring) or JAX-RS to deserialize JSON/XML into a Java object (e.g., User user).

Status Codes & Error Handling

7. Status Codes

  • 201 Created → Resource successfully created.
  • 400 Bad Request → Invalid input from the client.
  • 401 Unauthorized → Missing or failed authentication.
  • 404 Not Found → Resource does not exist.

8. Exception Handling

Create global exception handlers in @ControllerAdvice (Spring) to return standardized error responses:

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity handleNotFound() { ... }

Advanced Topics

9. HATEOAS

Hypermedia links guide clients in navigating resources.

Example:

{
  "order": { "id": 1 },
  "_links": {
    "self": "/orders/1",
    "payment": "/orders/1/payment"
  }
}

10. Pagination

Use page, size, and sort parameters. Returns a Spring Data Page with metadata:

@GetMapping("/users")
public Page<User> getUsers(Pageable pageable) { ... }

11. Caching

  • ETag → Helps check if content has changed.
  • Cache-Control → Example: max-age=3600 (cache for 1 hour).
  • Spring: Use @Cacheable or ResponseEntity with headers.

12. Security

Use Spring Security with OAuth2/JWT.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { ... }

13. Versioning

  • URI-based: /v1/users (simpler but less RESTful).
  • Header-based: Accept: application/vnd.myapi.v1+json (cleaner URIs).

Frameworks & Tools

14. Spring Boot Controller

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping
    public List<User> getUsers() { ... }
}

15. Testing

Use @SpringBootTest with TestRestTemplate or MockMvc:

mockMvc.perform(get("/users")).andExpect(status().isOk());

16. OpenAPI/Swagger

Add springdoc-openapi dependency in your build file. Annotate endpoints with @Operation and @ApiResponse.

Scenario-Based Answers

17. Library API Design

  • Resources: Book, Member
  • Endpoints:
    • GET /books → List books
    • POST /books → Add a new book (201 Created)
    • PUT /books/{id} → Update a book (200 OK)
    • DELETE /books/{id}→ Remove a book

18. 415 Error - Unsupported Media Type

Occurs when the client sends data in a format not specified in @Consumes. Example: The server expects JSON but the client sends XML.

19. Idempotent Payments

Use a unique client-generated header idempotency-key. The server checks if the key has been processed before to prevent duplicate payments.

20. Rate Limiting

Use Bucket4j with Spring Interceptors to limit requests per IP.


Java interview questions on strings

Java interview questions on strings

Strings in Java are immutable, meaning once they are created, their values cannot be changed. If you plan to modify text frequently, String should not be used, as it creates new objects instead of modifying existing ones. Instead,StringBuffer orStringBuilder should be used for efficient string manipulation.

For effective string handling, this guide provides an introduction to common Java string interview questions, covering topics from beginner to advanced levels with explanations and example code.

1. Basics of Strings in Java

1. What is a String in Java?

A String is a sequence of characters. In Java, strings are objects of the String class, which is part of the java.lang package. Strings are immutable, meaning their values cannot be changed once created.

Example:

String str = "Hello, World!";
2. How do you create a String in Java?

A string in Java can be created in two ways:

  1. String Literal: Created using double quotes.
  2. Using the new Keyword: Created using the new operator.

Example:

// Method 1: String Literal
String str1 = "Hello";

// Method 2: Using new Keyword
String str2 = new String("Hello");
3. What is the difference between String, StringBuilder, and StringBuffer?
  • String: Immutable and thread-safe.
  • StringBuilder: Mutable and not thread-safe.
  • StringBuffer: Mutable and thread-safe.

Example:

String str = "Hello";
StringBuilder sb = new StringBuilder("Hello");
StringBuffer sbf = new StringBuffer("Hello");
4. How do you find the length of a String?

Use the length() method of the String class.

Example:

String str = "Hello";
System.out.println(str.length()); // Output: 5

2. String Manipulation

5. How do you reverse a String in Java?

You can reverse a String using StringBuilder or by iterating through the characters.

Example:

// Using StringBuilder
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: olleH
6. How do you check if a String is a palindrome?

A palindrome is a string that reads the same forward and backward.

Example:

public static boolean isPalindrome(String str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
7. How do you remove whitespace from a String?

Use the replaceAll() method with a regular expression.

Example:

String str = " Hello, World! ";
String trimmed = str.replaceAll("\\s", "");
System.out.println(trimmed); // Output: Hello,World!

3. String Comparison

8. How do you compare two Strings in Java?

Use the equals() method for content comparison and == for reference comparison.

Example:

String str1 = "Hello";
String str2 = new String("Hello");
System.out.println(str1.equals(str2)); // Output: true (content comparison)
System.out.println(str1 == str2); // Output: false (reference comparison)
9. What is the difference between equals() and equalsIgnoreCase()?
  • equals(): Compares two strings for an exact content match.
  • equalsIgnoreCase(): Compares two strings ignoring case differences.

Example:

String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equals(str2)); // Output: false
System.out.println(str1.equalsIgnoreCase(str2)); // Output: true

4. String Conversion

10. How do you convert a String to an integer?

Use the Integer.parseInt() method.

Example:

String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123
11. How do you convert an integer to a String?

Use theInteger.toString() method or concatenation with an empty string.

Example:

int num = 123;
String str1 = Integer.toString(num);
String str2 = "" + num;
System.out.println(str1); // Output: 123
System.out.println(str2); // Output: 123
12. How do you convert a String to a character array?

Use the toCharArray() method.

Example:

String str = "Hello";
char[] charArray = str.toCharArray();
for (char c : charArray) {
    System.out.println(c);
}

5. Advanced String Questions

13. How do you find the first non-repeated character in a String?

Use aLinkedHashMap to maintain the order of characters and count their occurrences.

Example:

import java.util.LinkedHashMap;
import java.util.Map;

public static char firstNonRepeatedChar(String str) {
    Map<Character, Integer> map = new LinkedHashMap<>();
    for (char c : str.toCharArray()) {
        map.put(c, map.getOrDefault(c, 0) + 1);
    }
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        if (entry.getValue() == 1) {
            return entry.getKey();
        }
    }
    return '\0'; // No non-repeated character found
}
14. How do you count the number of words in a String?

Split the string by spaces and count the resulting array's length.

Example:

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


Arrays programming interview questions in Java for experienced

 Java Array Interview Questions for Experienced

Arrays are cornerstone of programming & understanding them thoroughly is key to excelling in technical interviews. 

Whether you're just starting out or are an experienced Java developer, it's crucial to be familiar with how arrays work in Java. In this guide, we'll walk through common Java array interview questions, from basic to advanced, complete with explanations and code examples.

  1. Basic Array Questions
  2. Array Manipulation Questions
  3. Searching and Sorting Questions
  4. Multidimensional Array Questions
  5. Advanced Array Questions
  6. Tips for Array Interviews

1. Basic Array Questions

1. What is an Array in Java?

An array in Java is a container object that holds a fixed number of values of a single type. Once created, the size of the array cannot be changed.

Example:

int[] numbers = new int[5]; // Array of 5 integers

2. How do you declare and initialize an array in Java?

You can declare and initialize arrays in several ways:

Example:

// Method 1: Declare and initialize separately
int[] numbers = new int[3];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;

// Method 2: Declare and initialize in one line
int[] numbers = {1, 2, 3};

3. What is the default value of an array in Java?

  • For numeric types (e.g., int, double), the default value is 0.
  • For boolean, the default value is false.
  • For object types (e.g.,String), the default value is null.

Example:

int[] numbers = new int[3];
System.out.println(numbers[0]); // Output: 0

4. How do you find the length of an array?

Use the length property of the array.

Example:

int[] numbers = {1, 2, 3};
System.out.println(numbers.length); // Output: 3

2. Array Manipulation Questions

5. How do you reverse an array in Java?

Reversing an array can be done by swapping the elements from both ends towards the center.

Example:

public static void reverseArray(int[] arr) {
    int start = 0;
    int end = arr.length - 1;
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

6. How do you find the largest and smallest element in an array?

To find the largest and smallest element, iterate through the array and keep track of the current minimum and maximum values.

Example:

public static void findMinMax(int[] arr) {
    int min = arr[0];
    int max = arr[0];
    for (int num : arr) {
        if (num < min) min = num;
        if (num > max) max = num;
    }
    System.out.println("Min: " + min + ", Max: " + max);
}

program 7. How do you remove duplicates from an array?

Use a HashSet to automatically remove duplicates, as it does not allow duplicate elements.

Example:

import java.util.HashSet;

public static int[] removeDuplicates(int[] arr) {
    HashSet<Integer> set = new HashSet<>();
    for (int num : arr) {
        set.add(num);
    }
    int[] result = new int[set.size()];
    int i = 0;
    for (int num : set) {
        result[i++] = num;
    }
    return result;
}

3. Searching and Sorting Questions

8. How do you search for an element in an array?

You can use linear search for unsorted arrays or binary search for sorted arrays.

Linear Search Example:

public static int linearSearch(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1; // Not found
}

Binary Search Example:

public static int binarySearch(int[] arr, int target) {
    int left = 0;
    int 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; // Not found
}

9. How do you sort an array in Java?

You can use the Arrays.sort() method, or implement different sorting algorithms such as Bubble Sort or Quick Sort.

Example:

import java.util.Arrays;

int[] numbers = {5, 2, 9, 1, 5};
Arrays.sort(numbers); // Sorts the array in ascending order

4. Multidimensional Array Questions

10. How do you declare and initialize a 2D array?

A 2D array is essentially an array of arrays. Here's how you declare and initialize one.

Example:

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

program 11. How do you traverse a 2D array?

You can traverse a 2D array using nested loops for rows and columns.

Example:

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

5. Advanced Array Questions

program 12. How do you find the second largest element in an array?

You can find the second largest element by iterating through the array and keeping track of the two largest values.

Example:

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

program 13. How do you find the missing number in an array of integers from 1 to N?

You can use the mathematical formula for the sum of the first N natural numbers and compare it to the actual sum of the elements in the array.

Example:

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

Program 14. How do you find duplicate elements in an array?

Using a HashSet, you can detect duplicate elements by checking if a value already exists in the set.

Example:

import java.util.HashSet;

public static void findDuplicates(int[] arr) {
    HashSet<Integer> set = new HashSet<>();
    for (int num : arr) {
        if (!set.add(num)) {
            System.out.println("Duplicate: " + num);
        }
    }
}

6. Tips for Array Interviews

  1. Master the Basics: Be comfortable with array declaration, initialization, and traversal.
  2. Practice Common Problems: Focus on problems like searching, sorting, and removing duplicates.
  3. Optimize Your Code: Aim to improve both time and space complexity when solving problems.
  4. Test Edge Cases: Don't forget to consider edge cases like empty arrays or arrays with one element.

Arrays are  foundational concept in Java, and understanding them is crucial for performing well in technical interviews. By practicing the questions and code examples provided in this guide, you'll be well-prepared for any array-related challenge that comes your way. 

Arrays programming Interview questions in Java for freshers

Java Programming Interview Questions for freshers

  1. What is Java Array?
    It refers to a variable-size, ordered collection whose elements have the identical type.

  2. What are the types of Java arrays?
    Single-dimensional arrays (for example, of type int[] arr = new int[5]) and multi-dimensional arrays (e.g.,int[][] arr = new int[3][3].

  3. How do you initialize an array in Java?
    Use either int[] arr = {1, 2, 3, 4, 5}; (remember the semicolon) or int[] arr = new int[5];.

  4. What is the default value of an array in Java?
    Numeric types default to 0, boolean to false, and reference types such as an object's field value through a NULL pointer exception error.

  5. Is the size of an array in Java changeable after initialization?
    No! An array has no dynamic conversion and will always be the same from the day it is initialized until the end.

  6. What's the difference between Java array and ArrayList?

  7. How do you copy an array in Java?
    You can use System.arraycopy(), Arrays.copyOf(), or the clone() method.

  8. How do you sort an array in Java?
    Arrays.sort(array);

  9. How do you search for an element in an array?
    Use a loop or Arrays.binarySearch(array, key); for sorted arrays.

  10. How do you convert an array to an exact corresponding index in a List?
    Arrays.asList(array); A method that returns a fixed-size list backed by the array.

Java Interview Programming Questions

  1. Write a Java program to reverse a string.

    public class ReverseString {
      public static void main(String[] args) {
        String str = "Hello";
        String reversed = new StringBuilder(str).reverse().toString();
        System.out.println("Reversed String: " + reversed);
      }
    }
    
  2. Write a Java program to test a number for prime status.

    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;
      }
      public static void main(String[] args) {
        int number = 29;
        System.out.println(number + " is prime: " + isPrime(number));
      }
    }
    
  3. Write a Java program to find the largest number in an array.

    public class LargestElement {
      public static void main(String[] args) {
        int[] arr = {10, 20, 5, 8, 30};
        int max = arr[0];
        for (int num : arr) {
          if (num > max) {
            max = num;
          }
        }
        System.out.println("Largest Element: " + max);
      }
    }
    
  4. Write a Java program to delete duplicates from an array.

    import java.util.HashSet;
    import java.util.Arrays;
    public class RemoveDuplicates {
      public static void main(String[] args) {
        int[] arr = {1, 2, 3, 1, 2, 4, 5};
        HashSet<Integer> set = new HashSet<>();
        for (int num : arr) {
          set.add(num);
        }
        System.out.println("Array without duplicates: " + set);
      }
    }
    
  5. Write a Java program to find the missing number in an array of 1 to N.

    public class MissingNumber {
      public int findMissing(int[] arr, int n) {
        int sum = n * (n + 1) / 2;
        for (int num : arr) {
          sum -= num;
        }
        return sum;
      }
      public static void main(String[] args) {
        int[] arr = {1, 2, 4, 5, 6};
        int n = 6;
        System.out.println("Missing number: " + new MissingNumber().findMissing(arr, n));
      }
    }
    


Top 65 java interview questions on collections

1.What Is The Java Collections Framework (JCF)?

Interfaces and classes for storing data in ways compatible with data structures (that is, memory-efficient).

2.What Are The Primary Interfaces In The Java Collections Framework?

Collection, List, Set Queue Map and all of their subinterfaces.

3.What is the difference between Collection and Collections in Java?

Collection: the root interface for data structures.

Collections: a utility class that has static methods.

4.Is There A difference among List, Set, and Map*

List: Sequential order, no duplication.

Set: No order, no duplication.

Map: Key value pairs--like a dictionary house keys in general practice--with unique keys.

5.What are the key differences between ArrayList and LinkedList?

ArrayList: Faster access to random locations but slow in the middle of things.

LinkedList: Quick updates anywhere on list, slower access than with less predictable block sizes.

6.What is the difference between HashSet, LinkedHashSet, and TreeSet?

HashSet: Unordered, fast.

LinkedHashSet: Maintains order of insertion (or addition)

TreeSet: A set in alphabetical or other order, depending on the key.

7.How Does HashMap Work in Java?

The key-value storage system uses buckets and hashing to handle collisions. With Java 8, it has been modified to handle collisions (e.g. using red-black trees).

8.What is the default capacity of an ArrayList?

10 (increases by 50% when full).

9.What are fail-fast and fail-safe iterators and how do they differ?

Fail-fast: throws a ConcurrentModificationException if modified during iteration

Fail-safe: permits modification (CopyOnWriteArrayList, ConcurrentHashMap).

10.Why is HashSet faster than TreeSet?

HashSet uses hashing (O(1)), while TreeSet uses a Red-Black tree (O(log n)).

11.What is the internal implementation of HashMap?

Behind the scenes: It's an array of buckets with linked lists for collision handling.

12.Why is the load factor in HashMap set to 0.75?

It's a trade-off between memory efficiency and speed (reduces rehashing costs).

13.What is the difference between Comparable and Comparator?

Comparable is for natural ordering (compareTo).

Comparator only does sorting (compare).

14.How Does ConcurrentHashMap Work Internally?

SEGMENT LOCKING. (Java 7), BUCKET LEVEL LOCKING. (Java 8) allow instantaneous access

15.What is the difference between synchronized and concurrent collections?

Synchronized: Slower, blocks threads (eg.Collections.synchronizedList). Concurrent: optimized for chucks of work (ConcurrentHashMap).

16.How does CopyOnWriteArrayList work?

When the list is modified, it creates a new copy for every call (which makes the program thread-safe). This causes a great shortfall in memory usage efficiency.

17.What is the difference between Hashtable and HashMap?

Hashtable: Hashtable is synchronized (slow).

HashMap: HashMap is not synchronized (faster).

18.Why should you override hashCode() and equals() in HashMap keys?

So that you act upon both the correct key and never retrieve any duplicates

19.How to make an ArrayList thread-safe?

Use Collections.synchronizedList() or CopyOnWriteArrayList.

20.What are weak keys in WeakHashMap?

If there are no strong references left, the keys are eligible for garbage collection. This is true of all of them in a WeakHashMap.

Advanced Level Questions

21.What are the differences between ConcurrentHashMap and SynchronizedMap?

ConcurrentHashMap: More efficient, with bucket-level locking. SynchronizedMap: locks entire collection.

22.How Does TreeMap Maintain Ordering?

It uses a Red-Black Tree, which orders elements in natural/comparator order.

23.How Does LinkedHashMap Maintain Insertion Order?

LinkedHashMap: Hash table and double chain.("

24.What Does remove() do in Iterator?

It Removes the last element returned by Iterator and Disallows exceptions when something goes wrong. It just bites! (So to speak.)

25.What is PriorityQueue, and how does it work?

A queque based on a minimum value of min-heap orders elements naturally in the queue or by comparing at run-time

26.What is BlockingQueue, and how does it help in multithreading?

It's one of the series of Implementations BlockingQueues: Full.put() will block until space is available, and (take() Empty BC) ditto for take. only blocking queue

27.What are IdentityHashMap and EnumMap?

IdentityHashMap: uses object identity values for keys. EnumMap: optimized to work with enum keys.

28.How Does The computeIfAbsent() Method Work In Java 8?

Adds value to a map only if key is missing.

29.How Does The Spliterator Work?

In parallel processing mode of a series of chunks

30.What are the performance considerations when choosing between different collection types?

Choose ArrayList for fast read, LinkedList for frequent inserts/deletes, Hash stark areas, Terence <>TreeSet for sorted data.

31. What is the difference between Collection and Collections in Java?

  • Collection: The collection framework is the root of the List, Set, and Queue classes.
  • Collections: A utility class, such as sort() or reverse(), that holds only static methods.

32. How is Iterator different from ListIterator?

  • Iterator: Only supports forward traversal.
  • ListIterator: You can go forwards and backwards. You can change the elements on the list.

33. What are Java′s different kinds of queues?

  • PriorityQueue: Sorts by priority.
  • Deque: A double-ended queue.
  • BlockingQueue: Supports thread-safe operations. Examples include: ArrayBlockingQueue, LinkedBlockingQueue.

34. What’s the difference between a Stack and a Queue?

  • Stack: Last In, First Out.
  • Queue: First In, First Out.

35. What is an Enumeration in Java?

  • A way to iterate over collections. It is used for iterating through collections (e.g., Vector, Hashtable).
  • A substitute for Iterator and ListIterator used in modern Java.

36. What is a LinkedHashMap in Java?

  • A HashMap with insertion order of elements on a doubly linked list.

37. What happens when a HashMap's capacity is exceeded?

  • It makes new changes (doubling capacity), rehashes elements, and puts them into new buckets.

38. How do you synchronize a List or a Set?

  • Use Collections.synchronizedList(myList or Collections.synchronizedSet(mySet).

39. What are the differences between a HashMap and a TreeMap?

  • HashMap: Not in order. O(1) lookup time.
  • TreeMap: The order of elements is O(log n) lookup time (Red-Black Tree).

40. What are the differences between Arrays and ArrayLists? - Array: Fixed size, faster to access. - ArrayList: Dynamic resizing, slower than the array but flexible.

41. How does the remove(Object o) method work in a Collection? - Removes the first occurrence.

42. What happens when two objects have the same hashCode() but are not equal? - One bucket of the same number holds the elements as a tree or a linked list.

43. What is a NavigableSet in Java? - It is a SortedSet with methods like lower(), higher(), ceiling(), and floor().

44. What’s the difference between poll() and remove() in a Queue? - poll(): This removes and returns the header element. When the queue is empty, it returns null. - remove(): Same as poll() but throws a NoSuchElementException if the queue is empty.

45. What's the point of the containsKey() and containsValue() methods in Map? - containsKey(): Makes certain that a given key exists. - containsValue(): Checks to see if a value exists (slower because it must search through all values).

46. What’s the difference between peek(), poll(), and remove() in a Queue? - peek(): Returns the head without removing it. - poll(): Returns the head, removes it, and returns null if empty. - remove(): Similar to poll() except if empty, it throws a NoSuchElementException.

47. What's the difference between IdentityHashMap and HashMap? - IdentityHashMap uses reference equality (==), while HashMap uses .equals().

48. How does TreeMap sort its elements? - It uses natural ordering (Comparable) or a custom comparator (Comparator).

49. What is a WeakHashMap in Java? - A HashMap where the keys are weak references and are removed from the map when not referenced any further.

50. What exactly is a ConcurrentLinkedQueue? - It's a thread-safe, non-blocking queue that relies on lock-free linked nodes to operate.

51. What are the advantages of ConcurrentHashMap over HashMap? - It uses segment-level locking in Java 7 and bucket-level locking in Java 8. - Multiple threads can make changes to different segments simultaneously.

52. What does Java 8 do to improve the performance of HashMap? - It uses balanced trees (Red-Black trees) instead of linked lists if the bucket size is > 8.

53. What are ConcurrentSkipListMap and TreeMap’s differences? - ConcurrentSkipListMap: A thread-safe sorted map that relies on a Skip List. - TreeMap: A Red-Black Tree that is not thread-safe.

54. What is BlockingQueue and its implementations? - A thread-blocking queue that fills the threads to keep the water level constant or empty. Examples include: LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue.

55. What is the difference between SoftReference, WeakReference, and PhantomReference? - SoftReference: Collected only when memory is low. - WeakReference: Collected at the next garbage collection if it has no strong references. - PhantomReference: Used for finalization and releasing resources.

56. How and when does CopyOnWriteArrayList give you thread safety? - After a list is changed, it copies the old list so that no thread can modify it while working with the new list.

57. What is the difference between TreeSet and HashSet? - TreeSet: Ordered, implemented using Red-Black Tree (O(log n) time). - HashSet: Unordered, using Hashing (O(1) time).

58. What is a BitSet? - An efficient bit-sponging tool.

59. What is the forEach() method in Java 8 collections? - It uses lambda expressions to iterate over a collection (e.g., list.forEach(System.out::println)).

60. What's the difference between unmodifiable and immutable collections? - Unmodifiable: A wrapper that prevents any changes (e.g., Collections.unmodifiableList()). - Immutable: Can't be changed in any way (e.g.,List.of() ,Set.of(0).

61. Why are HashMap keys immutable in Java? 
- To prevent inconsistent behavior from 'hashCode' changes.

62. What is a ConcurrentHashMap compute() method? - It allows atomic updates of the value associated with a key. (e.g., map.compute(key, (k, v) -> v + 1)).

63. How does the parallelStream() method in Java 8 work? - Splits the collection into segments and processes them in parallel using the Fork/Join system.

64. Why is EnumMap faster than HashMap for Enums? - It uses an array-based internal storage system, avoiding the overhead of computing hashes.

65. What’s the difference between TreeSet and LinkedHashSet? -

  TreeSet: Ordered set (O(log n)). 

- LinkedHashSet:Maintains insertion order (O(1)).


man command in linux

 Learn man Command in Linux: Start Using Linux Manual Pages the Right Way

The true power of Linux lies in the command-line interface. Whether you're a complete beginner or an advanced user, man will be one of the most important tools in your Linux toolbox. Follow this blog post to find out what the man command is, how to use it, and how to work effectively with it.

 What is the man Command?

The manual command, or man for short, prints out documentation in the form of manual pages for other commands, utilities, and functions on a Linux system. These manual pages give a detailed explanation of the usage, options, and examples associated with a command.

If you want to know how to use the ls command, for example, simply type:

man ls

This will display the ls manual page, explaining what the command does, how to use it, available options, and examples.

 Why is the man Command Important?

  • Built-in Documentation: The man command provides detailed, comprehensive documentation covering nearly every Linux command and utility.
  • No Internet Required: Manual pages are stored locally, so you don't need an internet connection.
  • Standard Format: Manual pages follow a consistent structure, making it easy to find the information you need.
  • Learn As You Go: You can explore new commands without relying on external materials.

 How to Use the man Command

The basic syntax of the man command is:

man [options] <command_name>

For example:

man grep

 Navigating Manual Pages

You can navigate through a manual page using the following keys:

  • Arrow Keys: Move up and down within the document.
  • Spacebar: Advance one page forward.
  • Enter: Move one line forward.
  • b: Move one page backward.
  • /search_term: Search for a specific term (e.g., /pattern).
  • n: Go to the next occurrence of the search term.
  • N: Go to the previous occurrence of the search term.
  • q: Quit the manual page.

 Sections of Manual Pages

Manual pages are divided into sections, each focusing on different types of content. Here are the standard sections:

  • Section 1: General user commands (e.g., ls, grep).
  • Section 2: System calls (e.g., open, read).
  • Section 3: Library functions (e.g., printf, malloc).
  • Section 4: Special files (e.g., /dev).
  • Section 5: File formats and conventions (e.g., /etc/passwd).
  • Section 6: Games and screensavers.
  • Section 7: Miscellaneous (e.g., man, bash).
  • Section 8: System administration commands (e.g., iptables, fdisk).

To view a specific section of a manual page:

man <section_number> <command_name>

For example:

man 5 passwd

 Advanced Usage of the man Command

CommandDescription
man -k <keyword>Search for manual pages related to a keyword
man -a <command>Display all available sections for a command
man <section_number> <command>View a specific section of a command
man -w <command>Show the file path of a manual page
man -f <command>Display a short description of a command (same as whatis)

 1. Search for Manual Pages

man -k <keyword>

For example:

man -k network

  2. Display All Sections

man -a <command_name>

For example:

man -a passwd

 3. View a Specific Section

man <section_number> <command_name>

For example:

man 3 printf

 4. Display the Location of Manual Pages

Use the -w option to get the location of a manual page on your system:

man -w <command_name>

For example:

man -w ls

 5. View a Short Description

Use the -f option to display a brief description of a command:

man -f <command_name>


This is the same as using the whatis command.

 Tips and Tricks

1. Use man man: To learn more about the man command itself, type:
   man man
2. Learn less Commands: The man pages are displayed using the less pager. Learning less commands will improve your navigation.
3. Customize Output: Set environment variables like MANPAGER and PAGER to change how man operates.
4. Install Missing Manual Pages: If a manual page is missing, install it using a package manager.
   On Debian-based systems:
   sudo apt install manpages-dev
5. Use tldr for Quick Examples: If man pages are too lengthy, try the tldr command for concise explanations:
   tldr <command_name>

The man command is an essential tool for working with Linux. Its rich and accurate documentation makes it easy for users to master their command-line skills. Whether you're a beginner or an experienced Linux user, mastering man will significantly enhance your productivity and confidence.


Select Menu