Blog Archive

Java Enhanced for loop example

Starting Java 5.0 the for-loop was enhanced. Its a very simple syntax now, easy to use and remember.
Here is a sample code on how to use it.
package com.as400samplecode;

import java.util.ArrayList;

public class JavaForLoop {

    public static void main(String[] args) {
       
        //let create an Array List for our example for loop
        ArrayList<OrderDetail> orderList = new ArrayList<OrderDetail>();
       
        //push some items into the ArrayList
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setItemNumber("ABC101");
        orderDetail.setDescription("ABC101 Item Description");
        orderDetail.setPrice(101.99);
        orderDetail.setQuantity(101);
        orderList.add(orderDetail);
       
        //push some items into the ArrayList
        orderDetail = new OrderDetail();
        orderDetail.setItemNumber("ABC102");
        orderDetail.setDescription("ABC102 Item Description");
        orderDetail.setPrice(102.99);
        orderDetail.setQuantity(102);
        orderList.add(orderDetail);
       
        //push some items into the ArrayList
        orderDetail = new OrderDetail();
        orderDetail.setItemNumber("ABC103");
        orderDetail.setDescription("ABC103 Item Description");
        orderDetail.setPrice(103.99);
        orderDetail.setQuantity(103);
        orderList.add(orderDetail);
       
        //Let's read the ArrayList back in our for Loop
        for (OrderDetail myDetail: orderList){
         
            System.out.println("Start --: ");
            System.out.println("Item Number: " + myDetail.getItemNumber());
            System.out.println("Description: " + myDetail.getDescription());
            System.out.println("Price: " + myDetail.getPrice());
            System.out.println("Quantity: " + myDetail.getQuantity());
       
        }

    }

}

No comments :

Post a Comment