🌐
Simplilearn
simplilearn.com › home › resources › software development › understanding for loop in java with examples and syntax
Understanding For Loop in Java With Examples and Syntax
July 31, 2025 - Java provides three types of loops, i.e., ✓ for loop ✓ while loop ✓ do-while loop. In this tutorial, you will learn all about for loop in Java. Start now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
W3Schools
w3schools.com › java › java_for_loop.asp
Java For Loop
In this example, the loop starts with i = 10. The condition i < 5 is already false, so the loop body is skipped, and nothing is printed. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
People also ask

How many types of loops are there in Java?
Java provides three main types of loops: the for loop, the while loop, and the do-while loop. Each type has its syntax and use cases, allowing developers to choose the most appropriate loop for a given scenario.
🌐
simplilearn.com
simplilearn.com › home › resources › software development › understanding for loop in java with examples and syntax
Understanding For Loop in Java With Examples and Syntax
When should I use a for loop versus a while loop in Java?
Use a for loop when the number of iterations is known or when iterating over a range of values. On the other hand, use a while loop when the number of iterations is uncertain or when looping based on a condition that may change during execution. Choose the loop type that best fits your program's specific requirements.
🌐
simplilearn.com
simplilearn.com › home › resources › software development › understanding for loop in java with examples and syntax
Understanding For Loop in Java With Examples and Syntax
What is the difference between a while loop and a do-while loop in Java?
The main difference between a while loop and a do-while loop is that a while loop tests the loop condition before executing the loop body, while a do-while loop executes the loop body at least once and then tests the loop condition.
🌐
simplilearn.com
simplilearn.com › home › resources › software development › understanding for loop in java with examples and syntax
Understanding For Loop in Java With Examples and Syntax
🌐
TutorialsPoint
tutorialspoint.com › java › index.htm
Java Tutorial
Explore the loops and control statements to learn how to control the execution of the programming logics: ... Explore the file handling chapters to learn how to create, write, read, and manipulate the files and directories: ... Our Java programming tutorial provides various examples to explain the concepts.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-for-loop-with-examples
Java For Loop - GeeksforGeeks
1 month ago - The following examples demonstrate how for loops and nested for loops are used in Java for iteration, pattern printing, and calculations.
🌐
Codecademy
codecademy.com › learn › learn-java
Java Tutorial: Learn Java Programming | Codecademy
Learn about object-oriented programming in Java. Explore syntax for defining classes and creating instances. ... Conditionals and control flow in Java programs. ... Build lists of data with Java arrays and ArrayLists. ... Use loops to iterate through lists and repeat code.
Rating: 4.4 ​ - ​ 10.7K votes
🌐
DataCamp
datacamp.com › doc › java › java-for-loop
Java For Loop
for (initialization; condition; update) { // Code to be executed } initialization: Initializes the loop variable. It is executed once at the beginning of the loop. condition: Evaluated before each iteration. If true, the loop body executes; if false, the loop terminates.
🌐
Netflix Tech Blog
netflixtechblog.com › optimizing-recommendation-systems-with-jdks-vector-api-30d2830401ec
Optimizing Recommendation Systems with JDK’s Vector API | by Netflix Technology Blog | Mar, 2026 | Netflix TechBlog
March 3, 2026 - For each candidate we fetch its embedding, loop over the history to compute cosine similarity one pair at a time and track the maximum similarity score. Although it is easy to reason about, at Ranker’s scale, this results in significant sequential work, repeated embedding lookups, scattered memory access, and poor cache locality. Profiling confirmed this. ... A flamegraph made it clear: One of the top hotspots in the service was Java dot products inside the serendipity encoder.
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › java-for-loop-example
Java For Loop Example
February 7, 2023 - In this article, we'll focus on the for loop, its syntax, and some examples to help you use it in your code. The for loop is mostly used when you know the number of times a loop is expected to run before stopping. Here's what the syntax of for loop in Java looks like:
🌐
Programiz
programiz.com › java-programming › for-loop
Java for Loop (With Examples)
To learn more, visit Java for-each Loop. If we set the test expression in such a way that it never evaluates to false, the for loop will run forever. This is called infinite for loop. For example,
🌐
Opengenus
discourse.opengenus.org › software engineering
For loop in Java - software engineering - Discuss Career & Computing - OpenGenus
May 20, 2019 - for loop is an entry controlled loop that is widely used in Java programming language. Loop is a programming concept which is natively supported by nearly all programming languages. Loops are used to repeat a particular…
🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
1 month ago - Example 2: Iterating in a List using for-each loop ... import java.util.*; class Geeks { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(3); list.add(5); list.add(7); list.add(9); int max = Integer.MIN_VALUE; for (int num : list) { if (num > max) { max = num; } } System.out.println("List of Integers: " + list); System.out.println("Maximum element: " + max); } }
🌐
ScholarHat
scholarhat.com › home
Loops in java - For, While, Do-While Loop in Java
Loops in Java - Types of loops in Java like For, While, Do-While Loop Java, understanding their distinct functionalities and usage within Java programming.
Published   August 30, 2025
Top answer
1 of 6
6

You should loop through the array and use an index / boolean flag to store whether or not the book is found. Then print the message in the end, based on the index / flag value.

int foundAtIndex = -1;
for(int i = 0; i < bookObj.length; i++) {
    if(bookObj[i].getName().equals(input)) {
        foundAtIndex = i;  // store the actual index for later use
        break;             // no need to search further
    }
}
if(foundAtIndex >= 0)
    System.out.println("Book Found!");
else
    System.out.println("Book not Found!");

Alternatively (unless your assignment specifically requires using an array) you should prefer a Set, which can do the search for you with a single call to contains().

