Professional Documents
Culture Documents
A674940238 - 21789 - 9 - 2019 - 05. Control Structures
A674940238 - 21789 - 9 - 2019 - 05. Control Structures
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
Java if Statement
for(data_type variable : array | collection){}
public class ForEachExample
{
public static void main(String[] args)
{ //Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr)
{
System.out.println(i);
}
}
}
Java Labeled For Loop
• We can have a name of each Java for loop.
Example 1:
class var2 {
public static void main(String arr[]) {
int a, b;
b = 5;
for(a=0; a<b; a++) {
System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
}
}
}
• Comma (separator) is used while initializing multiple loop
control variables.
Example 2:
class var21
{
public static void main(String arr[]) {
int x, y;
for(x=0, y=5; x<=y; x++, y--) {
System.out.println("x= " + x);
System.out.println(“y = " + y);
}
}
}
• Initialization and iteration can be moved out from for loop.
Example 3:
class Loopchk
{
public static void main(String arr[])
{
for(int i=1, j=5; i>0 && j>2; i++, j--)
System.out.println("i is: "+ i + "and j is:
"+j);
}
}
For-Each Version of the for Loop
• Beginning with JDK 5, a second form of for was
defined that implements a “for-each” style loop.