wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes OCP Practice Exams Sef-Assessment Test 2 Q4 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "OCP Practice Exams Sef-Assessment Test 2 Q4" Watch "OCP Practice Exams Sef-Assessment Test 2 Q4" New topic
Author

OCP Practice Exams Sef-Assessment Test 2 Q4

Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
i did not understand the solution to this ques.:

1. public class WeatherTest {
2. static Weather w;
3. public static void main(String[] args) {
4. System.out.print(w.RAINY.count + " " + w.Sunny.count + " ");
5. }
6. }
7. enum Weather {
8. RAINY, Sunny;
9. int count = 0;
10. Weather() {
11. System.out.print("c ");
12. count++;
13. }
14. }

What is the result?
A. c 1 c 1
B. c 1 c 2
C. c c 1 1
D. c c 1 2
E. c c 2 2
F. Compilation fails.
G. An exception is thrown at runtime.

Answer (for Objective 1.1):
 C is correct. All of an enum’s values are initialized at the same time, and an enum’s
variables are treated as if they were instance variables, not static variables.
 A, B, D, E, F, and G are incorrect, based on the above.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

Jeet after compilation enums are changed into actual classes. So your Weather enum after compilation would look like



SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
thank you for your reply.Exactly according to your answer the enum constant initialization happens before main() is executed,i.e when the class is loaded at runtime. So printing the count values of the 2 enum constants in main() should print 2 2, not 1 2 as the correct answer says, right?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

should print 2 2, not 1 2 as the correct answer says

Check the answer again, it says 1 1 not 1 2. count is an instance variable not static...
gihan dissanayaka
Greenhorn

Joined: Sep 03, 2011
Posts: 8
ya this is prints 11.but i don't know count is static or not.
@ankit- why you are saying count is not static
Jeet Jain
Ranch Hand

Joined: Sep 01, 2011
Posts: 53
thank you so much Got it
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

Fields declared in an enum are instance fields. This is written in the JLS...
gihan dissanayaka
Greenhorn

Joined: Sep 03, 2011
Posts: 8
Thank you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: OCP Practice Exams Sef-Assessment Test 2 Q4