core java

Find all even numbers from a list

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class Main {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);


        List<Integer> evenNumbers = numbers.stream()

            .filter(n -> n % 2 == 0) // The "Even Number" Predicate

            .collect(Collectors.toList());


        System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]

    }

}

----------------------------------------------------------------------------------------------------------

    Starts with 1


package practice;


import java.util.Arrays;

import java.util.Comparator;

import java.util.List;

import java.util.stream.Collectors;


public class Digit1 {

public static void main(String[] args) {

List<Integer> numbers= Arrays.asList(1,2,3,12,32,45,123,453,1243,5435,123,3,5,41,13,14,15,16,1,7,17);

List<Integer> starts1= numbers.stream()

   .map(String::valueOf)

   .filter(s->s.startsWith("1"))

   .map(Integer::parseInt)

   .collect(Collectors.toList());

System.out.println(starts1);

//filter(numbers->numbers).collect(Collectors.toList());

}

}

------------------------------------------------------------------------------------------------
To upper case

package practice;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Upp {

public static void main(String[] args) {
List<String> names=Arrays.asList("ravi", "Sranya", "sara","tara");
List<String> upper= names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upper);
}
}
------------------------------------------------------------------------------------------------------------------
Remove duplicates

package practice;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveDup {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,1,2,3,4,5,6,7,8,89,6,5);
List<Integer> dis= numbers.stream().distinct().collect(Collectors.toList());
System.out.println(dis);
}
}

-----------------------------------------------------------------------------------------------------------------------
MAX MIN

package practice;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;

public class MaxMin {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,1,2,3,4,5,6,7,8,89,6,5);
Optional<Integer> maxn= numbers.stream().max(Comparator.naturalOrder());
System.out.println(maxn.get());
Optional<Integer> min = numbers.stream().min(Comparator.naturalOrder());
System.out.println(min.get());
}
}

-------------------------------------------------------------------------------------------------------------------------

Sum of all

package practice;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class SumOfAll {

public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,7,8);
int summ= numbers.stream().mapToInt(Integer::intValue).sum();
}
}
--------------------------------------------------------------------------------------------------------------------------

Below are crisp, interview-ready answers for the 68 high-probability Collections questions.
They are written exactly at the depth expected for a 3+ years TCS Java Backend interview — not too shallow, not over-theoretical.

You can revise directly from this.

Max from numbers.

Optional<Integer> max = numbers.stream()

    .max(Integer::compareTo);


Find Duplicates

List<Integer> duplicates = numbers.stream()

    .filter(i -> Collections.frequency(numbers, i) > 1)

    .distinct()                           // remove duplicate duplicates themselves

    .collect(Collectors.toList());


remove duplicates

List<Integer> unique = numbers.stream()

    .distinct()

    .collect(Collectors.toList());


Frequenct of character

String str= "hello welcome to ravoi";

Map<Character, Long> frequency = 

    str.chars()                    // IntStream

       .mapToObj(ch -> (char) ch)  // Stream<Character>

       .collect(Collectors.groupingBy(ch -> ch,Collectors.counting() ));

// Print result

frequency.forEach((ch, count) -> 

    System.out.println("'" + ch + "' → " + count)); }



max salary of employee


Optional<Employee> maxsal= employees.stream().sorted(Comparator.comparingInt(Employee::getSalary).reversed()).findFirst();



List to MAp

Map<Long, Person> map = people.stream()

    .collect(Collectors.toMap(

        Person::getId,           // KeyMapper: how to get the key

        Function.identity()      // ValueMapper: the whole object becomes the value

    ));



Group employee by department

Map<String, List<Employee>> byDept = employees.stream()

            .collect(Collectors.groupingBy(Employee::getDepartment));



JAVA COLLECTIONS – 90% ASKED QUESTIONS WITH ANSWERS


A. BASICS

1. What is Collection Framework?

A unified architecture of interfaces, implementations, and algorithms to store, manipulate, and retrieve groups of objects efficiently.


2. Difference between Collection and Collections?

  • Collection → Interface (List, Set, Queue)

  • Collections → Utility class with static methods like sort(), reverse(), synchronizedList()


3. Difference between List, Set, Map?

  • List → Allows duplicates, maintains order

  • Set → No duplicates

  • Map → Key–value pairs, keys are unique


4. Why Map is not part of Collection hierarchy?

Because Collection works on single elements, while Map works on key–value pairs. Their contracts are fundamentally different.


5. Core interfaces in Collection Framework?

  • Iterable

  • Collection

    • List

    • Set

    • Queue
      (Map is separate)


6. Array vs ArrayList?

  • Array → Fixed size, supports primitives

  • ArrayList → Dynamic size, objects only


7. ArrayList vs LinkedList?

  • ArrayList → Fast random access

  • LinkedList → Fast insert/delete


8. ArrayList vs Vector?

  • ArrayList → Not synchronized

  • Vector → Synchronized, slower, legacy


9. Why ArrayList is not synchronized?

To improve performance. Synchronization is optional and can be added externally.


10. How to make ArrayList thread-safe?

  • Collections.synchronizedList()

  • CopyOnWriteArrayList


B. ARRAYLIST & LINKEDLIST

11. How does ArrayList work internally?

Uses a dynamic array. When capacity is exceeded, a new array is created and elements are copied.


12. Default capacity of ArrayList?

  • Initially 0

  • On first add → 10


13. How ArrayList grows?

New capacity = old capacity × 1.5


14. Time complexity in ArrayList?

  • get → O(1)

  • add → O(1) amortized

  • remove → O(n)


15. How LinkedList works internally?

Uses doubly linked list (previous + next references).


16. Why LinkedList insertion is faster?

No shifting of elements; only pointer updates.


17. When to use LinkedList?

When frequent insertions/deletions are required.


18. Difference between ArrayList and LinkedList?

ArrayList → index-based
LinkedList → node-based


C. SET

19. HashSet vs LinkedHashSet vs TreeSet?

  • HashSet → No order

  • LinkedHashSet → Insertion order

  • TreeSet → Sorted order


20. How HashSet works internally?

Internally uses a HashMap, storing elements as keys.


21. How HashSet prevents duplicates?

Uses hashCode() + equals().


22. Can HashSet store null?

Yes, only one null.


23. Why TreeSet does not allow null?

Uses compareTo() / Comparator, which throws NullPointerException.


24. If compareTo() returns 0?

Elements are treated as duplicates.


D. HASHMAP (MOST IMPORTANT)

25. What is HashMap?

A Map implementation that stores data as key–value pairs using hashing.


26. How HashMap works internally?

  1. hashCode of key

  2. Calculate index

  3. Store in bucket

  4. equals() check for collision

  5. Store or replace value


27. Default capacity & why 16?

  • Default: 16

  • Power of 2 → efficient index calculation


28. Load factor?

Threshold to resize map. Default = 0.75


29. What is rehashing?

Increasing capacity and redistributing entries.


30. When rehashing happens?

When size > capacity × load factor.


31. Collision handling?

Uses Linked List (Java 7)
Uses Linked List → Red-Black Tree (Java 8)


32. Same hashCode, different equals?

Stored in same bucket as separate entries.


33. Why equals() after hashCode()?

To confirm exact key match inside same bucket.


34. Nulls in HashMap?

  • 1 null key

  • Multiple null values


35. Why HashMap is not thread-safe?

No synchronization → race conditions possible.


36. Why immutable keys?

Hash code doesn’t change → avoids lookup failure.


37. HashMap issue in Java 7?

Worst case lookup = O(n) due to linked list.


38. Java 8 improvement?

Buckets converted to Red-Black Tree.


39. When list converts to tree?

When bucket size > 8 and capacity ≥ 64.


40. Why Red-Black Tree?

Guaranteed O(log n) lookup.


E. MAP VARIANTS

41. HashMap vs Hashtable?

Hashtable is synchronized, legacy, no nulls.


42. HashMap vs ConcurrentHashMap?

ConcurrentHashMap is thread-safe and high-performance.


43. HashMap vs LinkedHashMap?

LinkedHashMap maintains insertion/access order.


44. HashMap vs TreeMap?

TreeMap maintains sorted order.


45. Why ConcurrentHashMap does not allow null?

To avoid ambiguity during concurrent reads.


46. How ConcurrentHashMap is thread-safe (Java 8)?

Uses CAS + synchronized blocks, no full locking.


F. ITERATOR & CONCURRENCY

47. Fail-fast?

Throws ConcurrentModificationException.


48. Fail-safe?

Works on copy; no exception.


49. Why ConcurrentModificationException?

Structural modification during iteration.


50. Iterator vs ListIterator?

ListIterator supports bidirectional traversal.


51. Can you modify collection during iteration?

No, except using Iterator.remove().


52. How to modify safely?

Use Iterator remove or concurrent collections.


G. equals() & hashCode()

53. Contract?

Equal objects → same hashCode.


54. equals overridden but not hashCode?

HashMap lookup fails.


55. Unequal objects same hashCode?

Yes, allowed.


56. hashCode changes after insertion?

Object becomes unreachable in HashMap.


H. SORTING

57. Comparable vs Comparator?

Comparable → natural ordering
Comparator → custom ordering


58. How TreeSet sorts?

Uses compareTo() or Comparator.


59. compareTo inconsistent with equals?

Violates Set contract → duplicates allowed.


60. Sort List of objects?

Using Collections.sort() or Java 8 streams.


I. REAL-TIME SCENARIOS

61. Remove duplicates from List?

Convert to Set.


62. Frequency of elements?

Use HashMap.


63. Sort employees by salary?

Comparator / Stream sorted().


64. First non-repeated character?

LinkedHashMap.


65. Convert List to Map?

Use Stream collect().


66. Iterate Map?

entrySet, keySet, values.


67. Fast search collection?

HashMap / HashSet.


68. Thread-safe collection?

ConcurrentHashMap / CopyOnWriteArrayList.


FINAL TRUTH

If you revise only this, you cover ~90% of TCS Collections questions.

If you want next:

  • One-page last-minute revision

  • Mock interview (Q → expected answer)

  • Collections + Streams combined revision

Tell me how many hours left — I’ll optimize further.



Below is a focused and comprehensive list of Java 8 interview questions with clear, interview-ready answers, tailored for 2–5 years (especially 3+ years) Java backend developers. These are the most frequently asked questions in real interviews (TCS, Infosys, Wipro, Cognizant, Accenture, CGI, etc.).


1. What are the main features introduced in Java 8?

Answer:
Java 8 introduced functional programming concepts into Java.

Key features:

  • Lambda Expressions

  • Functional Interfaces

  • Stream API

  • Default and Static methods in interfaces

  • Optional class

  • Method References

  • New Date & Time API (java.time)

  • Nashorn JavaScript Engine (less common in interviews)


2. What is a Lambda Expression?

Answer:
A lambda expression is an anonymous function that provides a clear and concise way to implement a functional interface.

Syntax:

(parameters) -> expression

Example:

Runnable r = () -> System.out.println("Hello");

Benefits:

  • Reduces boilerplate code

  • Improves readability

  • Enables functional programming


3. What is a Functional Interface?

Answer:
A functional interface contains exactly one abstract method.

Examples:

  • Runnablerun()

  • Callablecall()

  • Comparatorcompare()

  • Predicate<T>test(T t)

  • Function<T, R>apply(T t)

  • Consumer<T>accept(T t)

  • Supplier<T>get()

Annotation:

@FunctionalInterface

(Compile-time safety)


4. Difference between Lambda Expression and Anonymous Class

LambdaAnonymous Class
No class creationCreates a class
Less codeMore boilerplate
No this ambiguitythis refers to inner class
Faster executionSlower

5. What is Stream API?

Answer:
Stream API is used to process collections of data in a functional and declarative manner.

Stream does NOT store data; it processes data from a source.


6. Explain Stream Pipeline

A stream works in three stages only:

  1. Source

    • Collection, Array, I/O

  2. Intermediate Operations

    • filter(), map(), sorted()

  3. Terminal Operation

    • forEach(), collect(), reduce()

Example:

list.stream()
    .filter(n -> n > 10)
    .map(n -> n * 2)
    .forEach(System.out::println);

7. Difference between map() and flatMap()

map()flatMap()
One-to-one mappingOne-to-many mapping
Output is Stream of StreamsOutput is single Stream

Example:

list.stream().map(s -> s.split(""));
list.stream().flatMap(s -> Arrays.stream(s.split("")));

8. Difference between filter() and map()

  • filter() → used for condition

  • map() → used for transformation


9. What is Optional?

Answer:
Optional is a container object used to avoid NullPointerException.

Common methods:

  • isPresent()

  • orElse()

  • orElseGet()

  • orElseThrow()

  • ifPresent()

Example:

Optional<String> name = Optional.ofNullable(value);
System.out.println(name.orElse("Default"));

10. Difference between orElse() and orElseGet()

  • orElse() → always executes argument

  • orElseGet() → executes only if value is absent (lazy)


11. What are Method References?

Answer:
Method reference is a shorthand syntax of lambda expression.

Types:

  1. Static method → ClassName::method

  2. Instance method → object::method

  3. Constructor → ClassName::new

Example:

list.forEach(System.out::println);

12. What is forEach()?

Answer:
A terminal operation used to iterate over elements.

Difference:

  • Collection.forEach() → external iteration

  • Stream.forEach() → internal iteration


