Java understanding For loops
ELI5: Understanding For Loops in Java
Java: For loop and If algorithm - Stack Overflow
java - How does a for loop work, specifically for(;;)? - Stack Overflow
Videos
As the title said, can you guys help me understand the for loops in java like I'm five. I've been trying to learn java but when it comes to for loop, I'm having a hard time understanding it. Especially when my professor is using single letters like for int i, x, y, and such something like that. Whenever I'm coding, I always use proper names so I don't get confused with the variables. But I still get confused using for loops;-; so I mostly prefer using the do.. while or while loops. But I want to learn to understand it because I noticed my prof always uses it and as well as ytber programmers.
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
Bookasstaticmembers.
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.
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.
A for loop in java has the following structure -
for (initialization statement; condition check; update)
loop body;
As you can see, there are four statements here -
- Initialization statement: This statement is executed only once, when the loop is entered for the first time. This is an optional statement, meaning you can choose keep this field blank. It is generally used for some initialization purpose.
- Conditional check: This statement is probably the most important one. It checks to verify whether or not certain expression evaluates to true. If it is, then the loop execution continues. You can choose to keep this field empty, which will be evaluated to
true. - Update: This statement list is executed from left to right, typically used to increment/decrement some variable.
- loop body: The body of the loop, which will be executed again and again based on the conditional check's truth value.
Basically this is how the execution follows - first, when the loop is entered for the first time, the initialization statement is executed once. Then the conditional check is executed to see if it evaluated to true. If it is, then the the loop body is executed, otherwise the loop execution is finished. After that, the Update statement(s) is(are) executed. Next, the conditional check is executed again, and if it evaluates to true, then again the loop body is executed, then update statement is executed, then again the conditional check....you get the picture.
Now about your for( ; ; ) syntax. It has no initialization statement, so nothing will be executed. Its conditional check statement is also empty, which means it evaluates to true after that the loop body is executed. Next, since the update statement is empty, nothing is executed. Then the conditional check is performed again which will again evaluates to true and then this whole process will again repeat.
So you see, this is basically an infinite loop which has no initialization statement, whose conditional check will always evaluates to true, and which has no update statement. This is equivalent to -
while(true)
{
.....
}
which is another popular loop construct in java.
When you use an infinite loop like this, it's important pay attention to the breaking condition as in most cases you can't let a loop to run indefinitely. To break out of these kinds of loops, you can use the break statement. The structure is as follows -
if(some_condition_is_true)
break; // This will cause execution to break out of its nearest loop
or
if(some_condition_is_false)
break;
This is the same as:
while(true) {
//Some Stuff
}
Basically, an alternate syntax for an infinite loop.