• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The enhanced for loop can't be used to initialize an array and modify its elements

 
Tiberius Marius
Ranch Hand
Posts: 115
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read something in Mala Gupta's book and i m not sure in understand or maybe it's mistake in the book .It's about the difference between normal for loop and enhanced for loop : 'The enhanced for loop can't be used to initialize an array and modify it's elements "
As long as the element type is not primitive the objects that are the elements can be modified right ? What am i getting wrong here ?

For example :
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That statement already confused some other candidates as you can read here. I also provided an example which proves the point in the book.

But your example is also true. If you use object references (like v which refers to a StringBuilder) you can obviously modify the StringBuilder itself by appending/deleting/inserting/... But you can't make v refer to another StringBuilder as in this code snippet:

The first and last enhanced for loop will print exactly the same now:
one
two


Hope it helps!
 
Tiberius Marius
Ranch Hand
Posts: 115
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it did , just as i suspected . But had to ask just in case i did not understand something correctly. Thanks
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic