Java For Loop

For-loop in programming are used to iterate group of statement under certain situations. Java are provide two variant of this loop. First is similar to C and C++ programming language and other is enhanced version.

//C++ Style
for (initialization; termination;increment/decrement) {
    //statement's
}
//Enhanced version
for(dataType varName:Range){
    //statement's
}

For loop is used many variety of way in Java programming.

//For loop example
class Execution{

  public static void main(String[] args) {
    String[] fruits = new String[] { "apple",
    "apricot",
    "avocado",
    "banana",
    "blackberry",
    "blueberry",
    "grape",
    "papaya",
     "mango" };

    for (String item : fruits) {
        System.out.println(item);
    }
  }
}

Output

apple
apricot
avocado
banana
blackberry
blueberry
grape
papaya
mango
//forEach loop example
import java.util.Arrays;
import java.util.List;

class Execution{

  public static void main(String[] args) {
    List<String>  days = Arrays.asList("Sun",
    "Mon",
    "Tue",
    "Wed",
    "Thu",
    "Fri",
    "Sat");
     days.forEach(System.out::println);

  }
}

Output

Sun
Mon
Tue
Wed
Thu
Fri
Sat

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved