-3

I saw this code in one of the tutorials. There isn't any error with it, but I just don't understand the code. Could someone guide me?

int trying[] = {3,4,5,6,7};
change (trying);

for(int y: trying) {
    System.out.println(y);
    }
}
public static void change (int x[]) {
    for ( int counter = 0; counter < x.length ; counter++){
        x[counter] += 5;
     }
}

Able to explain this part for me?

for(int y: trying) {
    System.out.println(y);
 }

I don't understand especially this line of code:

for (int y : trying)

1
  • that means: for each int contained in "trying" array, set this int as "y" and execute following block Commented Jun 16, 2015 at 13:29

7 Answers 7

5

Java for-Each loop Syntax:

for(data_type variable : array | collection){} 

Advantage:

  • It makes the code more readable.

in your example

 for(int y: trying){
     System.out.println(y);
 }

simply means like int y will iterate over all the values in trying. Like,

for(int i=0;i < trying.length;i++){
      int y = trying[i]; 
      System.out.println(y);
}

Collection:

 List<String> someList = new ArrayList<String>();
    // add "monkey", "donkey", "skeleton key" to someList

    for (String item : someList) {
        System.out.println(item);
    }

same as:

 for (Iterator<String> itr = someList.iterator(); itr.hasNext(); ) {
       String item = itr.next();
       System.out.println(item);
    } 

as it discussed earlier in this post

Sign up to request clarification or add additional context in comments.

5 Comments

for(int y=0;y < trying.length;y++) in your answer would mean that it would print values from 0 to trying.length
yes but the output is the content of the array trying
Ok, But what about the code in the question?
You could also provide an example of what happens in case of collections.
I am sorry if I offended you. I was just trying to draw your attention to the problem in your answer. Now it seems OK to me.
2

Okay, so trying[] is an array of integers. The function change() takes trying[] as input and +5 to every integer in trying[]. And the for loop that you are asking about is just syntactic sugar that can shorten code.

Look at the doc links and try running it in eclipse or some IDE.

Comments

2

for(int y: trying) is an implementation of foreach loop in java. This can be understood as:

for(int i = 0; i< trying.length; i ++){
    int y = trying[i];
    System.out.println(y);
}

the Java documentation states

The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator.

2 Comments

+1, since this makes more sense, then the answer with two upvotes. int y is the value contained in each array index, not the value of the index, as specified in that answer by @Hiru
For a simple and light description [PLUS ONE]
2

It's a for-each loop, a convenient way to loop over an array, a Collection, or more generally any Iterable.

For example, looping over an array of integers int[] trying, you can do:

for(int i=0; i<trying.length; i++) {
  int y = trying[i];
  // stuff with y
}

or using a while, an iterator... But this is a bunch of character, we are lazy and our fingers are tired. So here is shorter way to do such frequent operation:

for( int y : trying ) {
  // stuff with y
}

Behind the hood, the extended for cache an Iterator for any Iterable, or the index for an array, here is the JLS specification.

4 Comments

here is question is about an int array and not a Collection
@Blip Well, I think this is more a question about for-each than a question about array, but you're right, I'm going to change my example :)
no it does not use iterator for an array. refer to link provided by DJClaywort. also refer to my answer where I have quoted from this document.
1

This is called a foreach loop. So in words it says:

For each item "y" in the array "trying" - do something (here: print it).

It is very convenient in the case you don't care how often you loop but just want to address every item in the array/collection.

Alternatively you could just use the "normal" for loop as you used it in the change method.

Comments

1

I hope i can give you the information want or need.

Int trying[] is an array of integer.

with the for loop you loop trough the trying[] array, and everytime you circle trough you send a message to the console.

Then you have your second loop

so if you int counter is smaller then the length of the array x[] then you keep circling trough the loop. as soon as the counter reaches the same length or value as the x[] then the loop stops.

for(int y: trying) {
    System.out.println(y);
    }
}

So the example above isnt really that hard, the loop will continue to the point where i is greater or the same as trying.

with this information you can figure out the last for loop by yourself:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Comments

1

It says, run the code in { ... } for each object in trying.

Datatype is int, because trying is an array of int.

"y" is a variable that holds an object from trying (one at a time).

For example, when looping first time, y gets first value (3) from the array and runs the code between { and }. Then, y gets second value (4) from the array and run the same code again....and so on.

In this case, it will print a value of y for each object in trying.

for(int y: trying)
{
    System.out.println(y);
}

Datatype mentioned in for loop must be the same as the type of array. for Example,

for (String s : allLines) { ... }
for (Member m : allMembers) { ... }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.