3
votes

Could you help me understand what's going on. I've taken a book Core Java. The first variant is from there. The second variant is my attempt to compile the progrm. I have: java version "1.7.0_21" Java(TM) SE Runtime Environment (build 1.7.0_21-b11) Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

public class Welcome
{
   public static void main(String[] args)
   {
      String[] greeting = new String[3];
      greeting[0] = "Welcome to Core Java";
      greeting[1] = "by Cay Horstmann";
      greeting[2] = "and Gary Cornell";

      for (String g: greeting)
         System.out.println(greeting[g]);
   }
}

The result:

Welcome.java:16: error: incompatible types
         System.out.println(greeting[g]);
                                     ^
  required: int
  found:    String
1 error

If I change my code:

public class Welcome
{
   public static void main(String[] args)
   {
      String[] greeting = new String[3];
      greeting[0] = "Welcome to Core Java";
      greeting[1] = "by Cay Horstmann";
      greeting[2] = "and Gary Cornell";

      for (int g: greeting)
         System.out.println(greeting[g]);
   }
}

The result is:

Welcome.java:15: error: incompatible types
      for (int g: greeting)
                  ^
  required: int
  found:    String
1 error
4

4 Answers

4
votes

You don't get an index in an enhanced for-loop. you get a reference to the value in the container you are iterating. So, you can directly print it.

Change the below statement in your 1st snippet:

System.out.println(greeting[g]);

to:

System.out.println(g);

For your 2nd snippet, this:

for (int g: greeting)

doesn't make sense at all. As I said, you get the copy of reference to the elements in greeting, and since the element in greeting are of type String, your loop variable should be String g as in first snippet.

2
votes

It iterates through the elements of the iterable. This abstraction allows us not to worry about the inner working of the iterable (we no longer have to care about indexes and inner workings, just the elements).

 for (String g: greeting)
     System.out.println(g);
 }

See the official guide on iterations in Java.

0
votes

You don't need to use greeting[g]. Instead you would say:

for (String s: greeting) {
    System.out.println(s);
}

The s is merely each element in the array, no need to use an index

0
votes

The enhanced for loop saves you messing around with the index of the array you want to iterate through, its for when you just want to run from start to end and no fancy stuff.

for (String g: greeting)
     System.out.println(g);

g is now the 1st element in greeting and every loop it will become the next element until it reach's the end. That's why it was saying you gave it a String when it was expecting a int.

So basically it saves you typing this:

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

Hope that made sense bud