How should I think of it in Object Oriented way?

When looking at a single method, there is not much difference between procedural and OO style. The differences start to appear at a higher level, when trying to organize a bunch of conceptually related data and methods that operate on these.

The OO paradigm is to tie the methods to the data they operate on, and encapsulate both into coherent objects and classes. These classes are preferably representations of important domain concepts. So for your book store, you may want to put all book related code into your Book class. However, the above search method (and the collection of books it operates on) is not related to any particular book instance, so you have different choices:

  • put both the collection of books and the search method into Store (probably as regular members), or
  • put them into Book as static members.

The first choice is more natural, so I normally would prefer that. However, under specific circumstances the second option might be preferable. In (OO) design, there are hardly ever clean "yes/no" answers - rather tradeoffs between different options, each having their own strengths and weaknesses.

2 of 6
2

You could introduce state and remember whether you have found the book or not.

If you're not using Java 1.4 or earlier, you could also use the foreach loop syntax:

boolean bookFound = false;
for(Book currentBook : bookObj) {
     if(currentBook.getName().equals(input))
     //TODO: see above
}

Also, I would suggest looking into the Collections library, and replace your array with a list or set:

Set<Book> books = new HashSet<Book>();
books.put(new Book("Game Over"));
books.put(new Book("Shrek")); 
books.put(new Book("Ghost"));

And, while were at it, you could also think about when two books are equal and override equals() and hashCode() accordingly. If equal() would be changed to check the title, you could simply use books.contains(new Book(input)); and have the libraries do the work for you.

🌐
OneCompiler
onecompiler.com › java
Java Online Compiler
For loop is used to iterate a set of statements based on a condition.
🌐
Oracle
docs.oracle.com › javase › tutorial › java › nutsandbolts › for.html
The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)
See Java Language Changes for a ... in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases. The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of ...
Top answer
1 of 13
337

The three forms of looping are nearly identical. The enhanced for loop:

for (E element : list) {
    . . .
}

is, according to the Java Language Specification, identical in effect to the explicit use of an iterator with a traditional for loop. In the third case, you can only modify the list contents by removing the current element and, then, only if you do it through the remove method of the iterator itself. With index-based iteration, you are free to modify the list in any way. However, adding or removing elements that come before the current index risks having your loop skipping elements or processing the same element multiple times; you need to adjust the loop index properly when you make such changes.

In all cases, element is a reference to the actual list element. None of the iteration methods makes a copy of anything in the list. Changes to the internal state of element will always be seen in the internal state of the corresponding element on the list.

Essentially, there are only two ways to iterate over a list: by using an index or by using an iterator. The enhanced for loop is just a syntactic shortcut introduced in Java 5 to avoid the tedium of explicitly defining an iterator. For both styles, you can come up with essentially trivial variations using for, while or do while blocks, but they all boil down to the same thing (or, rather, two things).

EDIT: As @iX3 points out in a comment, you can use a ListIterator to set the current element of a list as you are iterating. You would need to use List#listIterator() instead of List#iterator() to initialize the loop variable (which, obviously, would have to be declared a ListIterator rather than an Iterator).

2 of 13
55

Example of each kind listed in the question:

ListIterationExample.java

import java.util.*;

public class ListIterationExample {

     public static void main(String []args){
        List<Integer> numbers = new ArrayList<Integer>();

        // populates list with initial values
        for (Integer i : Arrays.asList(0,1,2,3,4,5,6,7))
            numbers.add(i);
        printList(numbers);         // 0,1,2,3,4,5,6,7

        // replaces each element with twice its value
        for (int index=0; index < numbers.size(); index++) {
            numbers.set(index, numbers.get(index)*2); 
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // does nothing because list is not being changed
        for (Integer number : numbers) {
            number++; // number = new Integer(number+1);
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14  

        // same as above -- just different syntax
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            number++;
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // ListIterator<?> provides an "add" method to insert elements
        // between the current element and the cursor
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.add(number+1);     // insert a number right before this
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

        // Iterator<?> provides a "remove" method to delete elements
        // between the current element and the cursor
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            if (number % 2 == 0)    // if number is even 
                iter.remove();      // remove it from the collection
        }
        printList(numbers);         // 1,3,5,7,9,11,13,15

        // ListIterator<?> provides a "set" method to replace elements
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.set(number/2);     // divide each element by 2
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7
     }

     public static void printList(List<Integer> numbers) {
        StringBuilder sb = new StringBuilder();
        for (Integer number : numbers) {
            sb.append(number);
            sb.append(",");
        }
        sb.deleteCharAt(sb.length()-1); // remove trailing comma
        System.out.println(sb.toString());
     }
}
🌐
GroTechMinds
grotechminds.com › home › java loop programs examples
java loop programs examples
October 17, 2024 - For example, sequential execution (line by line), is the default natural order of execution in Java, whereas we have decision-making statements (if, if else, if else if, nested if), loop statements (for, while, do-while) and branching statements (break, continue) as well.
🌐
Jenkov
jenkov.com › tutorials › java › for.html
Java for Loops
April 18, 2024 - If the current String in the strings ... the next Java statement after the if statement is executed, and the variable wordsStartingWithJ is incremented by 1. The continue command also works inside for each loops. Here is a for each version of the previous example:...
🌐
Baeldung
baeldung.com › home › java › core java › java for loop
Java For Loop | Baeldung
February 25, 2026 - It’s useful if we’ve got nested ... for loop: aa: for (int i = 1; i <= 3; i++) { if (i == 1) continue; bb: for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { break aa; } System.out.println(i + " " + j); } } Since Java 5, ...