Reputation: 3584
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 ?
Upvotes: 0
Views: 7565
Reputation: 4847
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)
Upvotes: 1
Reputation: 5254
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.
Upvotes: 1
Reputation: 5855
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.
Upvotes: 1
Reputation: 1010
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).
Upvotes: 3