*
The moose likes Threads and Synchronization and the fly likes SCJP mock test question - threads and inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "SCJP mock test question - threads and inner classes" Watch "SCJP mock test question - threads and inner classes" New topic
Author

SCJP mock test question - threads and inner classes

paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20488
    ∞


<pre>
Question 5: Given the following class:
class Counter {
public static void main(String[] args) {
Thread t = new Thread(new CounterBehavior());
t.start();
}
}
Which of the following is a valid definition of CounterBehavior that would make Counter�s main() method count from 1 to 100, counting once per second?
Select the one right answer.
a)This class is an inner class to Counter:
class CounterBehavior {
for (int i = 1; i <= 100; i++);
try {
System.out.println(i);
Thread.sleep(1000);
} catch (InterruptedException x) {}
}
}
b) This class is an inner class to Counter:
class CounterBehavior implements Runnable {
public void run() {
for (int i = 1; i <= 100; i++);
try {
System.out.println(i);
Thread.sleep(1000);
} catch (InterruptedException x) {}
}
}
}
c) This class is a top-level class:
static class CounterBehavior implements Runnable {
public void run() {
try {
for (int i = 1; i <= 100; i++) {
System.out.println(i);
Thread.sleep(1000);
}
} catch (InterruptedException x) {}
}
}

</pre>
I'm thinking that none of them will work. The source claims the answer is "c". But a top level class that is static? I just tried it and it won't compile.

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Pawel Veselov
Ranch Hand

Joined: Jan 14, 1999
Posts: 165
Really non-understandable.
Only instances can create inner classes' instances, except inner class is static. But only inner classes can be static.
I think there is some sort of mistake in this question...

------------------
With best of best regards, Pawel S. Veselov ( aka Black Angel )


With best of best regards, Pawel S. Veselov ( aka Black Angel )
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20488
    ∞

Thanks Pawel for confirming that I'm not nuts.
J. Scott
Greenhorn

Joined: Mar 16, 2000
Posts: 4
Can't a static inner class also technically be considered a top-level class? Then the static inner/top-level class would have access to the outer class's static variables. If this is true then I think answer "C" is correct.
Not sure. I am still very new to Java, but would be interested in knowing if the above makes sense.
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20488
    ∞

Nope.
A static inner class has access to the private static stuff of the outer class.
J. Scott
Greenhorn

Joined: Mar 16, 2000
Posts: 4
This compiles, therefore answer "C" is true. (the code doesn't format well in this window; so please excuse the poor coding structure)
class Counter {
public static void main(String[] args) {
Thread t = new Thread(new CounterBehavior());
t.start();
}
static class CounterBehavior implements Runnable {
public void run() {
try {
for (int i = 1; i <= 100; i++){
System.out.println(i); Thread.sleep(1000);
}
} catch (InterruptedException x) {}
}
}}
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20488
    ∞

That's an inner class, therefore c is false.
C specifically states "This class is a top-level class:"
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Answer C is correct. I just tested it on my system to confirm
this. Answer B would be correct if the line that creates the
thread were changed as follows:
Thread t = new Thread(new Counter().new CounterBehavior());
Answer B also has a very subtle error in the for loop of the
run method. Notice the semicolon following the for loop. This
results in a do nothing for loop and causes a compilation error
in the try block since the variable i is not visible there.
Since answer B creates a non-static inner class it needs an
instance of the outer class before it can be instantiated itself.
Tony Alicea has a very good and concise description of inner
classes posted on the javacert forum. I can't find it right now
but maybe he can repost it here sometime.
Regards and have fun with Java.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
I forget to include this in my prior post. This happens to be
a very good question. Can u tell us in which mock exam u came
across this question. Thanks, Joe
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I agree with J. Scott on this one - according to Sun's Inner Classes Specification, a "static inner" class is actually called a top-level nested class, and is not considered inner. Two of the more direct quotes are here:
<blockquote>The static declaration modifier was designed to give programmers a way to define class methods and class variables which pertain to a class as a whole, rather than any particular instance. They are "top-level" entities.
The static keyword may also modify the declaration of a class C within the body of a top-level class T. Its effect is to declare that C is also a top-level class. Just as a class method of T has no current instance of T in its body, C also has no current instance of T. Thus, this new usage of static is not arbitrary.
As opposed to top-level classes (whether nested or not), inner classes cannot declare any static members at all. To create a class variable for an inner class, the programmer must place the desired variable in an enclosing class.
</blockquote>
and here:
<blockquote>"A non-static member class, or a class defined by a block or expression, is an inner class. All other classes are top-level."</blockquote>
Unfortunately it's not the clearest spec in the world, and many Java authors seem to have chosen to ignore this terminology in favor of "static inner" classes. This includes Roberts and Heller, who were involved in writing the SCJP exam. And even one of the official lists of objectives for the exam talks of "static inner" classes. So it's rather nebulous what the "correct" answer here is - you need to try to guess how a given question author intended the question - if an author talks about a "static inner class", he probably wants to use that terminology (unless one of the answers offered is "those don't exit").
In this particular question, it's particularly hard to tell what's on the author's mind. Since a) and b) take the time to specify that the class is "inner to Counter", I'm inclined to think they meant "inner" as synonymous with "nested", and since they didn't mention what c)'s class might be nested inside, it's not nested in anything. So no answer would be right. On the other hand, given that at least one answer should be right in a proper exam question, c) is the only one where I can see a loophole that allows it to be correct, so maybe it was intended that way.
Ugh. Anyway, the question's a mess, and the terminology's a mess. I just wanted people to be aware that there are competing usages out there, and that it can be perfectly valid to say "top-level nested class" instead of "static inner class". If Sun had written a clearer spec I'd even insist that it's always right to do so, but as it is both terms can be seen as correct.
OK, I'm off the soapbox for now.

[This message has been edited by Jim Yingst (edited February 10, 2000).]


"I'm not back." - Bill Harding, Twister
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Gee Jim, I think you're being a bit overly critical of this
question. Nowhere did it state that answer C was an inner class.
I think you're reading more into it than was actually stated.
I found the question confusing at first and thats why i investing
the time in testing it. Your discussion of the distinction
between a top level nested class and an inner class was
appreciated, however. The fact that the question has created
this much discussion (and hopefully understanding) is an
indication of how good it was. (I still want to know what mock exam it came from.) Regards, Joe
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20488
    ∞

I'm sorry I can't remember where the question came from. Note the date of the original post.
I just tried compiling it again and Java and here is what I got:
C:\CounterBehavior.java:1: Class or interface declaration expected.
static class CounterBehavior implements Runnable {
^
1 error

If an inner static class is a top level class, then what do we call a class that is not an inner class?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Joe-
I hadn't read your previous posts when I was composing my previous post (which took a while). So I was really addressing Paul's comments, not yours. But anyway...
The question is very good for discussion, but because of the ambiguities (which are really Sun's fault for giving us muddy definitions) it would make a bad actual test question, IMO.
I think we're all in agreement that J. Scott's code would work. But the problem says that CounterBehavior is a top-level class. Paul took that to mean it could not be nested (which it is in J. Scott's code) and I was arguing that it could be nested, but it depended on interpretation. I know it never said that answer C was an inner class. But he also didn't clearly state that it couldn't be nested. Maybe he meant to (in which case no answer), or maybe he didn't (in which case C is correct).
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Paul: I do remember having to move the curly brace that terminates the Counter class definition to the end of the file.
The way its written now CounterBehavior is really a separate
class not an inner (ahem, excuse me) nested class.
Lets drill it in our heads now: A static inner class is really a top level nested class.
I would think that any class thats not nested must be a top level class
[This message has been edited by Joe Java (edited February 10, 2000).]
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20488
    ∞

What do you call classes that are not involved with inner classes in any way?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
"The good old days."
Actually, I'd call them "top-level non-nested classes", because Sun never botherered to give them a proper name after they corrupted the definition of "top-level". I suppose "non-nested classes" would be sufficiently unambiguous also, but wouldn't be recognized as readily. Also, the way I read the spec, a top-level nested class is not an "inner" class, but it is a "nested" class. Which is why I take pains to say "nested" rather than "inner" if I can help it, because there's no disagreement about what "nested" means, while there is about "inner".
It's probably a good thing I don't work for Sun, because stuff like this would probably inspire me to do something rude and career-damaging (but oh so tempting).
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The original question is a little ambiguous, but not so much that the answer is less than obvious.
The purpose of the question is to confirm that you know A) the Runnable interface is required and B) That marking an inner class as static causes it to become a top-level class. The question makes no comment as to *where* the class is defined. The reason the question specifically calls the first two options "inner class" and the final option a "top-level class" is to cause confusion in those who don't know that a static inner becomes top-level. The Java Lang Spec is not fuzzy on this point. The third answer is the only one that *can* be right, and if you assume that it is right then static class CounterBehavior must be defined within the context of another class since that is the only time you can have a static class. Looking back at the question, it doesn't violate the premise of the question to put it there. So it *is* the correct choice. The difference in usage of "nested" and "inner" is a moot point. They are almost synonymous:
Nested classes are those defined within another class.
Inner classes are nested classes that aren't static, and therefore have a reference to an instance of the "outer" class.
For those who will be taking the SCJP:
This is just the kind of question you'll find on the exam. Here are a couple tips on how to get by this kind of question.
1) Remember that the questions have only one purpose in life, and that is to test your knowledge on very specific topic(s).
2) If there seem to be no clear answers, try to figure out what the question is trying to test you on. For me, that put many questions on the exam into perspective.
3) If you *know* only one can be right, and it's the kind of question that has at least one right answer, don't rack your brain, just put down that one. You can always check the box next to the question that directs you come back to it later.
4) The questins aren't meant to be a commentary on the Language Specification. Many of them are purposely ambiguous, so that raw facts alone aren't enough. You must also make decisions based on principles.
BTW: I HAVE worked for Sun
Mocky
Betty Reynolds
Ranch Hand

Joined: Feb 16, 2000
Posts: 111

4) The questins aren't meant to be a commentary on the Language Specification. Many of them are purposely ambiguous, so that raw facts alone aren't enough. You must also make decisions based on principles.

What principles are you referring to - OOP? If not a commentary, I hope the questions are at least based on the specification. That's what I'm basing my knowledge on.
If this comment seems inappropriate, I apologize. It's just that I am going through the rather painful process of preparing for the exam and I find the ambiguity and the lack of reliable information frustrating. Luckily, this journey is almost at an end. It's been quite a trip.


[This message has been edited by Betty Reynolds (edited April 24, 2000).]
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Here's a quote from the guide to "inner" classes on Sun's website (http://java.sun.com/products/jdk/1.1/docs/guide/innerclasses/spec/innerclasses.doc6.html#13908)
"The static keyword may also modify the declaration of a class C within the body of a top-level class T. Its
effect is to declare that C is also a top-level class."
Given this, answer C is ok since a static nested class is a top-level class (albeit with access to the static members of the containing class). It seems the question is really testing the victim's knowledge about the new nested - inner - top level terminology. I think it's rather a crummy trick on the part of the author, and I would hope the real test isn't like this, but if you take this slant on it then C is correct.
jp
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
i think there is a print mistake in that.
check for a) and b) you will find the difference
b) This class is an inner class to Counter:
class CounterBehavior implements Runnable {
public void run() {
for (int i = 1; i <= 100; i++) { // here { is not there.
try {
System.out.println(i);
Thread.sleep(1000);
} catch (InterruptedException x) {}
}
}
}
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hats off to all javagurus, the answer C is correct.. name your pgm as Counter.java and then follow as under: it works great..

class Counter {
public static void main(String[] args) {
Thread t = new Thread(new CounterBehavior());
t.start();
}
static class CounterBehavior implements Runnable {
public void run() {
try {
for(int i=1;i<=10;i++) {
System.out.println(i);
Thread.sleep(1000);
}
} catch(InterruptedException e) { }
}
}
}
surely its a static inner class....
Amit Zzz Kulkarni
Ranch Hand

Joined: Jul 05, 2000
Posts: 30
I agree whole heartedly with 'Mocky'. For those who will be taking the SCJP pls don't forget to go through the following JLS chapters :-
(*) Chapter 4 : Types,Values & Variables
for real basics.
(*) Chapter 14 : Expressions
for really tricky problems,read that and you will be enlightened.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: SCJP mock test question - threads and inner classes
 
Similar Threads
Hello Bartenders: A thread is lost
Synchronized Thread
Confused with mock exam question
Boone 1.1 Mock #5
Use of Private Constructor in Thread Example