wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Behaviour of  Enums Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Behaviour of  Enums " Watch "Behaviour of  Enums " New topic

Behaviour of Enums

Dj Lalotra

Joined: Sep 14, 2009
Posts: 8
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.

Byju Joy
Ranch Hand

Joined: Sep 06, 2005
Posts: 84
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

Joined: Mar 15, 2009
Posts: 453

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


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

SCJP 5.0 SCWCD 5.0
Dj Lalotra

Joined: Sep 14, 2009
Posts: 8
I agree. Here's the link: http://aspose.com/file-tools
subject: Behaviour of Enums
jQuery in Action, 3rd edition