Java - For Statement

1 - About

The for statement is a part of the control flow possibility of Java.

The Iterable interface must be implemented in order to use it. See for example: Java - Iterator Implementation

3 - Property

3.1 - Index

During a for loop, this is no shortcut syntax to get the index. You need to create it


int index = 0;
for (String s: strings){
  System.out.println("The current index is "+index);
  assert s == strings.get(index): "Error";
  // Increment
  index++
}

4 - Syntax

4.1 - General


for (initialization; termination; increment) {
    statement(s)
}

4.2 - Enhanced


for (datatype variable : collections or array) {
    statement(s)
}

5 - Infinite


for ( ; ; ) {
    
    // your code goes here
}

6 - Skip

The continue statement skips the current iteration of a for loop.

7 - Example

7.1 - Counter


for(int i=1; i<11; i++){
    System.out.println("Count is: " + i);
}

7.2 - Array

Java - Array


int[] anArray= {1,2,3,4,5,6,7,8,9,10};
for (int i = 0; i < anArray.length; i++) {
	System.out.println(i+" : "+anArray[i]);
}

8 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap