Posts Tagged for

Java Tutorial 10 – Enhanced For Loops

enhanced for loops are very useful for arrays.

to loop through array what we generally do is we take one int as index and use this index inside loop to point to array location and then we increment it.

But there is one more easiest way to loop through array which is called Enhanced For Loop. it automatically increments index and stops at the end of the array. let me show you one example:

For loop:

public class fruit {
    public static void main(String[] args) {
        String fruift[] = {“apple”, “banana”, “grapes”};
        int i;
        for (i = 0; i < 3; i++) {
            System.out.println(fruift[i]);
        }
    }
}
Enhanced For Loop:
public class fruit {
    public static void main(String[] args) {
        String fruift[] = {“apple”, “banana”, “grapes”};
        for (String i : fruift) {
            System.out.println(i);
        }
    }
}
You can see the difference between lines of code.
it is pretty much easy to use each element of array and loop through it.
Syntax:
for( <type of array> <variable> : <array name> )
for example u have array of int and you want to loop through each 1 then u have to write.
for( int x : numbers ){
….things to do….
}
here “numbers” is array of ints. int x holds the value of array elements.
Example.
int num[] = { 4, 34, 12, 7, 56, 89}
for( int x : num){
}
when first time it loops x holds value “4”.
then in second loop value of x will be “34” and so on…
It’s very useful to loop through all elements of array.
So, it’s all about enhanced for loop.
Have a nice day, Peace.

, , , , ,

Leave a comment

Java Tutorial 4 – Looping

I think you guys can do following:

  1. create new class
  2. now add following lines in main method

no need to import anything because we are not using scanner here.

Syntax:

while ( condition ) {

 ….to do …

}

it will first check the condition and if condition is true it run the code within the {} and again check the condition, this will continue till condition will not become false. Once it become false loop is ended.

we created here an int i and printed 1 line each time it loops.

and If u know C/C++ its going to boring for you ! because its same.

Again Doubts and suggestions  are invited.

Peace.

, , , , , ,

Leave a comment

Design a site like this with WordPress.com
Get started