Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes List of tricks to watch for in SCJP questions - please contribute 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "List of tricks to watch for in SCJP questions - please contribute" Watch "List of tricks to watch for in SCJP questions - please contribute" New topic
Author

List of tricks to watch for in SCJP questions - please contribute

Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
Hi all,

With your help I would like to compile a list containing the possible tricks that are nicely hidden in the java code that show up in SCJP questions. I realize that some of the tricks could be quite complex and difficult to describe in written English!! But let us try our best!!! Later we could compile a list of examples of each trick in terms of code if needed. Also I realize that this list could be quite long. But with all of your help, we can come up with a very helpful list for everyone!

If you have better ideas or suggestions please do share your thoughts!! If something similar had been discussed already, please do provide the information/link for that.

Here is my initial random list of tricks to watch for. Later we could try to classify these properly by topics (and also provide examples).

- Unreachable statements
- Accessing instance variables from static methods
- Uninitialized local variable
- Default access to methods in a class that implements an interface (watch out for this one!)
- Parent class only has a non-default constructor, whereas child class doesn't have a constructor or a default constructor
- Constructor called explicitly by name like Parent()
- Using assert to validate arguments to public methods (not illegal, but inappropriate)
- Starting a thread twice
- Calling wait() inside a non-synchronized method
- Assigning the result of a integer expression to a shorter data type without an explicit cast
- Calling add() on a Map data type
- Calling add() on a Generic type that is of type <? extends someType>
- Adding element outside the range of a subSet (of a TreeSet)
- Adding objects to a TreeSet/Map which didn't implement the Comparable/Comparator interface
- Using default access while overriding Object methods like equals(), toString() etc.
- Improper Exception hierarchy in catch blocks
- Method declares to throw an checked Exception when none is being thrown
- Passing a String argument to the renameTo() method of File
- Methods overloaded using varargs and array types (for example: int[] and int...)
- abstract and final used together
- Not using Object as an argument for the equals() method
- Saying a Runnable is a Thread
- Using <<< as a java operator
- Having static declarations inside inner classes
- Using static inside an interface or with abstract methods
- Synchronizing multiple threads on different objects/monitors
- Trying to change a file's path after it is instantiated

- .....shall post as things pop up to me....and much more with all of your help...

Thanks!
Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
I really appreciate the Idea . I would surely Contribute to it and request other aspirant to do so. and things which are directly given in k&B book could be left out. I think no use of writing those in it.


SCJP 6.0 96%

(Connecting the Dots ....)
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

- Calling wait() inside a non-synchronized method

- notify and notifyAll should also be called from a synchronized context. Also wait throws InterruptedException which must be properly handled.
- watch out for the main method. There might be a main method which returns int or one which takes String instead of String[] as argument or one which is not public...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
Thanks Sahil! Good points Ankit.

- I didn't think about the InterruptedException thrown by wait().
- Yeah, watch out for the main method signature, which might be a overload

Others that come to my mind now:

- Also Thread.sleep() being called without the InterruptedException being handled
- Non-final/constant values used in case statements
- abstract methods not being overridden
- Anonymous inner class having a constructor
- transient and volatile applied to non-instance variables
- Access modifiers (private, public, protected) applied to local variables
- Wrapper objets widening from one type to another

Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
1----- Inside While expression variable is being declared which is compilation error. eg while(int a)

2........ Enhanced for loop is using variable which is declared before , again a compilation error. for(temp : arrayreference)

3....... Remember compile time constants are being used in switch case expressions.

4........long variable is being used as an switch expression.

Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
Awesome contribution.

I am also compiling a few and the link can be found in my signature. Hopefully, they will bring to
expand now.

Happy Preparation,


Prithvi,
My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4339
    
    7

- Deliberately misleading class/method names. There's a good example in Sierra & Bates (chapter 2 self test) that I fell for the first time. Something like:

- Another one for assertions: using an error message expression that doesn't have a value
Rajeev Rnair
Ranch Hand

Joined: Mar 22, 2010
Posts: 308

Nice notes!!

watch out for finalize() method related qyestions!
The signature is protected void finalize() throws Throwable . So you don't need to write a try/catch inside finalize() if there is a throw new Exception();

watch out for differences between for(;true;){}, if(true){}, while(true){}, if(false){}, while(false){}, for(;false;) {} statements.


SCJP6, SCWCD5, OCP-JBCD5, OCE-JWSD6 OCE-JPAD6 , OCM-JEA5 1,OCM-JEA5 2,3 - Brainbench certifications: J2EE, Java2, Java2-NonGUI, JSP, SQL2000 Admin, SQL2000 Programming , Brainbench certified Java Programmer, Computer Programmer, Web Developer, Database Administrator
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
Awesome guys!!! Thanks for adding. I hope more folks jump in! Just to reiterate, the intention of my notes is more about looking for coding tricks that will result in a compile time error or a Runtime Exception. If one can figure this out these tricks in a given code quickly, then they can mark the appropriate answer (compiler error or Runtime Exception) and move on quickly to the next question, thereby saving time.

