Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Behaviour of Enums

 
Dj Lalotra
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi to all Ranchers,

Could anyone please explain me why the output of the following program is "same old" instead of "newly new"?
I was just wondering ,at line 8,what would be the result if we place 'continue' instead of 'break'?

Please explain how this for loop is going to behave exactly?


public class McGee {
4. public static void main(String[] args) {
5. Days d1 = Days.TH;
6. Days d2 = Days.M;
7. for(Days d: Days.values()) {
8. if(d.equals(Days.F)) break;
9. d2 = d;
10. }
11. System.out.println((d1 == d2)?"same old" : "newly new");
12. }
13. enum Days {M, T, W, TH, F, SA, SU};
14. }

Appreciate your help.

-DJ
 
Byju Joy
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assignment of d2 happens 'after' the break call. That means when loop breaks d2 will have value of second last iteration TH, not F.
 
avi sinha
Ranch Hand
Posts: 453
Google Web Toolkit Hibernate Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first thing : please post a code within the code tag .


second thing : please quote the source

solution :
there is nothing wrong in the code and the behavior is what it should be
check out the loop :
let there be a count

now

and since enums override the == operator which will check the value that's why d1==d2 will give TRUE hence
output = same old

avi sinha

 
Dj Lalotra
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic