Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Creating the MVP Current Progress

KHARAK SINGH
KHARAK SINGH
1,061 Points

I cannot understand this command?

for (char letter : toCharArray()) { }

2 Answers

anil rahman
anil rahman
7,786 Points

This for loop syntax is really simple:

for (char letter : toCharArray()) { 
   //do stuff for each item we loop through
}

It is basically saying ok so lets make a char variable and its called letter and for each item in my toCharArray() im going t set that item value to letter.

So its like for each letter in my array i am going to for example print out the value.

So if the array held the chars (h,e,l,l,o)

It would go through like this:

set this char letter = item number 1 which is "h" then do the code in the braces then again set char letter = item number 2 which is "e" the do the code in the braces and so on until it gets to the end of the array and you have now looped through and printed each item out.

Alex Popian
Alex Popian
977 Points

Why do we declare char letter inside the for method? Shouldn't it be declared before and then just say for( letter : toCharArray())? Sorry if this sounds dumb I'm not that good with java...

anil rahman
anil rahman
7,786 Points

I dont think ever seen a for loop without the data type specified. Its always been:

(char letter : listName)

or (String s : myArray)