• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

OCP Practice Exams Sef-Assessment Test 2 Q4

 
Jeet Jain
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeet after compilation enums are changed into actual classes. So your Weather enum after compilation would look like

 
Jeet Jain
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you so much Got it
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fields declared in an enum are instance fields. This is written in the JLS...
 
gihan dissanayaka
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic