wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes for-each construct Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "for-each construct" Watch "for-each construct" New topic
Author

for-each construct

bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
hi all,

can i use for-each loop on String?

like for( Char c : String) ? must it always be an array?

Sridhar Santhanakrishnan
Ranch Hand

Joined: Mar 20, 2007
Posts: 317
It can also be an instance of java.lang.Iterable
bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
so not for String?
Sridhar Santhanakrishnan
Ranch Hand

Joined: Mar 20, 2007
Posts: 317
I dont think it works for Strings. But probably one of the ranchers has a different idea.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37936
    
  22
No, you can't use it for Strings. But there is a String method which can convert the String to an array, and it will work on that array.
bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
thank you!
dhiraj sardana
Greenhorn

Joined: Jan 21, 2009
Posts: 5
You can only iterate an array or an object which is an instance of java.lang.iterable through for each loop.But you can iterate over string by first coverting it to char array like:

String str = "Hello world";
char[] chArr = str.toCharArray();
for(char c:chArr)
{
System.out.println(c);
}
bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
thank you. now i understand
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37936
    
  22
Please don't simply give out answers like that, dhiraj sardana. Ytbryan Lim would have remembered a lot better for working out the methods, rather than being told what to do.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Don't forget that toCharArray() creates a new array. This takes memory, and time to fill its contents. Using a basic for-loop using length() and charAt() is better:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
ok thank you. i was considering the efficiency as well. your post comes in handy!

thank you everyone! javaranch is super!!
 
Don't get me started about those stupid light bulbs.
 
subject: for-each construct
 
Similar Threads
How to remove spaces
Taking a string, and putting the characters into an array
Why does cons remain equal to null?
program on simple string array
can anyone please tell me the number of objects created in the following case?