Java - For Each Loop
Java - For Each Loop
loop
for - each loop
★ It is an enhanced for loop
Advantage:
Disadvantage:
Rules
1. It starts with the keyword for .
2. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base
type of the array, followed by a colon, which is then followed by the array name.
3. In the loop body, you can use the loop variable you created rather than using an indexed array element.
4. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Example
class ForEachExample1
Output
{ 12
public static void main(String args[]) 12
{ 14
//declaring an array 44
int arr[]={12,13,14,44};
for(int i:arr)
System.out.println(i);
} }
}
Activity 1 :Program
to find total of
array using
for each loop
Thank You
Switch case
Switch - case
★ Switch statement is Java’s multiway branch statement
The expression must be of type byte, Duplicate case values are not allowed.
short, int, or char.
The value for a case must be of the The value for a case must be a constant
same data type as the variable in the or a literal. Variables are not allowed.
switch.
The value of the expression If a match is found, the code
Working of is compared with each of the sequence following that
literal values in the case case statement is executed.
Switch - Case statements.
}
Nested Switch
Switch as part of the statement sequence of an outer switch. This is called a Nested switch
Example :
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
Importance of Switch
★ The switch differs from the if statement in that switch can only test for equality,
if can even test boolean.
★ In nested if switch statement and an enclosing outer switch can have case
constants in common.
★ A switch statement is usually more efficient than a set of nested ifs.
{
int a=8,int b=-8;
//Left Shift
int a1=a<<1; //Means shift one position left
System.out.println("Left shift of Positive 8 by 1 position :"+a1);
System.out.println("Binary Representation :"+Integer.toBinaryString(a1));
Binary
Representation :111111111111111111111111
11110000
Program…...
//Right Shift
int b3=b>>>1;
System.out.println("Integer Right shift with Zero Fill of Negative 8 by 1 position :"+b3);
System.out.println("Binary Representation :"+Integer.toBinaryString(b3));
Right shift with Zero Fill of Positive 8
by 1 position :4
}
Binary Representation :100
}
Integer Right shift with Zero Fill of
Negative 8 by 1
position :2147483644
Binary
Representation :1111111111111111111
Activity 3 - Prepare a note on Bitwise
Shift operator in Java.
Thank You