0

I'm always confused with enhanced for loop. I have this example

public class NonRepeatedChar
{   
    public static void main(String[] args)
    {
        String str = "javapassion";
        int[] count = new int[128];
        char[] charArr = str.toLowerCase().toCharArray();
        for (char c : charArr)
        {
            count[c]++; 
        }
        for (char c : charArr)
        {
            if (count[c] == 1)
            {      
                System.out.println("First Non repeated character is : " + c);
                break;
            }
        }
    }
}

So in the above in the first for loop it says count[c]++ , this means a new array count is initialised and value of c is stored while the iterator is incremented ?

6
  • Ouch i was still editing the code :( , it was edited by some one else. Apologies Commented Jan 23, 2011 at 21:47
  • @coolrockers2007 Oops. I just hit the submit button when the 'someone else is editing this' popped up Commented Jan 23, 2011 at 21:48
  • oops I was in there too. Commented Jan 23, 2011 at 21:49
  • 5
    One big problem you have is that count[c] can throw IndexOutOfBoundsExceptions because char can have values from 0 to 0xFFFF (65335) in java. Commented Jan 23, 2011 at 21:51
  • Does this code even compile? I'd expect an error from the compiler like: "Line xxx: array index - int required, char found" Commented Jan 23, 2011 at 22:44

4 Answers 4

3

c is, in turn, each char in your String, that is, it takes the values 'j', 'a', 'v' etc.
Each char in Java is a 16 bit value with the normal latin lower-case character being values less than 128.
So count[c]++ increments the array cell corresponding to that character (counts occurrences of it).

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

Comments

1

c is used as an array index. It just so happens that in unicode (and ASCII) the 'normal' characters have a base 10 decimal value of between 0 and 127. Therefore, the integer value of any ASCII character sequence that you'd supply to the program is always going to be between 0 and 127. (You can still supply non-ASCII (unicode) characters to Java, of course, but in the context of this example I'm guessing they wanted to keep it simple .) This also has the benefit (because the String is converted to lowercase) of giving you the answer sorted alphabetically.

The array count stores the number of times an individual character has been found (seeing as the character is used as the index). The line count[c]++ increments the entry for the character c. If the count exceeds one then it becomes a repeated character and thus won't be printed out at the end.

Comments

1

To learn the magic of the enhanced for loop, try expanding it into a regular for loop. For example, the first loop

for (char c : charArr)
{
    count[c]++; 
}

becomes

for (int i = 0; i < charArr.length; i++)
{
    char c = charArr[i];
    count[c]++;
}

So the enhanced for loop is less code, making it easier to type and read, but you do not have access to the index i.

The enhanced for loop also works for Iterable objects, like collections, but expands into different code. Try expanding that based on the behavior above and the Iterable interface.

Comments

1

Let's separate your two questions:

(A) what is a for loop

(B) what's going on with the operations on the count[] array


(A)

The for loop is just a way to traverse a collection or array so as to visit each member in said collection.

(B)

  • the for loop iterates over the characters in "javapassion"
  • each character (c) has an ascii value that is used as the array index in count[c]
  • count[c]++ increments the value at count[c] for each letter c
  • in the end, the resulting count[] array contains the number of occurrences of each letter found in the the input string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.