SCJP Sun Certified Programmer for Java 6 Study Guide : Exam 310-065

Katherine Sierra, Bert Bates

Mentioned 30

The Best Fully Integrated Study System Available--Written by the Lead Developers of Exam 310-065 With hundreds of practice questions and hands-on exercises, SCJP Sun Certified Programmer for Java 6 Study Guide covers what you need to know--and shows you how to prepare--for this challenging exam. 100% complete coverage of all official objectives for exam 310-065 Exam Objective Highlights in every chapter point out certification objectives to ensure you're focused on passing the exam Exam Watch sections in every chapter highlight key exam topics covered Simulated exam questions match the format, tone, topics, and difficulty of the real exam Covers all SCJP exam topics, including: Declarations and Access Control · Object Orientation · Assignments · Operators · Flow Control, Exceptions, and Assertions · Strings, I/O, Formatting, and Parsing · Generics and Collections · Inner Classes · Threads · Development CD-ROM includes: Complete MasterExam practice testing engine, featuring: Two full practice exams; Detailed answers with explanations; Score Report performance assessment tool Electronic book for studying on the go Bonus coverage of the SCJD exam included! Bonus downloadable MasterExam practice test with free online registration.

More on

Mentioned in questions and answers.

It wasn't that long ago that I was a beginning coder, trying to find good books/tutorials on languages I wanted to learn. Even still, there are times I need to pick up a language relatively quickly for a new project I am working on. The point of this post is to document some of the best tutorials and books for these languages. I will start the list with the best I can find, but hope you guys out there can help with better suggestions/new languages. Here is what I found:

Since this is now wiki editable, I am giving control up to the community. If you have a suggestion, please put it in this section. I decided to also add a section for general be a better programmer books and online references as well. Once again, all recommendations are welcome.

General Programming

Online Tutorials
Foundations of Programming By Karl Seguin - From Codebetter, its C# based but the ideas ring true across the board, can't believe no-one's posted this yet actually.
How to Write Unmaintainable Code - An anti manual that teaches you how to write code in the most unmaintable way possible. It would be funny if a lot of these suggestions didn't ring so true.
The Programming Section of Wiki Books - suggested by Jim Robert as having a large amount of books/tutorials on multiple languages in various stages of completion
Just the Basics To get a feel for a language.

Code Complete - This book goes without saying, it is truely brilliant in too many ways to mention.
The Pragmatic Programmer - The next best thing to working with a master coder, teaching you everything they know.
Mastering Regular Expressions - Regular Expressions are an essential tool in every programmer's toolbox. This book, recommended by Patrick Lozzi is a great way to learn what they are capable of.
Algorithms in C, C++, and Java - A great way to learn all the classic algorithms if you find Knuth's books a bit too in depth.


Online Tutorials
This tutorial seems to pretty consise and thourough, looked over the material and seems to be pretty good. Not sure how friendly it would be to new programmers though.
K&R C - a classic for sure. It might be argued that all programmers should read it.
C Primer Plus - Suggested by Imran as being the ultimate C book for beginning programmers.
C: A Reference Manual - A great reference recommended by Patrick Lozzi.


Online Tutorials
The tutorial on seems to be the most complete. I found another tutorial here but it doesn't include topics like polymorphism, which I believe is essential. If you are coming from C, this tutorial might be the best for you.

Another useful tutorial, C++ Annotation. In Ubuntu family you can get the ebook on multiple format(pdf, txt, Postscript, and LaTex) by installing c++-annotation package from Synaptic(installed package can be found in /usr/share/doc/c++-annotation/.

The C++ Programming Language - crucial for any C++ programmer.
C++ Primer Plus - Orginally added as a typo, but the amazon reviews are so good, I am going to keep it here until someone says it is a dud.
Effective C++ - Ways to improve your C++ programs.
More Effective C++ - Continuation of Effective C++.
Effective STL - Ways to improve your use of the STL.
Thinking in C++ - Great book, both volumes. Written by Bruce Eckel and Chuck Ellison.
Programming: Principles and Practice Using C++ - Stroustrup's introduction to C++.
Accelerated C++ - Andy Koenig and Barbara Moo - An excellent introduction to C++ that doesn't treat C++ as "C with extra bits bolted on", in fact you dive straight in and start using STL early on.


FORTH, a text and reference. Mahlon G. Kelly and Nicholas Spies. ISBN 0-13-326349-5 / ISBN 0-13-326331-2. 1986 Prentice-Hall. Leo Brodie's books are good but this book is even better. For instance it covers defining words and the interpreter in depth.


Online Tutorials
Sun's Java Tutorials - An official tutorial that seems thourough, but I am not a java expert. You guys know of any better ones?
Head First Java - Recommended as a great introductory text by Patrick Lozzi.
Effective Java - Recommended by pek as a great intermediate text.
Core Java Volume 1 and Core Java Volume 2 - Suggested by FreeMemory as some of the best java references available.
Java Concurrency in Practice - Recommended by MDC as great resource for concurrent programming in Java.

The Java Programing Language


Online Tutorials - The online documentation for this language is pretty good. If you know of any better let me know.
Dive Into Python - Suggested by Nickola. Seems to be a python book online.


Online Tutorials
perldoc perl - This is how I personally got started with the language, and I don't think you will be able to beat it.
Learning Perl - a great way to introduce yourself to the language.
Programming Perl - greatly referred to as the Perl Bible. Essential reference for any serious perl programmer.
Perl Cookbook - A great book that has solutions to many common problems.
Modern Perl Programming - newly released, contains the latest wisdom on modern techniques and tools, including Moose and DBIx::Class.


Online Tutorials
Adam Mika suggested Why's (Poignant) Guide to Ruby but after taking a look at it, I don't know if it is for everyone. Found this site which seems to offer several tutorials for Ruby on Rails.
Programming Ruby - suggested as a great reference for all things ruby.

Visual Basic

Online Tutorials
Found this site which seems to devote itself to visual basic tutorials. Not sure how good they are though.


Online Tutorials
The main PHP site - A simple tutorial that allows user comments for each page, which I really like. PHPFreaks Tutorials - Various tutorials of different difficulty lengths.
Quakenet/PHP tutorials - PHP tutorial that will guide you from ground up.


Online Tutorials
Found a decent tutorial here geared toward non-programmers. Found another more advanced one here. Nickolay suggested A reintroduction to javascript as a good read here.

Head first JavaScript
JavaScript: The Good Parts (with a Google Tech Talk video by the author)


Online Tutorials
C# Station Tutorial - Seems to be a decent tutorial that I dug up, but I am not a C# guy.
C# Language Specification - Suggested by tamberg. Not really a tutorial, but a great reference on all the elements of C#
C# to the point - suggested by tamberg as a short text that explains the language in amazing depth


nlucaroni suggested the following:
OCaml for Scientists Introduction to ocaml
Using Understand and unraveling ocaml: practice to theory and vice versa
Developing Applications using Ocaml - O'Reilly
The Objective Caml System - Official Manua


Online Tutorials
nlucaroni suggested the following:
Explore functional programming with Haskell
Real World Haskell
Total Functional Programming


wfarr suggested the following:
The Little Schemer - Introduction to Scheme and functional programming in general
The Seasoned Schemer - Followup to Little Schemer.
Structure and Interpretation of Computer Programs - The definitive book on Lisp (also available online).
Practical Common Lisp - A good introduction to Lisp with several examples of practical use.
On Lisp - Advanced Topics in Lisp
How to Design Programs - An Introduction to Computing and Programming
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp - an approach to high quality Lisp programming

What about you guys? Am I totally off on some of there? Did I leave out your favorite language? I will take the best comments and modify the question with the suggestions.

Java: SCJP for Java 6. I still use it as a reference.


O'Reilly Book:

  1. Real World Haskell, a great tutorial-oriented book on Haskell, available online and in print.

My favorite general, less academic online tutorials:

  1. The Haskell wikibook which contains all of the excellent Yet Another Haskell Tutorial. (This tutorial helps with specifics of setting up a Haskell distro and running example programs, for example.)
  2. Learn you a Haskell for Great Good, in the spirit of Why's Poignant Guide to Ruby but more to the point.
  3. Write yourself a Scheme in 48 hours. Get your hands dirty learning Haskell with a real project.

Books on Functional Programming with Haskell:

  1. Lambda calculus, combinators, more theoretical, but in a very down to earth manner: Davie's Introduction to Functional Programming Systems Using Haskell
  2. Laziness and program correctness, thinking functionally: Bird's Introduction to Functional Programming Using Haskell

Some books on Java I'd recommend:

For Beginners: Head First Java is an excellent introduction to the language. And I must also mention Head First Design Patterns which is a great resource for learners to grasp what can be quite challenging concepts. The easy-going fun style of these books are ideal for ppl new to programming.

A really thorough, comprehensive book on Java SE is Bruce Eckel's Thinking In Java v4. (At just under 1500 pages it's good for weight-training as well!) For those of us not on fat bank-bonuses there are older versions available for free download.

