Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about notation I never learned

 
Jay Dilla
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and rarely see
this is some code I saw on the Sun site:


What does mean and do?
I never learned this in any class or any of the Java books.
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a new form of the "for loop" ... I think it is being called the enhanced for loop.

for (Type var: arrayName) {

// your code goes here

}

will step through the array/collection called arrayName, place each element (which the Type specified must match) into var and then executes a pass through the loop. So essentially each element of the array gets a "ride through the loop" in var. Note that it does have some limits... it is only a one way path. You cannot do anything to var and WRITE it BACK into the array! This is only for picking up each item in the array and doing a pass through the code with it. If you need to write it back you need to use the old regular for loop or some other construct....
[ August 09, 2007: Message edited by: Bob Ruth ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"for(Type x : y)" basically means "for each instance of Type (referenced by x) in y..."

Note that y must be Iterable or an array.

For more details, see The For-Each Loop and JLS - 14.14.2 The enhanced for statement.
 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marc weber:


For more details, see The For-Each Loop .


"When you see the colon ( : ) read it as �in.� The loop above reads as �for each TimerTask t in c.� "

Ugh, was "in" already taken??? Would have been nice if they had chosen "in" to match the shell languages and Python, etc. Not to mention you wouldn't have to imagine it actually said in.
[ August 09, 2007: Message edited by: Red Smith ]
 
Jay Dilla
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you guys know if this is in the 1.4 SCJP exam? I came across it while studying. One guy mentioned it is new, so maybe it's in the 1.5 exam
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jay Dilla:
Do you guys know if this is in the 1.4 SCJP exam? I came across it while studying. One guy mentioned it is new, so maybe it's in the 1.5 exam

The enhanced for-each loop was new with 1.5. It is not on the 1.4 exam.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic