Java 8 forEach() method — Java Technical Interview Questions & Answers

Java 8 forEach() method

Java 8 forEach() method

  • 8 forEach() method is modern Java (5/8 toolkit). Lambdas are short functions: (n) -> print. They implement a functional interface (one abstract method). Streams let you filter/map/collect a list without a manual loop.
  • For 8 forEach() method: generics keep types safe: List<String>. Autoboxing turns int into Integer when needed. varargs is String... args. Optional avoids some null checks — don’t overuse it.
  • Keep 8 forEach() method small. Don’t dump business logic inside forEach. Know one tiny example you can write from memory.
  • Let's take this on the board with one tiny Main class — no extra files. Java 8 forEach() method — output: 10 then 20 then 30. for-each walks the array — no index variable. Start from main, go line by line, and stop at each print. That output is the proof for 8 forEach() method.

Technical Interview Tip: Say: for-each is for reading; classic for when index matters.

Code Examples for Java 8 forEach() method

Example

// For-Each Loop
public class Main {
  public static void main(String[] args) {
    int[] nums = {10, 20, 30};
    for (int x : nums) {
      System.out.println(x);
    }
  }
}

Java 8 forEach() method — output: 10 then 20 then 30. for-each walks the array — no index variable.

How to Explain Java 8 forEach() method to an Interviewer

What is 8 forEach() method?

8 forEach() method is part of modern Java (generics / Java 8 style). 8 forEach() method — lambda = (args) -> body on a functional interface. 8 forEach() method — streams filter/map/collect. Generics = List<String>.

Why do we use 8 forEach() method in Java?

Makes the program clearer or safer 8 forEach() method is part of modern Java (generics / Java 8 style).

Write one small example of 8 forEach() method.

Show syntax Say what prints

What mistake do beginners make with 8 forEach() method?

Only the name, no example 8 forEach() method — huge logic inside lambdas, or forgetting generics.

Where is 8 forEach() method used in a real program?

Day-to-day Java code