SCJP Chapter 1 questions...

I've been leading a certification group for my local JUG chapter for a few iterations. It's only now that I've been publishing the answers to questions that I get during our sessions. (Those I don't know and have to look up that is :)) I'll comment on the group in another post... but for now, on to the questions.

Q1: Is the variable arguments syntax valid for the main method?


I wrote the following code in a file named SimpleMain.java and saved it to a temp directory named Ch1\Q1

I then compiled and ran the code by doing the following...

D:\Ch1\Q1>javac SimpleMain.java

D:\Ch1\Q1>java SimpleMain
It Works!!!

D:\Ch1\Q1>

Q2: Is the question 4 in Chapter 1 valid?


The code is similar to the following. Saved as CoolEnum.java in the directory Ch1\Q2\A.

The above is valid. Just as in question 1 above, the code complied and executed.

D:\Ch1\Q2\A>javac CoolEnum.java

D:\Ch1\Q2\A>java CoolEnum
grainy plain

D:\Ch1\Q2\A>

If you're like our study group, or me especially, you'll look at line 8 in the CoolEnum.java file and think, "Isn't that class's field initially null?". The answer is yes, but to make it abundantly clear, consider the following modification to CoolEnum.java. Saved in another directory to avoid naming conflicts.

Produces the following

D:\Ch1\Q2\B>javac CoolEnum.java

D:\Ch1\Q2\B>java CoolEnum
grainy plain

D:\Ch1\Q2\B>

Huh... WHAT!!
Yes this is valid, but not a "best practice" way of accessing static fields. Consider the following code with out the enums. (This is an implementation of the Type-Safe-Enum pattern used for enums in Java 1.4.)

Which illustrates my point when compiled and ran in a new directory to avoid naming conflicts with Potatoes.

D:\Ch1\Q2\C>javac CoolSansEnum.java

D:\Ch1\Q2\C>java CoolSansEnum
grainy plain

D:\Ch1\Q2\C>


The answer... x.RUSSET is a valid way to access the static member RUSSET in the Potatoes class. But it should be accessed with Potatoes.RUSSET. Thus the clean looking code looks like...


For homework:


Why will the following NOT WORK. I know, do you?

6 comments:

MS M. said...

I don't know why. Seems to me it should work. Does it have something to do with static?

Big Mike said...

The answer will be discussed next meeting.

Mark R said...

RUSSET and FINGERLING cannot be resolved because the Enum name has not been specified. Consider if you had a second Enum, say IdahoPotatoes, which also defined RUSSET and FINGERLING. How would line 8 know which RUSSET to use?

MS M. said...

Chapter 3 is a hard chapter!

MS M. said...

Mike, come back - we missed you at the last meeting!!!!

MS M. said...

For the regulars to the study group: we are planning to work with topics in Chapter 6 for another week. We propose working through some exercises in the other book at the next meeting.