Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question in K&B Chapter 8

 
Joss Armstrong
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 355
Chrome Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But when you try to compile this code you get the error:

TestObj.java:8 ';' expected
System.out.println(o.equals("Fred"));
^
1 error


So line 8 is the logical answer to this question
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic