Java For-loop Syntax Is Not Rocket Science! Here’s Why! – J020

by Jun 15, 2015




DeegeU Java Course

Java For-loop Syntax Is Not Rocket Science! Here’s Why! is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.

Try at home

  1. Use the Java for-loop syntax to count from 0 to 100
  2. Create a for-loop that counts odd numbers from 100 to 0
  3. Create a for-loop that counts from 0 to 100, but prints fizz for multiples of 3, and buzz for multiples of 5
  4. Create an enhanced for-loop that prints out the contents of an array
  5. Make sure you know the difference in the Java for-loop syntax and the enhanced Java for-loop syntax
  6. Try creating errors in your program and compiling it

Transcript – Java For-loop Syntax Is Not Rocket Science! Here’s Why!

The for-loop is one of the most important Java control statements. You will be hard pressed to find an application that doesn’t contain a for-loop. The Java for-loop syntax isn’t rocket science. You’re telling Java I want you to loop over this block, and I want you to do it a set number of times. There’s two ways to loop using the for-loop, the basic way and the enhanced for-loop. In this video I’m going to show you both, and by the end you should be a pro with the Java for-loop syntax.

In this lesson we’re going to learn about looping, specifically for-loops. We’re going to look at how you can control the direction and the step of the loop. We’ll also cover something called for-each loops, AKA the enhanced for-loop. When we’re done, you should understand the difference between incrementing and iterating loops. So let’s take a look at loops!

Java for-loop syntax - Free Java Course Online - DeegeU

The basic Java for-loop syntax

The for-loop is a control statement that tells Java to loop over a Java block. Usually you loop a finite number of times. The Java for-loop syntax starts with the keyword for. Each basic for-loop has a start, condition, and step.

The start initializes any variable you require for the loop. This is only one variable. Other languages do more, Java does one. That’s really all you should need unless you’re trying to do something silly-clever. Initialization is run only once for the life of the loop, and it happens when you start the loop. The condition tells the loop when it should stop. When this condition evaluates to false, the looping stops. The step tells the for-loop how it should advance for each loop. Surprisingly, all of these are optional.

Here’s what it looks like when everything is left out. There is no start, no stop, and no increment. Just semicolons. You’d think this wouldn’t run, but actually the opposite is true. This runs forever. We’ve seen how long that is.

The important thing to note is each piece of the for-loop is optional. There might be a good reason to leave everything optional, but… if you need an empty for-loop like this, I’d just make a while loop with a true condition. It does the same thing.

So lets look at what happens in a for-loop. The first thing run is the initialization. Here we are initializing the variable i to 0.

Every step we are going to increment i by 1. I’m using the ++ unary operator here, but I could also have written i=i+1. The ++ operator is just more succinct.

The condition is, we are not stopping until i is greater than or equal to 10. The condition here says i less than 10. That means if i equals 10, we should not loop. When we first enter the loop, i is 0. The second loop, i is 1. And so on. We continue looping. Every time we loop, the index i is incremented in value by one. Each loop we check is i less than 10. Yes, increment i and loop again. When i is 10, the condition fails. The loop stops.

Lets take a look at the code, and play with loops a bit.

(* screencast *)

One place you’ll see for-loops is when working with arrays. Its also one place you’ll often see looping errors. Let’s look at the following example. We have an array. It’s got 5 numbers in it. Looping over the array, we add one to each element.

When we are done we should have an array that looks like this. Each element is increased in value by one. Look what happens when we include an equals sign.

In this case we’re including 5 as an index to update. Our array only has five indexes that go from zero to 4. 5 will cause an error and your program will crash. You’re gonna see this error often, especially when you’re starting out. Let’s intentionally cause this error to see what happens.

(* screencast *)

This is a better for-loop. It’s sometimes called the enhanced for-loop. I don’t make this stuff up. The way to read this control statement is, for each i in array. Read the colon as “in”. The enhanced for-loop syntax is the keyword for, the type for each element in your collection, and the collection.

The enhanced Java for-loop syntax - Free Java Course Online - DeegeU

The enhanced Java for-loop syntax

This loop is better because it doesn’t care about an index. You don’t even need to know how many elements are in the array. You iterate over each item in the array, and the compiler takes care of range checking for you. Two catches to this loop. One, you can’t modify each element as you visit it, and two you don’t know the current index. You can certainly put an index in there on your own, but if you really need to, just use the normal for-loop. Let’s look at the enhanced for-loop in code.

(* screencast *)

We’ve been playing with numbers, but you can iterate over other types. Here’s an example of iterating over a character array. The output would be “a s d f”. I’ll leave it as an exercise for you to type this loop in. If you have questions, leave it in the comments and I’ll gladly help you out!

I’d say 90% of the time, I use the enhanced for-each loop and iterate over arrays. The Java for-loop syntax is much simpler with enhanced for-loops and leads to safer code. That means it’s less likely to break with weird errors. Both loops are almost always the same speed. Normal for-loops can be slightly faster if the array is an array if integers. In other array types there’s almost no difference. You shouldn’t worry about it. It’s a judgement call on which one you should use, but if you can iterate using a for each instead of incrementing over a normal loop, go for the iterations.

As always, if you have questions, leave them in the comments below. And with that, I’ll see you in the next lesson!







Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • No infringement intended

Get the code

The source code for “Are you ready to tackle the fizzbuzz test in Java?” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-java-intro.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

Don’t miss another video!

New videos come out every week. Make sure you subscribe!

Comments

comments

DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I’m a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I’ve programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I’ve worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This