Friday, 30 December 2016

While Loop In Java Example

package com.kt4study.corejava.loop;

import java.util.ArrayList;
import java.util.Iterator;

/**
 @author kt4study.blogspot.co.uk
 
 */

public class WhileLoopExample {

  public static void whileLoopExampleDemo() {
    
    //While Loop Type 1
    int i = 1;
    // Check condition
    while (i <= 3) {
      System.out.println("Current value Of 'i' is :: " + i);
      i++;
    }
    
    //While Loop Type 2 forArrayList Object 
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("Java Guider");
    arrayList.add("Kt4Study.blogspot.co.uk");
    // Get list of ArrayList elements to iterate
    Iterator<String> iterator = arrayList.iterator();

    // Check condition
    while (iterator.hasNext()) {
      System.out.println("Iterated element from while loop :: " + iterator.next());
    }

  }

  public static void main(String[] args) {
    WhileLoopExample.whileLoopExampleDemo();
  }
}

Output →

Current value Of 'i' is :: 1
Current value Of 'i' is :: 2
Current value Of 'i' is :: 3
Iterated element from while loop :: Java Guider
Iterated element from while loop :: Kt4Study.blogspot.co.uk

No comments:

Post a Comment