Of course, as many ppl have already mentioned, Josh Bloch's Effective Java v2 is an essential part of any Java developer's library.

Let's not forget Head First Java, which could be considered the essential first step in this language or maybe the step after the online tutorials by Sun. It's great for the purpose of grasping the language concisely, while adding a bit of fun, serving as a stepping stone for the more in-depth books already mentioned.

Sedgewick offers great series on Algorithms which are a must-have if you find Knuth's books to be too in-depth. Knuth aside, Sedgewick brings a solid approach to the field and he offers his books in C, C++ and Java. The C++ books could be used backwardly on C since he doesn't make a very large distinction between the two languages in his presentation.

Whenever I'm working on C, C:A Reference Manual, by Harbison and Steele, goes with me everywhere. It's concise and efficient while being extremely thorough making it priceless(to me anyways).

Languages aside, and if this thread is to become a go-to for references in which I think it's heading that way due to the number of solid contributions, please include Mastering Regular Expressions, for reasons I think most of us are aware of... some would also say that regex can be considered a language in its own right. Further, its usefulness in a wide array of languages makes it invaluable.

C: “Programming in C”, Stephen G. Kochan, Developer's Library.

Organized, clear, elaborate, beautiful.


The first one is good for beginners and the second one requires more advanced level in C++.

I know this is a cross post from here... but, I think one of the best Java books is Java Concurrency in Practice by Brian Goetz. A rather advanced book - but, it will wear well on your concurrent code and Java development in general.


C# to the Point by Hanspeter Mössenböck. On a mere 200 pages he explains C# in astonishing depth, focusing on underlying concepts and concise examples rather than hand waving and Visual Studio screenshots.

For additional information on specific language features, check the C# language specification ECMA-334.

Framework Design Guidelines, a book by Krzysztof Cwalina and Brad Abrams from Microsoft, provides further insight into the main design decisions behind the .NET library.

For Lisp and Scheme (hell, functional programming in general), there are few things that provide a more solid foundation than The Little Schemer and The Seasoned Schemer. Both provide a very simple and intuitive introduction to both Scheme and functional programming that proves far simpler for new students or hobbyists than any of the typical volumes that rub off like a nonfiction rendition of War & Peace.

Once they've moved beyond the Schemer series, SICP and On Lisp are both fantastic choices.

For C++ I am a big fan of C++ Common Knowledge: Essential Intermediate Programming, I like that it is organized into small sections (usually less than 5 pages per topic) So it is easy for me to grab it and read up on concepts that I need to review.

It is a must read for me the night before and on the plane to a job interview.

C Primer Plus, 5th Edition - The C book to get if you're learning C without any prior programming experience. It's a personal favorite of mine as I learned to program from this book. It has all the qualities a beginner friendly book should have:

  • Doesn't assume any prior exposure to programming
  • Enjoyable to read (without becoming annoying like For Dummies /
  • Doesn't oversimplify

For Javascript:

For PHP:

For OO design & programming, patterns:

For Refactoring:


  • C - The C Programming Language - Obviously I had to reference K&R, one of the best programming books out there full stop.
  • C++ - Accelerated C++ - This clear, well written introduction to C++ goes straight to using the STL and gives nice, clear, practical examples. Lives up to its name.
  • C# - Pro C# 2008 and the .NET 3.5 Platform - Bit of a mouthful but wonderfully written and huge depth.
  • F# - Expert F# - Designed to take experienced programmers from zero to expert in F#. Very well written, one of the author's invented F# so you can't go far wrong!
  • Scheme - The Little Schemer - Really unique approach to teaching a programming language done really well.
  • Ruby - Programming Ruby - Affectionately known as the 'pick axe' book, this is THE defacto introduction to Ruby. Very well written, clear and detailed.

Ok I know this might sound a bit silly, as it depends on the person, but on average how much time should I spend on preparing for SCJP? I already have some experience with Java (a few small and medium projects for my university, from implementing a simple "ships" game to some client-server stuff).

I was thinking about taking it around jun-july '10 so I'd have around 7-8months, is it enough/too much/not enough?

Also I've been looking for a good book, is there anything better than: "Sun Certified Programmer for Java 6 Study Guide" by Kathy Sierra and Bert Bates? And what about some practical questions (like "implement this and this" or "write a piece of code which does...")?

Ah and is it really worth it (I'd spend my own money). I'm not asking if it will make me a better programmer (as I've seen such a thread on stackoverflow alread) but do the employers even care about it?

I've never known being certified to help greatly but I don't live in the US or a hot bed of the IT industry. Someone else may be able to shed more light on this topic, but I can only assume that in a more vibing city for IT such as Silicon Valley or perhaps NY, it may look a little more impressive if two or more candidates are evenly matched. But if you're weak in interviewing skills or thinking on the spot etc, being certified might not help too greatly.

The book you mentioned sounds good and will probably be sufficient. I've always enjoyed the head first series too and in your case perhaps the Head First Java might be worth a look (also Kathy Sierra and Bert Bates).

Some other posts relating to SCJP may be of help too:

Does scjp help

is an scjp certificate worthwhile

It took me 3 weeks to prepare for the Java 6 exam, I have 0 professional Java programming experience. For someone who uses the language daily (like a java programmer) it should be even easier. I was very excited to get it over with as soon as possible, so I ordered the Kathy Sierra SCJP Sun Certified Programmer for Java 6 Study Guide at and one day shipped it to me so that I received it on a Saturday. As soon as it came, I started reading. That took about two weeks as the book is an 800 page monster with some self tests in the book that both give you good practice and teach you some specific details that the book did not mention in the actual chapter (a lot you can guess but not all...). For the last week I reviewed all the 2 Minute Drills and re-read the chapters that were API heavy. Also there are a lot of tables (important string methods, thread methods, file API methods, and concurrency). I also took the two master exams included in the book. I took them in study mode and attempted the question, then if it said wrong, I went and tried to figure out why it is wrong, then I went to the reference/hints if I needed. On the day of the exam I reviewed the File/String/Collections API an hour prior to the exam and took it.

I scored 90% so that's GREAT considering I do not have any Java work experience at all and prepared in 3 weeks. It should be much easier for any professional Java developer to prep/take. Although I have known of Java since it came out, and I used it for the occasional graduate and undergraduate program in college so I'm not totally new. Also, I know other C languages so I am used to much of the control structures, etc... However if I can figure out the API/language workings in three weeks enough to get a 90% any experienced java programmer should have no problem figuring out enough to pass. Still that book is giant, the 2 hours of daily train riding to work was a big help in getting the reading done.

Some people say you have to write a hundred small programs to figure things out. But that book is pretty good on details. The most important thing to write programs about (maybe I wrote 10) are the constructors/initializer blocks/static initializer blocks/to find out exactly what is inherited and to cement the order. And when casting a sub class as its parent, it is important to see what happens when you access the variables/overloaded methods. While the overloaded methods are simple and what is expected, accessing variables is not so straight forward. Trust me, write a few programs about it, especially where the super type/sub type have instance variables with the same name.

I think the main thing I got out of SCJP is a broad overview of the language. Java is a beast, the API/language is huge. Typically I just used the parts of the language I needed for each project/activity in Java and looked up the API as I went. Some key words (like transient) I just did not know. Also some interview trivia (like if you override equals what else must you override) I did not know (at least according to what a friend told me). Also I had no idea about things like the internationalization classes Locale, Calendar, DateFormat, NumberFormat, and Date. Really if I was writing serious Java software, I would probably use Calendar for date arithmetic needs. I don't think it will help me land a Java job as everyone seems to want Java experience prior to even giving you an interview. But if I ever do get an interview, the knowledge I gained from preparing the exam would definitely help me to better answer the questions (though I'm sure a lot of the specific API details will fade with time). Also now I feel more confident with Java. Still I can't say that I can just whip up a Java program on the white board that fully works because the API is very complex. A language like C is pretty small, include stdio.h/stdlib.h/string.h and memorize 30 functions and you can do a lot. Java has way more packages/classes to include and way more API. Also with expressions there are a ton of rules, promotions, casting, autoboxing, etc. which would be really easy to mess up. Though C has precedence hell, with the right parenthesis you can get away with a lot. Java is more strict on things (ie if(0) is an error). But the exam is worth it just for some additional trivia, although the exam is a bit frustrating, and if you look at the book it pretty much tells you that the exam deliberately picks tricky questions and edge cases in an attempt to confuse you. It will deliberately give bad indentation and other stuff to try to be tricky. I hate that because rather than focusing on you knowing the material reasonably, it focuses on trying to confuse you.

One thing of note, don't get thrown by the Master exam. I tried to take one in exam mode, and they gave 75 questions in 1.5 hours and I nearly decided to postpone the exam. The real exam is 60 questions and you get 3 hours. Also the questions on the actual exam are MUCH easier than on the master exam. My master exam score was 37%.... My last two times I just did it in study guide mode, attempted each question/if answer was wrong tired again/viewed reference once with the A exam and once with the B exam... I did fine on the exam and I am really really happy that I did not postpone it over the study guide, because now it is over and I can relax....

As explained in these Stackoverflow questions: question 1 & question 2 I understand that "String literals" are interned when:

String s = "abc"; 

And that the JVM will create a new String object instead of using an existing one from the String Pool when:

String s = new String("abc");

However, I have a doubt after reading the following two similar statements.

When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.

In this case, we actually end up with a slightly different behavior because of the keyword "new." In such a case, references to String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table.

So if we also put a reference in nonpool memory AND in pool memory when we create an object using "new" and based on the definitions above. Shouldn't the JVM also return the same reference when we do this?:

String one = new String("test");
String two = "test";

System.out.println(one.equals(two)); // true
System.out.println(one == two);      // false

Because when declaring the String literal String three = "test"; it will already exist in the pool? and therefore should return the same reference and print true? or do the previous statements mean that they will be put in pool memory but simply skipped when the new operator is used?

Maybe this will aid your understanding:

String literal = "test";
String one = new String(literal);
String two = "test";

System.out.println(literal == two); //true
System.out.println(one == two); //false

In the example you posted:

String one = new String("test");
String two = "test";

the reference passed to the constructor String(String) has the same value as the reference two due to interning. However, the string itself (referenced by these two references) is used to construct a new object which is assigned to reference one.

In this example, there are exactly two Strings created with the value "test": the one maintained in the constant pool and referenced whenever you use the literal "test" in an expression, and the second one created by the "new" operator and assigned to the reference one.


Perhaps you're confused about this statement:

When the compiler encounters a String literal, it checks the pool to see if an identical String already exists.

Note that this might be more clearly stated as:

When the compiler encounters a String literal, it checks to see if an identical String already exists in the pool.

Strings are only put in the pool when they are interned explicitly or by the class's use of a literal. So if you have, for example, this scenario:

String te = "te";
String st = "st";

String test = new String(te) + new String(st);

then while a String will exist with the value test, said String will not exist in the pool as the literal "test" has never occurred.

I'm already a developer it is my day job, and I've made a decent business out of it. I'd like to learn Java, but all the tutorials seem to start out as if the only language I know is English. Are there any good resources for a programmer to learn Java?

In addition to the excellent suggestions here, I have to add Kathy Sierra's and Bert Bate's excellent certification guide to the SCJP test. It really helped me when I started learning Java (coming from C++).

And if you ever do choose to get certified, this book is both challenging enough and interesting enough to easily get you past the exam.

In a Swing application, what is the best way to send data (interact) between two views?

Looking at the Coupling session in the Study Guide to the SCJP 6, it says:

All nontrivial OO applications are a mix of many classes and interfaces working together. Ideally, all interactions between objects in an OO system should use the APIs, in other words, the contracts, of the objects' respective classes.

If I understood this correct, the better way would be create interfaces (contracts) to each view, and if needed use this interfaces methods to retrieve data. Is this a good way? Spending a good time creating a lot of interfaces to say what is exposed by a view is ok?

Another way that I think is to have classes to hold the data (Model) of a view. In this case, is a good approach access directly this model classes?

Thanks in advance.

The notion of a separable model pervades Swing, as outlined in A Swing Architecture Overview. Typically, each model is represented by an interface; a few include an AbstractXxxModel with some basic event plumbing; and many have a DefaultXxxModel with a standard implementation.

Say there's the following base class:

package bg.svetlin.ui.controls;

public abstract class Control {
    protected int getHeight() {

Also, in the same package, there's a class that inherits:

package bg.svetlin.ui.controls;

public abstract class LayoutControl extends Control {
    public abstract void addControl(Control control);

Then, there's a third class in another package:

package bg.svetlin.ui.controls.screen;

public abstract class Screen extends LayoutControl {

And, finally, there's the implementation class, again in a different package:

package bg.svetlin.ui.controls.screen.list;    

public class List extends Screen {

    private final Vector controls = new Vector();

    public void addControl(Control control) {
        height += control.getHeight();

Even though List inherits from Control, and the getHeight() is protected, there's the following error:

getHeight() has protected access in bg.svetlin.ui.controls.Control

I've checked that my imports are right. I'm using NetBeans.

Any idea what's wrong? I thought protected fields and methods are visible to the children even if the latter are in a different package.


I thought protected fields and methods are visible to the children even if the latter are in a different package.

That's correct. The class itself has an access to the inherited protected members. But, what you're trying to do it to call the getHeight method on some Control reference. You're allowed to call it only on this instance!

For a better understanding, let me quote Kathy Sierra's SCJP Preparation Guide:

But what does it mean for a subclass-outside-the-package to have access to a superclass (parent) member? It means the subclass inherits the member. It does not, however, mean the subclass-outside-the-package can access the member using a reference to an instance of the superclass. In other words, protected = inheritance. The subclass can see the protected member only through inheritance.

This question was taken from Kathy Sierra SCJP 1.6. How many objects are eligible for garbage collections?

According to Kathy Sierra's answer, it is C. That means two objects are eligible for garbage collection. I have given the explanation of the answer. But why is c3 not eligible for garbage collection (GC)?

class CardBoard {
    Short story = 200;
    CardBoard go(CardBoard cb) {
    cb = null;
    return cb;

public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);
    c1 = null;
    // Do stuff
} }

When // Do stuff is reached, how many objects are eligible for GC?

  • A: 0
  • B: 1
  • C: 2
  • D: Compilation fails
  • E: It is not possible to know
  • F: An exception is thrown at runtime


  • C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
  • A, B, D, E, and F are incorrect based on the above. (Objective 7.4)

No object ever existed that c3 points to. The constructor was only called twice, two objects, one each pointed to by c1 and c2. c3 is just a reference, that has never been assigned anything but the null pointer.

The reference c3, that currently points to null, won't go out of scope and be removed from the stack until the closing brace at the end of the main method is crossed.

The object originally assigned to c1 is unreachable because the c1 reference was set to null, but the c2 reference has not been changed, so the object assigned to it is still reachable from this scope via the c2 reference.

To get this code to compile, I can either:

Why do I have to do this?

class Test {
    public static void main( String[] args ) {
          printAll( args );

    public static void printAll( String[] line ) {
        System.out.println( lines[ i ] );
        Thread.currentThread().sleep( 1000 ):

(Sample code from Kathy Sierra's SCJP book.)

I know that the exception which Thread.sleep() throws is a checked exception, so I have to handle it, but in what situation does Thread.sleep() need to throw this exception?

If a method is declared in a way that it can throw checked exceptions (Exceptions that are not subclasses of RuntimeException), the code that calls it must call it in a try-catch block or the caller method must declare to throw it.

Thread.sleep() is declared like this:

public static void sleep(long millis) throws InterruptedException;

It may throw InterruptedException which directly extends java.lang.Exception so you have to catch it or declare to throw it.

And why is Thread.sleep() declared this way? Because if a Thread is sleeping, the thread may be interrupted e.g. with Thread.interrupt() by another thread in which case the sleeping thread (the sleep() method) will throw an instance of this InterruptedException.


Thread t = new Thread() {
    public void run() {
        try {
            System.out.println("Done sleeping, no interrupt.");
        } catch (InterruptedException e) {
            System.out.println("I was interrupted!");
t.start();     // Start another thread: t
t.interrupt(); // Main thread interrupts t, so the Thread.sleep() call
               // inside t's run() method will throw an InterruptedException!


I was interrupted!
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at Main$

I've just read through the chapter on method-local inner classes in the SCJP book, and I'm really struggling to think of any practical use for them.

I've always been under the impression, that methods should be as small and specific to their task as possible (Orthogonality IIRC), so introducing even the simplest inner class would create heft and unwieldy methods.

Can anyone suggest a good practical usage for method local inner classes? So far it feels as if I might have to understand them purely for passing the exam, and not for use in everyday coding.


In most cases (e.g. for action listeners, runnables and such) you would use anonymous classes instead of method-local named classes.

But there is one thing which named classes can do and anonymous classes can't: implementing more than one interface, or extending a class and interfaces, too. Also, you can create more than one object of this class (without using a loop).

When overloading methods that contain parameters that dont match, the JVM will always use the method with the smallest argument that is wider than the parameter.

I have confirmed the above with the following two examples:

Widening: byte widened to int

class ScjpTest{

    static void go(int x){System.out.println("In Int");}
    static void go(long x){System.out.println("In long");}

    public static void main (String[] args){

        byte b = 5;




Boxing: int boxed to Integer

class ScjpTest{

    static void go(Integer x){System.out.println("In Int");}
    static void go(Long x){System.out.println("In Long");}

    public static void main (String[] args){

        int b = 5;




Both the above examples output "In Int" which is correct. I am confused though when the situation involve var-args as shown in the following example

class ScjpTest{

    static void go(int... x){System.out.println("In Int");}
    static void go(long... x){System.out.println("In lInt");}

    public static void main (String[] args){

        byte b = 5;   //or even with:  int b = 5




The above produces the following error: reference to go is ambiguous, both method go(int...) in ScjpTest and method go(long...) in ScjpTest match
1 error

Why does it not apply the same rule as in the previous examples? i.e. widen the byte to an int as it is the smallest that is larger than byte?

As AlexR pointed out, var-args is just like an array. Arrays of primitives (such as byte[] short[] int[] long[] float[] double[] seem to be internally compiled to the same class. That's why your overloaded methods are ambiguous. However the following code is perfectly valid:
static void go(int... x){System.out.println("In Int");}
static void go(Long... x){System.out.println("In lInt");}

This compiles successfully (since int[] and Long[] are different types), and produces the output In Int.
If you're preparing for SCJP, I would highly recommend you reading book SCJP Sun Certified Programmer for Java 6 Exam 310-065. The section Overloading in this book covers all the tricks with mixing boxing and var-args.

i heard, sleep() will lock the current sync method/block But here, when i call sleep() on thread 1, thread 2 is able to access the same block? Can anyone Explain?

public class Main {     
    public static void main(String args[])
        Thread1 t1 = new Thread1();
        Thread2 t2 = new Thread2();
        System.out.println("going to start t1");
        System.out.println("going to start t2");




public class Thread1 extends Thread{

    public void run() { 
        Syncc s1 = new Syncc();"T1:");



public class Thread2 extends Thread{

    public void run() { 
        Syncc s2 = new Syncc();"T2:");


public class Syncc{

    public void me(String s){
        for(int i=0; i<=5; i++)
            System.out.println(s+" "+" "+i);
            try {
            } catch (InterruptedException e) {              



going to start t1
going to start t2
T2:  0
T1:  0
T2:  1
T1:  1
T1:  2
T2:  2
T1:  3
T2:  3
T1:  4
T2:  4
T2:  5
T1:  5

BUT according to sleep() method, it should not unlock the current synchronization block right? if so the out put should be..

going to start t1 going to start t2

T1:  0
T1:  1
T1:  2
T1:  3
T1:  4
T1:  5
T2:  0
T2:  1
T2:  2
T2:  3
T2:  4
T2:  5

i mean after thread 1 execution only thread 2 should start right? Whats the issue?

Rules of Sleep, Yield and Join

  • Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.

  • A sleeping thread is guaranteed to sleep for at least the time specified in the argument to the sleep() method (unless it's interrupted), but there is no guarantee as to when the newly awakened thread will actually return to running.

  • The sleep() method is a static method that sleeps the currently executing thread's state. One thread cannot tell another thread to sleep.

  • The setPriority() method is used on Thread objects to give threads a priority of between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs recognize 10 distinct priority levels—some levels may be treated as effectively equal.

  • If not explicitly set, a thread's priority will have the same priority as the priority of the thread that created it.

  • The yield() method may cause a running thread to back out if there are runnable threads of the same priority. There is no guarantee that this will happen, and there is no guarantee that when the thread backs out there will be a different thread selected to run. A thread might yield and then immediately reenter the running state.

  • The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in the runnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will usually preempt the running low-priority thread and put the high-priority thread in.

  • When one thread calls the join() method of another thread, the currently running thread will wait until the thread it joins with has completed. Think of the join() method as saying, "Hey thread, I want to join on to the end of you. Let me know when you're done, so I can enter the runnable state."

I'm new in Java. I'm studying this program language and I guess that pure Java is not very useful. Can you advice me what related technologies / frameworks I should to study firstly?

You really should start with pure Java. Starting with anything else is like trying to run when you can't walk. Every framwork you'll learn afterwards will be much easier to understand.

Try to get a good book or something about the basics, for me personally studying for the SCJP certification really did the trick, if you're not interested in taking the exam yourself the book is still very educating:

SCJP Sun Certified Programmer for Java 6

I'm trying to learn java from bottom up, and I got this great book to read . Now I found example in the book about declaring Enums inside a class but outside any methods so I gave it a shot :

Enum CoffeeSize { BIG, HUGE, OVERWHELMING }; 

In the book its spelled enum and I get this compile message Syntax error, insert ";" to complete BlockStatements

Are the Enums that important at all?I mean should I skip it or its possible that I will be using those some day?

This is the correct way to declare an enum inside a class:

public class Main {
  enum Foo { One, Two, Three }

  public static void main(String args[]) {

You use the enum keyword, not Enum, which is the superclass of all enum instances.

In Sierra/Bates SCJP book page 797:

"java and javac [...] first look in the directories that contain the classes that come standard with Java SE. Then they look in the directories defined by classpaths"

Oracle documentation is stating the same order.

(I know I shouldn't do that but...) To test this behaviour I implemented and in directory: C:\dev\cmdline\TestProject\sources\java\util

package java.util;
public class HashSet {}


package java.util;
import java.util.HashSet;
public class Lol {
    public static void main(String... x) {
        HashSet a = new HashSet();

I get a compilation error when executing: C:\dev\cmdline\TestProject\sources>javac java/util/

java\util\ error: cannot find symbol a.add("lol"); ^ symbol: method add(String) location: variable a of type HashSet

...which means that the default classpath (current directory) is first used.

So, is the Oracle documentation wrong? How would you test the classpaths order?

Referring to the Oracle Documentation, the statement from the SCJP book may be oversimplified. The Oracle Documentation explicitly differentiates between the "Java Launcher" (java) and the Java Compiler javac. And in fact, the processes are somewhat different.

I'll try to extract the relevant parts that explain the behavior that you are observing:

(From How Classes are Found : How Javac and JavaDoc Find Classes:)

If a referenced class is defined in both a class file and source file, [...] javac uses class files, but automatically recompiles any class files it determines to be out of date. The rules for automatic recompilation are documented in the javac document for Windows or Solaris.

These linked docments contain the corresponding subsection (which is the same in both cases), from which I'll quote here again:

(From javac - Java programming language compiler : SEARCHING FOR TYPES:)

When compiling a source file, the compiler often needs information about a type whose definition did not appear in the source files given on the command line. [...]

When the compiler needs type information, it looks for a source file or class file which defines the type. [...]

A successful type search may produce a class file, a source file, or both. If both are found, you can use the -Xprefer option to instruct the compiler which to use. If newer is given, the compiler will use the newer of the two files. If source is given, it will use the source file. The default is newer.

If a type search finds a source file for a required type, either by itself, or as a result of the setting for -Xprefer, the compiler will read the source file to get the information it needs. In addition, it will by default compile the source file as well. You can use the -implicit option to specify the behavior. If none is given, no class files will be generated for the source file. If class is given, class files will be generated for the source file.

So to summarize: The javac compiler will find your source file for java.util.HashSet, as well as the class file from the bootstrap classes. But by default, it will compile the source file.

(And interestingly, there seems to be no easy way to convince him not to use the source as input: The -implicit option only determines whether a .class file is generated, but even if -implicit:none is set, it will still use the class that was created from the source...)

You can also use the -verbose option to watch this process in more detail:

javac -verbose java/util/

produces the following output:

[parsing started RegularFileObject[java\util\]]
[parsing completed 100ms]
[search path for source files: .]
[search path for class files: (A long list with rt.jar and related JARs)]
[loading RegularFileObject[.\java\util\]]
[parsing started RegularFileObject[.\java\util\]]
[parsing completed 0ms]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Object.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/String.class)]]
[checking java.util.Lol]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/AutoCloseable.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Byte.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Character.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Short.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Long.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Float.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Integer.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Double.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Boolean.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Void.class)]]
java\util\ error: cannot find symbol
  symbol:   method add(String)
  location: variable a of type HashSet
[checking java.util.HashSet]
[total 1072ms]
1 error

It does not even try to load the HashSet` class from the bootstrap JARs, but instead, directly refers to your source file:

[loading RegularFileObject[.\java\util\]]

In contrast, when you omit your own HashSet class, you'll see the expected output:

[parsing started RegularFileObject[java\util\]]
[parsing completed 100ms]
[search path for source files: .]
[search path for class files: (A long list with rt.jar and related JARs) ]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/util/HashSet.class)]]
[loading ZipFileIndexFileObject[c:\jdk1.8.0\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Object.class)]]

where it obtains the HashSet class from the rt.jar.

What is the difference between these two. I know Boxing is converting primitive values to reference. What is widening. Also what should be the sequence first boxing should be done or widening should be done?

Widening is when assign byte to int. i.e. you are widening the data type.

Sequence must be boxing then widening.

You CANNOT widen then box (int cannot be Long).

You CAN box then widen (int can become Object via Integer)

Note: Highlighted words are from Sun Certified Java Programmer SCJP 6 - Kathy Sierra

Does anybody has any experience with Sun training? I wonder if the extra $1000 is justified if I sign up for the classroom training vs. the web-based or cd-rom one?

Any advantages / disadvantages for both trainings?


I train people to pass the SCJP (I'm SCJP 1.5 + SCBCD and preparing SCJP 1.6 + SCWCD). The Sun courses (and material) are very basic and don't focus on the exam objectives. So my plan & advice is:

  1. Save the objectives in Evernote, print them or make a tattoo. That's what matters to pass the exam.
  2. The best book to pass (as stated above) is Kathy and Bert's.
  3. Obviously, setup a Java SDK + IDE of your choice (I love Eclipse) and start programming examples aimed at the cert.
  4. The only two webs you'll need are StackOverflow and JavaRanch where you can meet Kathy and Bert
  5. Use a tool to simulate the examination. I use Enthuware
  6. Relax, plan for two months if you're studying after work and pass the exam!


The SCJP class is incredibly easy, it is basically a test of your knowledge of the Java syntax and APIs.

The Bates & Sierra guide should get you through just fine. You shouldn't need anything else.

I recommends book SCJP and free web trainings, like or or similar

This was "my way";-)

I understand compiling Long F1 = 100; would fail, since 100 is an integer so compiler will box it to be Integer, and the wrapper types can not be widened.

But why would compiling Short S1 = 100; succeed? Thank you so much for helping.

From chapter 3 of SCJP:

The following is legal,

byte b = 27;

but only because the compiler automatically narrows the literal value to a byte. In other words, the compiler puts in the cast. The preceding code is identical to the following:

byte b = (byte) 27; // Explicitly cast the int literal to a byte

It looks as though the compiler gives you a break, and lets you take a shortcut with assignments to integer variables smaller than an int. (Everything we're saying about byte applies equally to char and short, both of which are smaller than an int)

In your case the compiler is using:

Short s = (short)100;

This is a similar question to the one appearing at: How to ensure Java threads run on different cores. However, there might have been a lot of progress in that in Java, and also, I couldn't find the answer I am looking for in that question.

I just finished writing a multithreaded program. The program spawns several threads, but it doesn't seem to be using more than a single core. The program is faster (I am parallelizing something which makes it faster), but it definitely does not use all cores available, judging by running "top".

Any ideas? Is that an expected behavior?

The general code structure is as following:

   for (some values in i)
        start a thread of instantiated as MyThread(i)
        (this thread uses heavily ConcurrentHashMap and arrays and basic arithmetic, no IO)
        add the thread to a list T

   foreach (thread in T)
        do thread.join()

I think I read in the SCJP book by Katherine Sierra that JVM's ask the underlying OS to create a new OS thread for every Java thread.

So it's up to the underlying Operating System to decide how to balance Java (and any other kind of) threads between the available CPU's.

I have a general idea of how the Garbage Collector works in Java, but my reasoning for destroying an object is not because I care about freeing up memory, but because of functionality. I can explain better with an example:

Say I'm making a game where money is involved. When a person picks up a Money object off the ground, I want to call that object's addTo method, which involves adding a value to that person's wallet.

public class Money {

  /** The value of this object. */
  private final int value;

  // constructor
  public Money(double x) {
    this.value = x;

  // Should be called when a Person picks up this object.
  public void addTo(Person bob) {

  public static void main(String[] args) {
    Person bob = new Person();
    Money dollar = new Money(1.00);
    dollar.addTo(bob);    // bob finds $1.00

After dollar is found, I don't want someone else to be able to pick it up. In other words, I don't want myself or any other program to be able to accidentally call the line:


So after Bob picks up the money, its value is added to his wallet and there's no need for an object representation of that value anymore. It's not that I care about the memory the object is using, but I don't want that object to be accidentally used somewhere else in the program. How do I destroy dollar besides setting dollar = null;?

You have NO CONTROL over Java Garbage Collection -GC- and there is now way that you can force the Java Virtual Machine to destroy an object for you.

You can call System.gc() [or Runtime.getRuntime().gc()] but that only suggests the JVM to run the Garbage Collection. The true is that the JVM is not supposed to listen to you for this and the GC execution is not guaranteed. Do not rely on that.

Regarding your design need, put your money in a bank (or a street if you want people to find them) and ask the bank to give you one. Assuming that the bank has only 1, then subsequent calls will return null.


I decided to remove some dust from my books and to quote a few lines from the Forcing Garbage Collection section of the 3rd chapter of the SCJP Study Guide. A book that I studied for pure masochism.

The first thing that should be mentioned here is that, contrary to this section's title, garbage collection cannot be forced.'s recommended that you never invoke System.gc() in your code - leave it to the JVM. is only possible to suggest to the JVM that it performs garbage collection. However, there are no guarantees the JVM will actually remove all of the unused objects from memory (even if garbage collection is run).

Garbage Collection is a harder concept than it seems...

I have the following two piece of code :

package com.akshu.multithreading;

 * @author akshu
public class MyThread extends Thread {
    protected  int b;   

    private int a;
    public void run() {;

        System.out.println("int a:"+a);



package com.akshu.utility;

import com.akshu.multithreading.MyThread;

public class MyUtility extends MyThread{

    public static void main(String args[])
        MyThread th1 = new MyThread();
        int d =th1.b;  // line1
        System.out.println("int d"+d);


with the above files of code i am trying to understand purpose of protected access modifier. In the file MyUtility , I am trying to refer variable b of class MyThread.But its giving me below error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The field MyThread.b is not visibilty.

My concern is variable b should be accessible from subclass as i have already extended the Mythread. But it is giving me compile time error. Also when i declare this variable as static in my superclass i was able to access it directly .So what wrong i am doing when i am trying to access via instance?

From Kathy Sierra's great book, explaining the misunderstanding of protected scope:

But what does it mean for a subclass-outside-the-package to have access to a superclass (parent) member? It means the subclass inherits the member. It does not, however, mean the subclass-outside-the-package can access the member using a reference to an instance of the superclass. In other words, protected = inheritance. Protected does not mean that the subclass can treat the protected superclass member as though it were public. So if the subclass-outside-the-package gets a reference to the superclass (by, for example, creating an instance of the superclass somewhere in the subclass' code), the subclass cannot use the dot operator on the superclass reference to access the protected member. To a subclass-outside-the-package, a protected member might as well be default (or even private), when the subclass is using a reference to the superclass. The subclass can see the protected member only through inheritance.

Thus, in your case, you try to use a reference to access a protected member outside parent's class package:

MyThread th1 = new MyThread();
int d =th1.b;  //b cannot be reached !

I want to do SCJP certification and dont want to join coaching for that,so need suggestion on Without joining coaching how to prepare for SCJP???

I did the exam with the only help of the "official book" and the tests it includes. Passed with 90-something%, after reading the book and doing all its exercises a couple of times.

You may also want to check the forums at JavaRanch.

If you have experience with Java, the exam will be relatively easy. If not, I would suggest you to code quite a lot for at least 6 months basic Java programs (console only is ok, no need to go into fancy web sites) to get a good grasp of the language and increase your chances to pass the test.

Ok so this isn't 100% programming question, for which I'm really sorry, but still this is the best place I know to ask it.

In ~2weeks time I'll have a job interview, first they'll make me take a test from Java and I was wondering what's the best way to prepare for it? I bet it will be something similar to SCJP (but probably much easier), are there any (short) books, tutorials that are worth reading? I did order the SCJP book by Sierra/Bates but I won't be able to read it before the test.

Don't get me wrong I do have experience with Java etc. but I really want to get the job so I want to go there well prepared.

Also marry Xmas to everyone, no matter what religion you are.

I have a little book with "Exam Cram" in its title. The emphasis is on "little;" you can read through it in a single evening. It describes in prose all the important features of Java, it contains tables of quick facts that will be essential, and it covers, briefly, all of the SCJP exam.

For the less than eidetic, it gives hints on how to write yourself a crib sheet from memory once the test starts (meaning you can carry a bit of what you need to know in short-term memory). There are also some tips on pitfalls and such. Finally, and perhaps most importantly, there is at least one practice exam in it (haven't looked at it in a while) and a bunch of drill questions.

Alas, from what I see at Amazon, the book I recommended only covers Java 2: Still, there are bound to be similar, more timely books.

This one: by Kathy Sierra is similar and about Java 6.

Some people would (and in fact did) recommend buying a general purpose Java book. Ideally, all you should have to do is learn "all of Java" and then you'd be ready for the exam. But this is not a winning strategy!

related anecdote

The first time I took my driver's test with the DMV, I had a long wait and quickly skimmed through a little info booklet they provided. I easily scored 100.

I later had to take the test again. Knowing the test was laughably easy, I spurned the booklet and failed the theoretical test. The booklet didn't contain anything I didn't already know: But being by the same people who administer the test, it contained the same wording, it had similar situations from the test, it emphasized similar topics and situations. In a few minutes, it could easily make the difference between passing and failing.


Same approach with these "prepare for test XXX" books. It's a racket, but the special-purpose prep books work better at preparing you for the test than general knowledge (or general knowledge books) do.

Can someone please explain why we we would use system.out.flush() in a simpler way? If there could be a chance of losing data, please provide me with an example. If you comment it in the code below nothing changes!

class ReverseApp{
    public static void main(String[] args) throws IOException{
    String input, output;

        System.out.print("Enter a string: ");
        input = getString(); // read a string from kbd
        if( input.equals("") ) // quit if [Enter]
        // make a Reverser
        Reverser theReverser = new Reverser(input);
        output = theReverser.doRev(); // use it
        System.out.println("Reversed: " + output);


Thank you

When you write data out to a stream, some amount of buffering will occur, and you never know for sure exactly when the last of the data will actually be sent. You might perform many operations on a stream before closing it, and invoking the flush() method guarantees that the last of the data you thought you had already written actually gets out to the file.

Extract from Sun Certified Programmer for Java 6 Exam by Sierra & Bates.

In your example, it doesn't change anything because System.out performs auto-flushing meaning that everytime a byte in written in the buffer, it is automatically flushed.

class Test {

    public static void main(String[] args) {

        System.out.println("1.. ");
        synchronized (args) {


            try {
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block



I am getting IllegalMonitorStateException monitor exception in this code. As per my understanding, because of synchronized block around args which is string array object, current thread must have acquired the lock and with the wait method, I am release the lock.

Can someone explain me the reason behind this exception?

Hi ankit i assume you are trying to learn some basic concepts of multithreading. try to get hold of some good online tutorials :

or try some basic good book.

The program you wrote actually doesn't need synchronization as there is only one thread (main). I know you are just trying your hands, therefore giving some insights. Even if you correctly called wait method on args(args.wait()) or synchronized on Thread.currentThread your thread may goes into indefinite wait (making your program unresponsive) because there is no other thread to notify your main thread.

Could we have a concrete superclass and then an abstract subclass? Could someone please explain how that works?

Thank You

Yes you can, and as long as you don't extend this class, you don't have to implement any methods.

Abstract class AbstractClass extends ConcreteClass{
    public abstract void method();

class ConcreteClass {
    public void doSomething(){


in the AbstractClass you don't have to implement the doSomething method, and in the ConcreteClass, you don't have to implement the method(). It would be better if you just try it yourself, and I recommend you to read this book

Thanks, Khalil.

I have two threads, one of them starts when i press a button. it just display values from 1-20 on the button btn.settext(""+ j). inside the listener fo that button I wrote the following:

btn_listener.setOnClickLstener(new Listener) {
    public void onClickListener(view v) {
        if (!t2.isAlive()) {

t2 is a thread. what happens at run time is, when I click the button while the thread2 is running nothing happens, but, when the thread2 finishes it job and i ckick the button the app crashes. any reason why that happens?

A thread cannot be restarted.

According to SCJP by Kathy Sierra:

After you called the start() method on a thread, it cannot be restarted; it runs until completion, then it dissolves, and is considered dead (although you can still call its specific methods on it, you cannot call start() again).

If you call start() a second time, it will cause an exception (an IllegalThreadStateException, which is a RuntimeException).

i want to learn coding web apps with java using glassfish.

i have bought a book "Beginning JAVA EE 6 Platform with Glassfish 3 - From Novice to Professional". I wonder if I can jump to this book directly or do I need to read a book about JAVA SE first?

I just want to develop web apps and not desktop applications nor browser java applets.

Thanks in advance.

Learning Java SE is not only learning to develop desktop applications or applets (which are basically just Swing/AWT). You learns how to use and write basic Java code and to make use of the basic Java SE API's. You still need them in Java EE. You'll need to write plain Java SE code in the Servlet methods, the DAO classes, the domain/model objects, etcetera. In practically all classes which you need to implement/create for Java EE.

So yes, I can strongly recommend to learn Java SE first, if not done yet. Sun has nice tutorials about that, check the chapter Trails Covering the Basics. If you prefer a book, then I can recommend the Head First Java and/or maybe the SCJP6 book of the same authors. You can however skip any Swing/AWT chapters. You don't need to know about them in Java EE.

mCallback = (OnHeadlineSelectedListener) activity;

This is some java code for an android app tutorial. I don't understand the what this is doing exactly. I know it's assigning a value to mCallback but what? why is OnHeadlineSelectedListener in parenthesis and then the activity object is right behind it, what the heck?

 * Copyright (C) 2012 The Android Open Source Project
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);

    public void onCreate(Bundle savedInstanceState) {

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));

    public void onStart() {

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById( != null) {

    public void onAttach(Activity activity) {

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");

    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item

        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);

That is type casting. For example: You have Animal interface with two methods, run and eat.

public interface Animal {
    public String run();
    public String eat(String food);

And you have class, which implements it, say, Cat class. Cat class has some extra methods, scratch and mew.

public class Cat implements Animal{
   public String run(){
     return "Run as a cat";
   public String eat(){
     return "Eat fish";
   public String mew(){
     return "MEW!!!!";
   public String scratch(){
     return "scratch-scratch-scratch";

Also, you have Dog class, which has bark method.

public class Dog implements Animal{
   public String run(){
     return "Run as a dog";
   public String eat(){
     return "Eat meat";
   public String bark(){
     return "BARK!!!!";

So, very often you need to work with you animal like with some exact animal (dog or cat). But compiler cat not make this casting without your help. So, you have to tell it what exactly you want:

public void Show{
  Cat cat = new Cat(); //you have a cat
  Dog dog = new Dog(); //and a dog
  Animal animal = null; //and animal
  dog = (Dog)animal; //and here is where compiler can't convert animal to dog without your help.
  Animal animal2 = cat; //But this casting it can make without your help, as it exactly knows what to do.

This one book is very usefull to learn Java. If you are really interested in understanding such things, you should read it. The full explanation of how casting works can be found in this book too.