Friday, 18 March 2016

Different types of FOR loops in Java

package pack1;

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

public class Forloops {

public static void main(String a[]){
String[] m = {"a","b","c"};
//Type 1

/*for(int i=0;i< m.length;i++){
System.out.println(m[i]);
}*/

//Type 2
/*
for (String n: m){
System.out.println(n);
}*/

//Type 3

/*for(int i=0;i<5;i++){
System.out.printf("%d the value is", i);
}*/

//Type 4 - with collections

/*List<String> x = new ArrayList<String>();
x.add("item 1");
x.add("item 2");
x.add("item 3");
for(String z:x){
System.out.println(z);
}*/

//Type 5 - Collections using iterator

ArrayList al = new ArrayList();
     // add elements to the array list
     al.add("C");
     al.add("A");
     al.add("E");
     al.add("B");
     al.add("D");
     al.add("F");

     // Use iterator to display contents of al
     System.out.print("Original contents of al: ");
     Iterator itr = al.iterator();
     while(itr.hasNext()) {
        Object element = itr.next();
        System.out.print(element + " ");
     }
}

}


User Defined Object/class/dataType and Iteration through FOR loop:

/** User defined class/dataType**/

package pack1;

import java.util.ArrayList;
import java.util.List;

class Person {
public int personId;
public String personName;

public int getPersonId() {
    return personId;
}

public void setPersonId(int personId) {
    this.personId = personId;
}

public String getPersonName() {
    return personName;
}

public void setPersonName(String personName) {
    this.personName = personName;
}}

/** Main Class *****************************************/
public class ArrayLoop {

public static void main(String a[]){
Person p = new Person();   /** setting values for user class **/
p.setPersonId(1);
p.setPersonName("Prabhu");
List<Object> x = new ArrayList<Object> (); /** Initialising a List to add User defined clas*//
x.add(p);    //** Adding User class to List **/
for (Object ob: x){  //** Iterating the list to get user class object **//
System.out.println(ob.getClass());
Person m = (Person)ob;   /** Type casting to user class **//
System.out.println(m.personId);
System.out.println(m.personName);
}
}

}



Output:

class pack1.Person
1
Prabhu

No comments:

Post a Comment