Of course I do understand that some questions don't really contain any tricks, but just ask for the result of something when the code is executed. In these cases, one has to be thorough with the fundamentals to be able to answer correctly.
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8801
    
    5
This is good you guys, but remember that wait(), notify(), and notifyAll() have been removed from the SCJP 6 exam.


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Prasad Kharkar
Ranch Hand

Joined: Mar 07, 2010
Posts: 438

I think we should see the Sun official page for updating of exam objectives at least 2 times a day
are there any new objectives added to the exam?

SCJP 6 [86%] June 30th, 2010
OCPWCD [84%] March 26th, 2013
If you find any post useful, click the "plus one" sign on the right
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
Hi Bert,

Thanks for the encouragement. I wish we could publish a list of such tricks in the appendix of a book or something.

Bert Bates wrote:This is good you guys, but remember that wait(), notify(), and notifyAll() have been removed from the SCJP 6 exam.


Ah, really? I do see the following in the SCJP objectives under the topic "concurrency" at this link: http://in.sun.com/training/catalog/courses/CX-310-065.xml

"Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.".
They do talk about object locking, but guess not about releasing that lock using wait() (from what you are saying). But I would have been jumping up and down if someone said that they removed the Date and Calendar APIs from the exam objectives. I can never sink those concepts into my brain wait(), notify() and notifyAll() are much easier to understand (and remember!).

Anyway thanks for pointing out this change. I wish there was a list to which I could subscribe and be informed when something changes in the objectives of a Sun exam.

P.S. Let me also take this opportunity to tell you how great of a resource the "Head first Java" book is. I have never enjoyed reading a book like that. I wish every book is written that way. The amount of imagination and creativity you have put into that book is amazing. It makes me crave for learning like never before!!! You have done an incredible job!
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

Thanks for the encouragement. I wish we could publish a list of such tricks in the appendix of a book or something.


It looks like a good candidate for a wiki. There is one here that documents trips / traps -> http://faq.javaranch.com/java/ScjpFaq#tripsTraps

You can edit that if you like.


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
Deepak Bala wrote:
Thanks for the encouragement. I wish we could publish a list of such tricks in the appendix of a book or something.


It looks like a good candidate for a wiki. There is one here that documents trips / traps -> http://faq.javaranch.com/java/ScjpFaq#tripsTraps

You can edit that if you like.


Thanks for the link. That is a useful one. I do find the list of some of the tricks there, but unsure about the wiki link you are referring to. Could you please provide the exact editable wiki link you are talking about.

Thanks.
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

There is an edit link on top of the page I mentioned. You can use that to edit the page content.
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
Deepak Bala wrote:There is an edit link on top of the page I mentioned. You can use that to edit the page content.


Thanks. I didn't realize that this is an editable twiki page. It works as you had suggested. Great.

wbrian radley
Greenhorn

Joined: Apr 03, 2008
Posts: 22
watch for those cases where the compiler takes into account that a variable is final and where it does not



watch for weird but valid syntax
the following all compile and run



and


Muneeswaran Balasubramanian
Ranch Hand

Joined: Mar 19, 2010
Posts: 138
Hi Guys,

Its quite helpful to me.Thanks to you all.


Cheers Munees
My Blog
dhiru kumar
Greenhorn

Joined: Jul 30, 2011
Posts: 21
Hi All,
First of all a heartful thanks to every one here .This one is for final instance variable and final local variable initialization.


If I am wrong somewhere, Do correct it.
Thanks
Dhiru
varaprasad dadi
Greenhorn

Joined: Mar 13, 2011
Posts: 1

Thanks Larry!! for initiating such useful discussion.Am moving closely to take up the exam soon!!!
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

1. I've seen some tricky questions where the code was all OK, but the answer was "Compilation Failure" because of missing import statements.
2. You can shadow variables, but not local variables in a block within the same method.
3. In a printf(), %d is NOT for doubles; the 'd' stands for 'decimal'. It is for int types
4. In a printf(), %b is NOT for byte; the 'b' stands for 'boolean'.
5. In StringBuilder and StringBuffer, the equals() method is the default == operator. equals() is defined for the String class.
6. Don't be confused by getting a lock on the Thread itself and getting a lock on the object's method that is being executed.
7. If a class implements an interface, but inherits the required methods, then it doesn't have to re-implement those required methods.
8. enums cannot be declared within a method (but classes can be).
9. A method that returns an Integer can't redefine a method that returns an int with the same argument list.
10. Watch out for trick questions where a constructor is final and thereby no instance can be constructed of it an no other class can subclass the class with a private constructor.
11. Watch out for missing semicolons for inner classes
12. To get a Date from a calendar, you might expect to call getDate() but actually, you can getTime()
13. Don't get compare() and compareTo() mixed up. compare() is for classes that implement the Comparator interface whereas compareTo() is for classes that implement the Comparable interface.
14. Remember that the following regex pattern must be doubly escaped. Instead of "\d" which is a compile-time error, you must have "\\d"
15. Watch out for an int being passed into a method that takes a short. Even if you know that the int can be represented as a short, the compiler flags this as a compile-time error.
16. In the Console class, the method readPassword() returns an array of char -- not a String.
17. If there is a class that doesn't implement Comparable, then when you add an instance of this class to TreeSet an exception will be thrown
18. Remember that the method System.console() is allowed to return null, so you can't rely on the console being available.
19. Beware of code that seems to look OK, but be very careful about "extends" and "implements" to be sure that they are used correctly.
nitin sethi
Ranch Hand

Joined: Jul 14, 2011
Posts: 59

Kaydell,

Could you please explain the below?

2. You can shadow variables, but not local variables in a block within the same method.
nitin sethi
Ranch Hand

Joined: Jul 14, 2011
Posts: 59

To add to the list:

1. It's legal to do an instance of test for any non-final class with an interface.
2. StringBuilder and StringBuffer classes don't have the concat method and hence the concatenation operator (+) does not work with only them.
3. A non-nested class can’t be static.
4. A method may be declared final in which case it cannot be hidden or overridden.
Rajanand Pandaraparambil Kuttappan
Greenhorn

Joined: Oct 26, 2011
Posts: 15
Keydell,

Could you please explain the ones below:-

6. Don't be confused by getting a lock on the Thread itself and getting a lock on the object's method that is being executed.

"getting a lock on the thread" == "thread object acts as the monitor" & "getting a lock on the object's method" == ?. We can get a lock on object only; not on its method, right? Or do you mean to say, a synchronized method, where method's object will act as the monitor ? If yes, in that case, is there any behavior difference for the monitor, as compared to the case where the thread object itself act as the monitor ?

10. Watch out for trick questions where a constructor is final and thereby no instance can be constructed of it an no other class can subclass the class with a private constructor.


By "constructor is final", you mean to declare it as 'private' right - not the java keyword 'final' right?

Thanks
Raj


Rajanand P K, Oracle Certified Professional, Java SE 6 Programmer.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

By "constructor is final", you mean to declare it as 'private' right - not the java keyword 'final' right?


Yes, I'm sorry, I meant that when the constructor is "private" it essentially makes the class final. Not that you use the "final" keyword, but it seems to me that when the constructors are all "private" that essentially you might as well make the class "final" by marking the class with the "final" keyword.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688


Kaydell,

Could you please explain the below?

2. You can shadow variables, but not local variables in a block within the same method.


In the code below, you can re-declare i



In the code below, the second declaration of i causes a compile-time error.

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688




6. Don't be confused by getting a lock on the Thread itself and getting a lock on the object's method that is being executed.


"getting a lock on the thread" == "thread object acts as the monitor" & "getting a lock on the object's method" == ?. We can get a lock on object only; not on its method, right? Or do you mean to say, a synchronized method, where method's object will act as the monitor ? If yes, in that case, is there any behavior difference for the monitor, as compared to the case where the thread object itself act as the monitor ?


Right, I didn't mean to say that you can get a lock on a method. You get a lock on the objects whose method is being executed when the method is marked as "synchronized". What I'm saying is that there is a difference between using an object as a monitor and using the thread as a monitor. That's what I meant to say.
Rajanand Pandaraparambil Kuttappan
Greenhorn

Joined: Oct 26, 2011
Posts: 15
What I'm saying is that there is a difference between using an object as a monitor and using the thread as a monitor.


As I see the Thread itself is an Object, I am not able to find any difference between using the Thread itself and using some-other-object as the monitor - syntactically, or functionally(wait, notify behavior). Or if I put it in this way, is there anything specifically to take care of for the use of statements - synchronized, wait and notify, if I use the Thread itself as a monitor, instead of some-other-object ?

Or am I completely off-track from what you were trying to put?

Thanks
Raj
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: List of tricks to watch for in SCJP questions - please contribute
 
Similar Threads
Traps to be aware of in any SCJP test !!!!! :)
Passed with 84%. Some tips...
SCJP5.0 passed!!
Study Notes from a person who secured 100%.
Syllabus for JCP