Reputation: 51
I have found this program in which the for each loop is applied on a char array and iteration is done using a Character...Please explain me how it is happening??...I thought that the iteration can only be done using a char..
class Print{
public static void main(String args[]) {
printCharacters("Java");
}
public static void printCharacters(String word) {
char[] characters = word.toCharArray();
for (Character ch : characters) {
System.out.println(ch);
}
}
}
Output:
J
A
V
A
Upvotes: 1
Views: 1631
Reputation: 3490
char
is a simple data type in Java, it is not an object like a String
. Every simple data type has a wrapper class to use it like an object (this is needed in some situations like when using an ArrayList
which only can store objects and no primetives like char
). The wrapper class for char
is Character
, int
is wrapped by Integer
, long
by Long
, float
by Float
and double
by the Double
class.
In this special case there is no need to wrap the char
with an Character
instance!
Upvotes: 0
Reputation: 53525
I'm not sure why all the downvotes, that's a legit question!
You actually had a good catch here, since the array is defined using a primitive char
the iteration in the for-loop should do the same:
for (char ch : characters) {
System.out.println(ch);
}
Unless we have a good reason to do autoboxing
and create a Character
object - this overhead is not needed (and it's actually a hit in performance and a waste of memory in the heap as well).
An example for such a "good reason" is when we want to use generics
which doesn't work with primitive types. However, this is not the case here.
Upvotes: 4