PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

For-Each Loop in Java

← All stacks

Theory

19/270

For-Each Loop in Java

for-each (enhanced for) walks every element without an index. Read it as “for each item in this list”. Shape: for (int x : arr) System.out.println(x);

Use it when you only need values. If you need the position, or you must replace an item by index, use a normal for with i.

Do not remove items from a list inside for-each without an iterator — Java can throw ConcurrentModificationException. Keep for-each simple: read and print, or copy.

Let's take this on the board with one tiny Main class — no extra files. For-Each Loop in Java — 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 For-Each Loop.

Exam tip

Say when for-each is better than index-for, and when it is not.

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

For-Each Loop in Java — output: 10 then 20 then 30. for-each walks the array — no index variable.

Short notes

  • Deffor-each walks every element without an index.
  • Rulefor (Type x : arr). Read as “for each item”.
  • UseOnly values, not positions.
  • TrapRemoving from a list inside for-each can crash.

Questions

1

What is for-each?

2

When should you not use for-each?

3

Write the shape.

Previous← Java For LoopNextJava While Loop →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.