13. Difference between findFirst() and findAny()

  • findFirst() → returns first element

  • findAny() → returns any element (better for parallel streams)


14. What is reduce()?

Answer:
Used to reduce stream elements to a single value.

Example:

int sum = list.stream().reduce(0, Integer::sum);

15. Difference between collect() and reduce()

  • reduce() → immutable reduction

  • collect() → mutable reduction (List, Set, Map)


16. Difference between Stream and ParallelStream

StreamParallelStream
Single threadMultiple threads
Order preservedOrder not guaranteed
Less overheadHigh overhead

Use parallel streams only for large datasets.


17. Can we reuse a Stream?

Answer:
No. A stream can be consumed only once.


18. Difference between Predicate, Function, Consumer, Supplier

InterfaceMethodPurpose
Predicatetest()Condition
Functionapply()Transformation
Consumeraccept()Consumes
Supplierget()Supplies

19. Default methods in Interface – Why needed?

Answer:
To add new methods to interfaces without breaking existing implementations.


20. New Date and Time API advantages

  • Immutable

  • Thread-safe

  • Clear separation (Date, Time, DateTime)

Classes:

  • LocalDate

  • LocalTime

  • LocalDateTime

  • ZonedDateTime


21. Common Java 8 Coding Questions (Very Important)

  • Find highest/lowest number

  • Find duplicate elements

  • Count frequency of characters

  • Sort map by values

  • Find second highest number

  • Group employees by department

  • Find max salary employee

  • Convert List to Map

  • Remove duplicates

  • Find first non-repeated character


22. Real Interview Tip (Important)

Interviewers expect:

  • Clear explanation

  • Why Java 8 was introduced

  • When NOT to use streams

  • Difference between traditional loops and streams


If you want, I can:

  • Give Java 8 coding questions with step-by-step explanation

  • Provide a Java 8 one-page interview cheat sheet

  • Create a Java 8 mock interview (Q&A format)

Tell me how you want to proceed.




Here are the **most frequently asked core Java interview questions** with **simple, easy-to-say answers** in plain English. These are the ones interviewers ask again and again in 2025–2026 (for freshers, 1–5 years experience, and even senior roles). I've kept explanations short, clear, and natural — the way you can speak confidently in an interview.


I've grouped them and numbered them like before.


### Core Java Fundamentals & OOP

1. **What are the main features of Java?**  

   Java is simple, object-oriented, platform-independent, secure, robust (strong error checking), supports multithreading, has automatic garbage collection, and is portable (write once, run anywhere).


2. **Why is Java platform-independent? Explain JDK, JRE, JVM.**  

   Java is platform-independent because source code (.java) compiles to bytecode (.class), and bytecode runs on any machine with a JVM.  

   - **JVM** (Java Virtual Machine): Runs the bytecode.  

   - **JRE** (Java Runtime Environment): JVM + libraries needed to run Java programs.  

   - **JDK** (Java Development Kit): JRE + tools like compiler (javac) to develop Java programs.


3. **Why is Java not 100% object-oriented?**  

   Because it has primitive types like int, float, boolean — these are not objects.


4. **What are the four pillars of OOP? Give simple examples.**  

   - **Encapsulation**: Hide data inside class (use private variables + public getters/setters).  

   - **Inheritance**: Child class gets features from parent (extends keyword).  

   - **Polymorphism**: Same method name does different things (method overriding or overloading).  

   - **Abstraction**: Show only what is needed, hide details (abstract class or interface).


5. **Difference between abstract class and interface?**  

   - Abstract class: Can have both abstract and normal methods, instance variables, constructors.  

   - Interface: Before Java 8 — only abstract methods. After Java 8 — can have default and static methods.  

   A class can extend only one abstract class but implement many interfaces.


6. **Can we override static, private, or final methods?**  

   No.  

   - Static: Belongs to class, not object → no overriding.  

   - Private: Not visible to child class.  

   - Final: Cannot be changed.


7. **Method overloading vs method overriding?**  

   - Overloading: Same method name, different parameters (in same class).  

   - Overriding: Same method name + same parameters (child class changes parent method).


8. **Difference between final, finally, finalize?**  

   - **final**: Keyword — variable (constant), method (cannot override), class (cannot extend).  

   - **finally**: Block after try-catch — always runs (cleanup like closing files).  

   - **finalize**: Method in Object class — called by garbage collector before destroying object (rarely used now).


9. **Why are Strings immutable in Java?**  

   For security (passwords), thread-safety, caching in String pool, and better performance.


10. **Difference between == and .equals()?**  

    - **==** : Checks if two references point to same memory (same object).  

    - **.equals()** : Checks content equality (you can override it, like in String).


### Memory, JVM & Garbage Collection

11. **Difference between Stack and Heap memory?**  

    - **Stack**: Fast, stores method calls, local variables (LIFO). Each thread has its own stack.  

    - **Heap**: Stores objects, shared by all threads. Garbage collected here.


12. **How does Garbage Collection work?**  

    JVM automatically frees memory from unused objects. It has young generation (Eden + Survivor) for short-lived objects and old generation for long-lived. Minor GC is fast, Major/Full GC is slower.


13. **What is String pool? How does intern() work?**  

    String pool is special part of heap for string literals (to save memory).  

    `intern()` brings string to pool if not already there and returns pooled reference.


### Multithreading & Concurrency

14. **What is multithreading? Difference between Thread and Runnable?**  

    Multithreading = multiple threads run at same time (better CPU use).  

    - Extend **Thread** class: Simple but limits inheritance.  

    - Implement **Runnable**: Better — allows extending another class.


15. **Difference between synchronized and ReentrantLock?**  

    - **synchronized**: Easy keyword, automatic lock release.  

    - **ReentrantLock**: More control (tryLock, timeout, fairness, interruptible).


16. **What is volatile keyword?**  

    Tells JVM not to cache variable — always read/write from main memory. Useful for visibility in multithreading (not atomicity).


17. **What is deadlock? How to prevent it?**  

    Deadlock = two threads wait forever for each other's lock.  

    Prevent: Lock in same order, use timeouts, avoid nested locks.


18. **Difference between wait(), notify(), notifyAll()?**  

    They work inside synchronized block.  

    - wait(): Thread releases lock and waits.  

    - notify(): Wakes one waiting thread.  

    - notifyAll(): Wakes all waiting threads.


### Collections Framework

19. **Difference between ArrayList and LinkedList?**  

    - **ArrayList**: Fast random access (get/set), slow insert/delete in middle.  

    - **LinkedList**: Fast insert/delete, slow random access.


20. **How does HashMap work internally?**  

    Uses array of buckets. Hash code → index → if collision, uses linked list (or tree if many). Load factor 0.75 → resize when full.


21. **Difference between HashMap, LinkedHashMap, TreeMap?**  

    - **HashMap**: No order.  

    - **LinkedHashMap**: Maintains insertion order.  

    - **TreeMap**: Sorted order (by key).


22. **What is fail-fast vs fail-safe iterator?**  

    - Fail-fast: Throws ConcurrentModificationException if collection changed during iteration (ArrayList, HashMap).  

    - Fail-safe: No exception, works on copy or allows changes (CopyOnWriteArrayList, ConcurrentHashMap).


### Exception Handling

23. **Difference between checked and unchecked exceptions?**  

    - Checked: Must handle or declare (throws) — e.g., IOException.  

    - Unchecked: Runtime, no need to handle — e.g., NullPointerException.


24. **Difference between throw and throws?**  

    - **throw**: Manually throw exception (throw new Exception()).  

    - **throws**: Declare method can throw exception.


25. **What is try-with-resources?**  

    Automatically closes resources (files, connections) after try block — no need for finally (Java 7+).


### Strings & Others

26. **Difference between String, StringBuilder, StringBuffer?**  

    - **String**: Immutable.  

    - **StringBuilder**: Mutable, not thread-safe, faster.  

    - **StringBuffer**: Mutable, thread-safe (synchronized), slower.


27. **What is autoboxing and unboxing?**  

    Automatic conversion: int → Integer (autoboxing), Integer → int (unboxing). Can cause performance issues in loops.


### Java 8+ Features

28. **What are lambda expressions?**  

    Short way to write anonymous methods (for functional interfaces). Example: `(a,b) -> a + b`


29. **What is Stream API?**  

    Processes collections in functional style (filter, map, reduce). Lazy — operations run only when terminal operation called.


30. **Difference between map() and flatMap()?**  

    - **map()**: One-to-one (transforms each element).  

    - **flatMap()**: One-to-many → flattens nested collections.


These cover 80–90% of core Java questions asked in interviews. Practice saying them out loud in simple words — interviewers like clear, confident answers more than bookish language.


If you want code examples for any (like producer-consumer, custom HashMap logic, or Stream code), or more advanced ones (for 5+ years), just tell me your experience level! All the best for your interview! 💪

Previous Post
Next Post

post written by: