-
Notifications
You must be signed in to change notification settings - Fork 1
For Loops in Java
Sharina Stubbs edited this page Sep 17, 2019
·
11 revisions
- Note that instead of var or const in JavaScript, you write int, because you need to specify the type of data that is being used.
- Regarding scope, everything in Java is more block oriented.
Several examples are those found in A Guide to Java Loops
for (int i = 0; i < 5; i++) {
System.out.println("Simple for loop: i = " + i);
}
for ( ; ; ) {
}
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);
}
}
int[] intArr = { 0,1,22,33,40 };
for (int num : intArr) {
System.out.println("Enhanced for-each loop: i = " + num);
}
for (String item : list) {
System.out.println(item);
}
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(
"Key: " + entry.getKey() +
" - " +
"Value: " + entry.getValue());
}
List<String> names = new ArrayList<>();
names.add("Mabel");
names.add("Razzle");
names.add("Luna");
names.add("Finn");
names.add("Pip");
names.forEach(name -> System.out.println(name));
- A Guide to Java Loops - https://www.baeldung.com/java-loops
- Oracle docs - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html