Java for keyword examples
- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
1. Java Classic for loop
Syntax of the classic for loop is as follows:for (initialization; terminate condition; incrementation) {
// statements
}
where:- initialization: contains code that initializes the loop, usually by declaring a counter variable. This code is executed only once.
- terminate condition: contains code that checks for a condition to terminate the loop. This code is executed every iteration, if the codition is met, the loop is terminated.
- incrementation: contains code that increments value of the counter variable. This code is executed every iteration.
for (int i = 0; i < 10; i++) {
System.out.println("Number: " + i);
} 2. Java Enhanced for loop
The enhanced for loop (also known as for-each) has been introduced since Java 5.This kind of for statement is a convenient way to iterate over an arry or a collection. Syntax of enhanced for loop is as follows:for (T var : collection<T> or T[] array) {
// statements
}
for (int number : nums) {
System.out.println("Number: " + number);
}And the following code iterates over an collection of Strings:Collection<String> names = new ArrayList<String>();
names.add("Tom");
names.add("Bill");
names.add("Jack");
for (String name : names) {
System.out.println("Name: " + name);
}See all keywords in Java.
Related Topics:
- Java do-while construct
- Java break keyword
- The 4 Methods for Iterating Collections in Java
- Some notes about execution control statements in Java
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments