File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question in K&B Chapter 8 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 "Question in K&B Chapter 8" Watch "Question in K&B Chapter 8" New topic

Question in K&B Chapter 8

Joss Armstrong

Joined: Jul 29, 2004
Posts: 17
On page 662 of SCJP book there is a question
1. public class TestObj {
2. public static void main(String[] args) {
3. Object o = new Object() {
4. public boolean equals(Object obj) {
5. return true;
6. }
7. }
8. System.out.println(o.equals("Fred"));
9. }
10. }

And the answers are
E. Compilation fails because of an error on line 4.
F. Compilation fails because of an error on line 8.
G. Compilation fails because of an error on a line other than 3, 4, or 8.

The correct answer given is G on the basis that compilation fails due to a missing ; on line 7 but I would have thought that this would be picked up by the compiler as a missing ; on line 8?
Equally you could say it was an error on line 3 because the assignment started on line 3 was not closed correctly.
Is there a standard way of knowing how to place errors on questions like this on the exam?

Faisal Ahmad
Ranch Hand

Joined: Aug 31, 2006
Posts: 355

If you notice line 3, you can see that an anonymous inner class is being declared that extends class Object. Line 7 is the end of that inner class. Line 8 doesn't belongs to the inner class discussed above. The assignment started at line 3 is not closed correctly on line 7. So, the compiler shows the error at line 7.
Joss Armstrong

Joined: Jul 29, 2004
Posts: 17
But when you try to compile this code you get the error: ';' expected
1 error

So line 8 is the logical answer to this question
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
This is the way the compiler tells about missing semicolons, So the semicolon is expected at the beginning of the next line following the statement that miss the semicolon.
[ September 18, 2007: Message edited by: Ahmed Yehia ]
I agree. Here's the link:
subject: Question in K&B Chapter 8
It's not a secret anymore!