69
Sun Certified Programmer for Java 6 Study Guide SCJP Exam 310-065 Kathy Sierra Bert Bates McGraw Hill ISBN: 978-0-07-159106-5 Study Notes by Mahanthi Bukkapatnam

SCJP StudyGuide

Embed Size (px)

DESCRIPTION

SCJP Study Guide CNTP

Citation preview

  • Sun Certified Programmer for Java 6 Study Guide

    SCJP Exam 310-065

    Kathy Sierra Bert Bates

    McGraw Hill

    ISBN: 978-0-07-159106-5

    Study Notes by Mahanthi Bukkapatnam

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 2 of 69

    Table of Contents

    Introduction: Why these notes ............................................................................................ 5 Chapter 1: Declaration and Access Control........................................................................ 6

    Identifiers and JavaBeans ............................................................................................... 6 Declare Classes ............................................................................................................... 7 Declare Interfaces ........................................................................................................... 8

    Declare Interface Constants ........................................................................................ 9 Declare Class Members .................................................................................................. 9

    Variable args ............................................................................................................. 10 Constructors .............................................................................................................. 10 Modifiers allowed only on methods ......................................................................... 11 Modifiers allowed only on instant variables............................................................. 11 Modifiers allowed only on local variables................................................................ 11 Transient variables .................................................................................................... 12 Volatile variables ...................................................................................................... 12

    Enums ........................................................................................................................... 13 Chapter 2: Object Orientation........................................................................................... 14

    Polymorphism............................................................................................................... 14 Overriding and Overloading ......................................................................................... 14

    Overriding ................................................................................................................. 14 Overloading............................................................................................................... 15

    Reference variable casting ............................................................................................ 16 Legal Return Type ........................................................................................................ 17 Constructors and Initialization...................................................................................... 19 Statics............................................................................................................................ 20 Coupling and cohesion.................................................................................................. 20

    Chapter 3: Assignments .................................................................................................... 21 Literals, Assignments and Variables............................................................................. 21 Passing variables into methods ..................................................................................... 21 Array declaration, Construction and Initialization........................................................ 21

    Initialization .............................................................................................................. 21 Wrapper classes and Boxing......................................................................................... 22

    Boxing, == and equals()............................................................................................ 22 Overloading................................................................................................................... 23 Garbage Collection ....................................................................................................... 23

    Chapter 4: Operators ......................................................................................................... 24 Chapter 5: Flow control, Exceptions and Assertions........................................................ 25

    If statements .................................................................................................................. 25 Switch statements.......................................................................................................... 25 Loops and Iterators ....................................................................................................... 26

    Basic for Loop........................................................................................................... 26 Enhanced for Loop (for arrays)................................................................................. 26 Labeled Statements ................................................................................................... 26

    Exception handling ....................................................................................................... 27

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 3 of 69

    Assertion ....................................................................................................................... 28 Chapter 6: String, I/O, Formatting and Parsing ................................................................ 29

    String, StringBuffer and StringBuilder ......................................................................... 29 File and I/O ................................................................................................................... 29 Serialization .................................................................................................................. 29 Dates, Numbers and Currency ...................................................................................... 29 Parsing, Tokenizing and Formatting............................................................................. 29

    Chapter 7: Collections....................................................................................................... 30 hashCode() and equals() ............................................................................................... 30 Collections .................................................................................................................... 31

    Operations on a collection ........................................................................................ 31 Key Interfaces and Concrete classes......................................................................... 31 Ordered and Sorted ................................................................................................... 32 List interface ............................................................................................................. 33 Set Interface .............................................................................................................. 34 Map interface ............................................................................................................ 35 Queue Interface......................................................................................................... 36 Sorting Collections and Arrays................................................................................. 36 Comparable Interface................................................................................................ 36 Comparator Interface ................................................................................................ 37 Key Sort methods...................................................................................................... 37 Searching Arrays and Collections............................................................................. 37 Converting Arrays to Lists to Arrays........................................................................ 38 Using Lists ................................................................................................................ 39 Using Sets ................................................................................................................. 39 Using Maps ............................................................................................................... 39 Using Navigating (Searching) TreeSets and TreeMaps............................................ 39 Polling ....................................................................................................................... 40 Descending Order ..................................................................................................... 40 Backed Collection..................................................................................................... 40 Using PriorityQueue class......................................................................................... 40 Method overview for Arrays and Collections........................................................... 40 Method overview for List, Set, Map and Queue....................................................... 40

    Chapter 7: Generics........................................................................................................... 41 Generics and Collections .............................................................................................. 41

    Before Java 5............................................................................................................. 41 Generics and Legacy Code ....................................................................................... 42 Polymorphism and Generics ..................................................................................... 43 Generic Methods....................................................................................................... 43

    Parameterized Types ..................................................................................................... 44 Class.......................................................................................................................... 44 Methods..................................................................................................................... 45

    Chapter 8: Inner Classes ................................................................................................... 46 Overview and Key Points ............................................................................................. 46 Regular Inner class........................................................................................................ 47 Method Local inner class .............................................................................................. 48

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 4 of 69

    Anonymous inner class ................................................................................................. 50 Static Nested class......................................................................................................... 51

    Chapter 9: Threads............................................................................................................ 52 Overview....................................................................................................................... 52 Distinguish Thread and Thread of Execution ............................................................... 53 The Thread class ........................................................................................................... 53 Thread and the Runnable interface ............................................................................... 54 Defining Threads .......................................................................................................... 55 Instantiating Threads..................................................................................................... 56 Starting Threads ............................................................................................................ 57 Getting the name of the Thread .................................................................................... 57 Starting multiple threads ............................................................................................... 58 Thread Scheduler .......................................................................................................... 58 Thread States and Transitions....................................................................................... 59 Sleeping......................................................................................................................... 60 Thread Priorities............................................................................................................ 61 Yielding from a thread .................................................................................................. 61 Join() method ................................................................................................................ 62 Synchronization Code................................................................................................... 63 Key points about locking and synchronization............................................................. 64 Synchronizing static methods ....................................................................................... 65 More Synchronization points........................................................................................ 66 Thread interaction ......................................................................................................... 67 Exceptions related to threads ........................................................................................ 67 Summary - Points to keep in mind................................................................................ 68 Heading......................................................................................................................... 69

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 5 of 69

    Introduction: Why these notes

    To develop the habit of taking good notes. Help me in visualizing the concept and the relationship with other concepts. Help me pass the exam Help me to overcome my fear of taking exam.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 6 of 69

    Chapter 1: Declaration and Access Control

    Identifiers and JavaBeans

    Legal Identifiers

    Legal Identifier

    First char 1. $ 2. _ 3. Letter

    Subsequent chars 1. $ 2. _ 3. Letter 4. Number

    Size

    Unlimited

    Restrictions

    Java Keywords cannot be used

    Case

    Case sensitive

    Valid JavaBean method signatures

    get set isMyStatus() public void addMyListener(MyListener m) public void removeMyListener(MyListener m)

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 7 of 69

    Declare Classes

    Access modifiers for a class

    private, default, protected and public,

    Non-access modifiers for a class

    strictfp

    final

    abstract

    Strictfp applicable to:

    Only applicable to:

    1. Class 2. Method

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 8 of 69

    Declare Interfaces

    Interface methods:

    How to think about methods in an interface?

    All the methods in an interface are abstract. No non-abstract method in an interface

    Methods of an interface are public and abstract.

    Interface constants:

    Constants in an interface

    Public, static and final (in any combination)

    Static methods in an interface?

    No not allowed

    Restrictions for the methods in an interface

    Cannot be

    1. final 2. strictfp 3. native

    Extends and interfaces

    Interfaces can extend other interfaces. Only interfaces.

    An Interface can extend multiple interfaces. Weird it is mentioned in page 123

    Inplement and interface

    No implementing of other interfaces or classes

    Can a interface method be protected?

    No. It can only be public.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 9 of 69

    Declare Interface Constants

    One key rule to remember

    Constants in an interface are: public static and final

    Declare Class Members

    final arguments

    Final arguments cannot be modifying the argument in the method.

    What modifiers cannot go together.

    Abstract and static cannot go together.

    Why? Abstract needs an object, static means no object is necessart.

    The intention can be conflicting if you use both abstract and static together.

    Other method modifiers

    synchronized - Threads strictfp - floating point, scientific computing native - integrating legacy code.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 10 of 69

    Variable args

    Key rules

    Only 1 argument as var args

    Last argument

    Declared like the following: int x

    not like the following: int x

    How many arguments can be passed to a var arg variable?

    0 or more.

    Constructors

    Return type of a constructor

    Nothing.

    What happens if a return type is specified

    If a return type is specified, it becomes a method.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 11 of 69

    Modifiers allowed only on methods

    Modifiers allowed only for methods

    1. abstract 2. synchronized 3. strictfp 4. native

    Modifiers allowed only on instant variables

    Only for the instance variables

    1. transient 2. volatile

    Modifiers allowed only on local variables

    Only for local variables

    1. final

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 12 of 69

    Transient variables

    Transient means

    Please do not serialize this variable.

    Volatile variables

    Volatile means

    In a multi-threading situation, please do not perform any caching for there variables.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 13 of 69

    Enums

    2 places enums can be declared

    Outside a class Inside a class

    Can be declared in a method?

    No Never

    Access modifier rule when declared outside a class

    Not private or protected.

    Public or default allowed

    Semicolon rule

    Semicolon at the end of an enum declaration is optional

    Method to get all the enums as an array?

    values() returns the enum values as an array

    Does the values() method return the enums in the order by which they are declared?

    Yes

    Block and overriding for individual enum

    You can start a block and override specific methods for that particular enum.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 14 of 69

    Chapter 2: Object Orientation

    Polymorphism

    Extends rule

    A class can extend only one class.

    Abstract methods requirement

    Declaration should end with a semi colon.

    Overriding and Overloading

    Overriding

    Some rules

    Arguments must be the same

    Return type must be the same or must be a subtype

    access level can be less restrictive

    overriding method can throw any number of unchecked exceptions.

    Checked exceptions must be narrower or fewer.

    Can you override methods that are final or static

    No. Final means you cannot override it. Compiler Error If it is private in the super class, then you can redefine it.

    Static If the subclass has a method by the same name, it is called redefining, not overriding. No compiler error.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 15 of 69

    Overloading

    Some rules

    Must Change Arguments must change

    Optional 1. Return type 2. Access modifier 3. Throw new or broader exceptions

    See Page 115

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 16 of 69

    Reference variable casting

    Compiler while casting

    The compiler makes sure that the two types belong to the same inheritance tree

    Animal animal = new Animal() Dog dog = (Dog) animal;

    The above code, compiles but fails at runtime.

    Downcast

    You want to call a specific method.

    How to think about downcast

    Watch out for this point.

    (I was not aware of this before)

    The compiler checks to see if the class is in the same inheritance hierarchy and then allows it.

    If the compiler knows for sure it is not the same type, it will give an error.

    Downcast in not that safe

    Animal animal = new Animal(); Tiger tiger = new Tiger(); tiger = new Animal();

    This above code give an compile error. tiger reference cannot take an Animal object.

    If we provide a cast like: tiger = (Tiger)new Animal();

    The code compiles, but at runtime, gives a class cast exception.

    Casting across inheritance tree

    What happens when you cast say an Animal to a String.

    Example: Animal a = new Animal();

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 17 of 69

    String name = (String) a;

    You will get a compiler error.

    How to think about upcasting?

    It is safe. You can do it explicitly or implicitly.

    Legal Return Type

    Overriding methods return type

    The return type can be a subtype of the overridden method.

    Covariant what is it

    Need to do some research.

    Within the bounds of covariant returns.

    Overloading requirements

    Just changing the return type is not enough.

    The parameters should change for overloading to work.

    Valid return values

    On Page 128 and 129 there are 6 rules.

    In a method with an object reference return type, you can return any object type that can be implicitly cast to the declared return type.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 18 of 69

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 19 of 69

    Constructors and Initialization

    Default constructor

    If you dont provide a constructor, the compiler creates a default constructor.

    Syntax of a default constructor

    A constructor with no arguments.

    Scenario in which the default constructor will not be created

    If a non default constructor is provided, default constructor will not be created by the compiler.

    First statements in a constructor

    this() or super().

    this() or super can only occur as the first line in the constructor, if used other than the first statement, you will get a compiler error.

    Prerequisite for calling an instance method or access an instance variable from the constructor

    The call to super() must complete.

    Can you call the constructor from other methods?

    No, constructors can be called from other constructors only.

    Key Rule for constructors

    The first line in a constructor must be a call to super() or a call to this(). No exceptions.

    If the constructor does not have this() or super() what will the compiler put in?

    super();

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 20 of 69

    If you dont put a this or super as the first line, what will the compiler insert?

    super()

    The super class does not have a no arg constructor, what the rule that the subclass constructor has to follow.

    The first line of the constructor will have to call the super class constructor with the proper arguments.

    When constructors are chained, and you dont call super() what will happen.

    KaBoom the stack will explode.

    Can you have this() and super() in the same method.

    How can you? You cannot.

    Statics

    Coupling and cohesion

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 21 of 69

    Chapter 3: Assignments

    Literals, Assignments and Variables

    Passing variables into methods

    Array declaration, Construction and Initialization

    Initialization

    When is the instance initialization block run?

    Immediately after the call to super().

    Before the construction of the current object begins.

    What exception is thrown from a static init block?

    ExceptionInInitializationError

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 22 of 69

    Wrapper classes and Boxing

    Are Wrapper classes immutable?

    Yes

    Given a string representation of a value, how do you get its primitive?

    parseXXXX()

    Parse gets a primitive

    Given a string representation, how do you get the wrapper object

    valueOf()

    valueOf() you get a wrapper Object

    Given a wrapper how do you convert into other primitives?

    xxxxValue();

    From wrappers, how do you get the Hex and the Octal version of the value?

    toHexString() and toOctalString();

    Boxing, == and equals()

    Boolean

    == return ture if the values are same

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 23 of 69

    Byte

    == return ture if the values are same

    Character

    == return true if the values are within \u0000 to \u007f. Else false

    Short and Integer

    -128 to +127 return true, else false.

    Overloading

    Order for matching a method for overloading

    It is done in the following order.

    Primitive widening

    Auto Boxing

    Var args

    Garbage Collection

    How to invoke the garbage collector

    System.gc();

    finalize() method(?)

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 24 of 69

    Chapter 4: Operators

    Assignment Operators

    instanceof Comparison

    RACL

    Relational Operators

    Arithmetic Operators

    Conditional Operators

    Logical Operators

    TODO

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 25 of 69

    Chapter 5: Flow control, Exceptions and Assertions

    If statements

    Switch statements

    Valid data types allowed for a switch statement.

    Char, byte, short, int or enum.

    What data types are not allowed.

    Long, float and double.

    Requirement for the case constant

    Case constant must evaluate to the same type as the switch expression.

    The case constant must be a compile time constant

    If the case constant is final is that enough.

    No, if it is a final variable, it must have been initialized.

    Case constant ranges

    The case constant has to fall within the valid range of the switch expression data type.

    Can you have more than one label using the same value.

    No. The compiler will get confused.

    Are boxing allowed for case constants?

    Yes.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 26 of 69

    Loops and Iterators

    Basic for Loop

    Key requirement for condition.

    You can have only 1 test expression

    Last two things that happen in a for loop.

    1. Iteration expression 2. evaluating the conditional expression

    Enhanced for Loop (for arrays)

    Key requirement for the declaration section of the enhanced for loop

    Declaration should declare a new variable. Cannot use an old variable.

    Key requirement for the expression section

    Expression needs to be a array.

    Labeled Statements

    Can you label any statement?

    Yes

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 27 of 69

    Exception handling

    A return statement is encountered, will the finally block execute

    Yes. Definitely. (This is a point I learnt from this book)

    Will finally always execute?

    Yes, whether an exception happens or not.

    In a try-catch-finally code block, which sections are optional.

    Either one of the catch or finally blocks are required.

    You cannot ignore both catch or finally blocks.

    Unwinding the stack

    Order of the exception handlers.

    Specific Exception handlers come first

    Generic Exception handlers come last.

    Else it will result in a compile error.

    What are unchecked exceptions?

    Error and RuntimeExceptions

    Common exception

    See page 382

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 28 of 69

    Assertion

    What exception is thrown when an assertion fails

    AssertionError

    Example of assertions

    assert( x < y );

    assert( x < y ) : Message goes here..;

    Requirement for the expression after :

    It has to be capable of being converted to a String.

    Void cannot be converted to a String. So a method returning void cannot come in the part.

    JVM Command line switches

    -ea -enableassertions

    -da -disableassertions

    Selective enabling

    -ea:com.packagename.com

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 29 of 69

    Chapter 6: String, I/O, Formatting and Parsing

    String, StringBuffer and StringBuilder

    File and I/O

    Serialization

    Dates, Numbers and Currency

    Parsing, Tokenizing and Formatting

    TODO

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 30 of 69

    Chapter 7: Collections

    hashCode() and equals()

    Overriding equals

    Strings and Wrappers override equals and make good hashing keys

    Equals contract.

    Reflexive

    Symmetric

    Transitive

    Consistent

    Null

    equals() and hashCode()

    If equals() of 2 objects is true, hashCode() must be true

    If hashCodes() are not equal, then equals() has to be false.

    instanceof operator

    In the equals() method, use instanceof to see if the class is proper class.

    Transient variables and equals()

    When overriding equals(), do not use transient variables for comparision.

    Why? The explanation is a TODO item

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 31 of 69

    Collections

    Operations on a collection

    What are the operations?

    1. Add

    2. Remove

    3. Retrieve

    4. Find/Search an object or a group of objects in the collections

    5. Iterate through a collection.

    Key Interfaces and Concrete classes

    Key Interfaces

    Collection List Set

    NavigableSet SortedSet

    Queue Map

    NavigableMap SortedMap

    Key Concrete Classes

    Maps HashMap Hashtable TreeMap LinkedHashMap

    Sets HashSet LinkedHashSet TreeSet

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 32 of 69

    Lists ArrayList Vector LinkedList

    Queues PriorityQueue

    Utilities Collections Arrays

    Ordered and Sorted

    Difference

    Ordered is different from sorting

    But a sorted collection is in a natural ordered.

    Sorted collection is both sorted and ordered.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 33 of 69

    List interface

    Main concept of a list

    Cares about the index.

    Has methods related to the index

    Get(int index) indexOf(Object o) add(int index, Object obj)

    You want a fast iteration? Which list class do you use?

    ArrayList

    Main difference between ArrayList and Vector

    Vector methods are synchronized, will have a performance hit.

    You want a fast insertion and deletion, which list class you would want to use?

    LinkedList

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 34 of 69

    Set Interface

    Main point about a set

    A set does not allow duplicates

    Main way to think about set classes

    HashSet and TreeSet

    And HashSet has a cousin called LinkedHashSet

    HashSet and hashCode() relation

    The more efficient is the hashCode() method, the efficient is the access performance with HashSet

    LinkedHashSet and HashSet difference

    HashSet objects are not ordered.

    LinkedHashSet the insertion order is maintained.

    Tree Set

    Ascending Order by natural order.

    TreeSet implements NavigableSet.

    NavigableSet implements SortedSet

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 35 of 69

    Map interface

    Main point about a set

    Cares about unique identifiers

    Relies on the equals() method

    HashMap

    Unsorted and unordered map

    More efficient your hashCode(), the more efficient is the access performance.

    Null and HashMap

    HashMap allows one null key

    Allows multiple null values.

    Hashtable

    Synchronized version of HashMap.

    Does not allow anything that is null.

    LinkedHashMap

    Maintains insertion order

    Slower to add and remove

    Faster iteration

    TreeMap

    Sorted Order.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 36 of 69

    Queue Interface

    Main point

    FIFO first in, first out

    PriorityQueue

    ?

    Sorting Collections and Arrays

    How do you sort a collection

    Collections.sort( list );

    Comparable Interface

    Requirement for the sort method

    Sort() method takes a list

    The objects in the list must implement an interface called Comparable.

    Comparable interface

    You need to implement a single method called compareTo();

    Example:

    Int x = thisObject.compareTo( anotherObject );

    -ve thisObject < anotherObject 0 same +ve thisObject > anotherObject

    Implementation point

    You need to have access to the source code in order to implement the compareTo() method

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 37 of 69

    Key Method

    compareTo()

    Comparator Interface

    What can you do with this interface

    If you dont have access to the source code of the class that you want to sort, you can use the Comparator to do the compare operation.

    Key method

    compare()

    Key Sort methods

    Collections

    Collections.sort(list) Collections.sort(list, comparator)

    Arrays

    Arrays.sort( array ) Arrays.sort( array, comparator)

    Searching Arrays and Collections

    Search method

    binarySearch()

    Successful search

    Return the index of the element being searched

    0 and +ve indicate successful search

    -ve indicates unsuccessful search

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 38 of 69

    Unsuccessful search

    0 -> -1 1 -> -2 2 -> -3

    As 0 is a valid searh index.

    Collections state for searching

    Sorted.

    If not sorted, results unpredictable.

    Comparator requirements.

    If the sort is not done by the comparator, then the binarySearch() should not use the comparator.

    If the comparator is used to sort the collection, then pass the comparator as an argument to the binarySearch() method

    Converting Arrays to Lists to Arrays

    List and sets

    toArray()

    Arrays

    asList() Backed collections

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 39 of 69

    Using Lists

    Iterator

    Iterator i3 = d.iterator();

    While( i3.hasNext() ) { Dog d2 = I3.next(); //No need for the cast here as we are using generics }

    Using Sets

    What does the add method return

    True/False. If there is a duplicate object already present in the collection, then add() would return false.

    Using Maps

    Using Navigating (Searching) TreeSets and TreeMaps

    Key methods

    Lower() less than Floor() less than or equal Higher() greater than Ceiling() greater than or equal

    LowerKey() FloorKey() HigherKey() CeilingKey()

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 40 of 69

    Polling

    Key Idea

    Peek returns a copy (?) to verify this

    Poll return and removes the entry from the collection.

    Key methods

    pollFirst() pollFirstEntry() retrieves and removes the key value pair.

    pollLast() pollLastEntry()

    Descending Order

    Key methods

    TreeSet.descendingSet()

    TreeMap.descendingMap()

    Backed Collection

    TODO

    Using PriorityQueue class TODO

    Method overview for Arrays and Collections TODO

    Method overview for List, Set, Map and Queue TODO

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 41 of 69

    Chapter 7: Generics

    Generics and Collections

    Before Java 5

    Short coming of Collections before Java 5

    Not type safe.

    No way to check at compile time as to what type of object is being added to the collection.

    A non-generic collection can hold any kind of object!

    Advantage of Generics with collections.

    1. Ensures that the exact type is added to the collection. 2. You dont have to do an explicit cast when retrieving the

    object from the collection.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 42 of 69

    Generics and Legacy Code

    Example

    List myList = new ArrayList();

    List myList = new ArrayList();

    Public List changeStrings(ArrayList s) { }

    Public List changeStrings(ArrayList s) { }

    Will the generic code work with the legacy code?

    Yes. No problem.

    Will get a compiler warning.

    Explain Type Erasure

    After the code compiles, all the Generic type information is lost. The byte codes generated before and after generics were introduced, is exactly the same.

    Generics when do they come into play.

    Only at compile time.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 43 of 69

    Polymorphism and Generics

    Base type

    List myList = new ArrayList();

    This works just fine.

    Generic Type

    List myList = new ArrayList();

    This does not work.

    Compare Generic and Array example

    Object[] myArray = new JButton[3]; //Works fine

    List list = new ArrayList // Does NOT work

    Generic Methods

    Base type

    List myList = new ArrayList();

    This works just fine.

    What is the mechanism by which you tell the compiler that you will not be adding anything into the collection, but still let the method take in generic subtypes?

    ?

    Public void addAnimal(List animals)

    Public void addAnimal(List

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 44 of 69

    Do you have an equivalent for extends?

    Yes, with the super keyword.

    we can have the following

    public void addAnimal(? super Dog) { }

    Which means, accept any class which is a supertype of Dog.

    Key rule for using the ?

    While declaring - It cannot be used in the RHS while creating the object

    Reference declaration

    When creating a typed collection you cannot use the ?

    What is wrong with this statement?

    The following does not compile:

    List foo = new ArrayList

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 45 of 69

    carRental object will have to deal with the Car type only

    Can we use more than 1 parameter type

    Yes.

    Public class RentalGeneric { //T is the parameter type }

    Can the ? wildcard be used for classes?

    NO

    The following is not legal:

    Public class NumberHolder

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 46 of 69

    Chapter 8: Inner Classes

    Overview and Key Points

    What is the relationship the inner class shares with the outer class?

    Inner class instance has access to all members of the outer class instance even Private member of the outer class

    4 Types of inner classes

    Regular Inner class

    Method local Inner class

    Anonymous inner class

    Static Inner class

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 47 of 69

    Regular Inner class

    Example

    Class MyOuter {

    Private int x = 7; Class MyInner { Public void method() { System.out.println( X = + x ); } } }

    Requitement for Instantiating an Inner class

    You need to have an instance of the outer class.

    2 places an inner class instance is instantiated

    Within the outer class There is an implicit this reference to the outer instance.

    Outside the outer class

    Example for instantiating an inner class from the outside the outer class

    MyOuter outer = new MyOuter(); MyOuter.MyInner inner = outer.new MyInner();

    You need to have the outer instance, otherwise you cannot instantiate the inner class.

    Weird point

    Instantiating an inner class is the only scenario in which youll invoke new on an instance.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 48 of 69

    In other places, you invoke new to create a new instance.

    How do you reference the outer class instance?

    MyOuter.this

    MyOuter is the class name.

    Access modifiers for inner class

    Since inner class is like a member of the outer class all the modifiers applicable for member can be applied for the inner class as well:

    final

    abstract

    public

    private

    protected

    static

    strictfp

    Method Local inner class

    How do you define method local class and

    Where can you instantiate it?

    In a method.

    Only after you declare the class, can you instantiate an object of the method local inner class

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 49 of 69

    What method local inner object can and cant do?

    The instance can be created only in the method in which the inner class is declared.

    The inner class can access the outer class instance variables and methods.

    It cannot access the local variables of the method in which it is defined.

    It can access the local variables which are marked final and initialized(?)

    It the method is static, then the inner class can only access the static members of the outer class. as there is no this reference associated with a static method.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 50 of 69

    Anonymous inner class

    Plain old version 1

    Class Popcorn { Public void pop() { } }

    Class Food { Popcorn p = new Popcorn() { Public void pop() { } }; }

    Plain Old Version 2

    interface Popcorn { Public void pop() { } }

    Class Food { Popcorn p = new Popcorn() { Public void pop() { } }; }

    Key point to remember

    Through anonymous inner classes, we are creating an instance of a new subclass (we dont know its name).

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 51 of 69

    Static Nested class

    Example

    Class MyOuter { Static class MyInner { } }

    Instantiation:

    MyOuter.MyInner inner = new MyOuter.MyInner();

    Key point

    It can only access the static members of the outer class.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 52 of 69

    Chapter 9: Threads

    Overview

    What sections are in this chapter?

    1. Start new Threads 2. Recognize thread states and transitions.

    a. By what methods the transitions take place. 3. Object Locking 4. Write code to use wait, notify and notifyAll

    Can you explain why this order exists?

    1. First you need to know how to create a thread object and know how to start a thread.

    2. A thread of execution will be going through a few stages like the following:

    1) newly created thread. 2) Runnable eligible for running not waiting. 3) Running the thread is executing at this stage. 4) Blocked/waiting the thread is put on hold. 5) Dead the thread is finished executing.

    3. Need for Object locking the underlying mechanism for blocking threads to allow for atomic operations (Rewrite this line). The keywords the language provides for enabling this functionality.

    4. Inter-thread communication the methods provided on the Object itself.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 53 of 69

    Distinguish Thread and Thread of Execution

    What is a java.lang.Thread

    Thread is a object. It is created on the Heap.

    Thread of execution

    Thread of execution is a lightweight process, that has its own call stack.

    The Thread class

    What does a thread mean to you?

    A thread means: a thread of execution that has its own call stack

    What is one of the most important rule to keep in mind with regards to threads?

    Very little is guaranteed.

    What is the name of the main thread in Java

    It is called main.

    What are the important methods on the Thread object not on the object itself.

    start() yield() sleep() run()

    In which method does the action happen?

    run() method.

    The thread of execution will always begin by invoking the run() method.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 54 of 69

    Thread and the Runnable interface

    What are the 2 ways by which you can define and instantiate a thread.

    1. Extend the java.lang.Thread class. 2. Implement the Runnable interface.

    Can you explain as to why extending the Thread class is not a good design.

    SubClassing means that you are making a special class of the Thread class. This is very unlikely.

    What are the 2 benefits of implementing the Runnable interface.

    By implementing the Runnable interface, you can make the class be a part of a thread and at the same time you are free to extend other class.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 55 of 69

    Defining Threads

    Of the 2 ways to create threads, which is preferable.

    Implementing the Runnable interface

    What happens if you overload the run() method like run(String s)? Will the overloaded method be called?

    No.

    Only the run() method will be invoked from the new thread of execution.

    What are the 2 steps to define code to run in a separate thread by extending the java.lang.Thread class

    1. Extend the java.lang.Thread class 2. Override the run() method

    Example: public class Thread1 extends java.lang.Thread {

    public void run() { System.out.println(Here you go.); }

    }

    How do you define behavior to be run in a separate thread using the Runnable interface.

    Make the class implement the runnable interface and define the public void run() method.

    Example: public class Runnable2 implements Runnable {

    public void run() { System.out.println(Here you go.); }

    }

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 56 of 69

    Instantiating Threads

    How do you instantiate a subclass of the java.lang.Thread class

    Thread1 t1 = new Thread1()

    How do you instantiate a thread when a class has implemented the Runnable interface?

    Pass the instance of the class which implements Runnable as the argument to the constructor when creating an object of the Thread class.

    Runnable2 r = new Runnable2(); Thread t2 = new Thread(r);

    Overloaded constructors to keep in mind

    Thread() Thread(String name)

    Thread(Runnable r) Thread(Runnable r,String s)

    When Thread object is created, is a thread started?

    No. The Thread object has been created.

    When is a new thread created? When is a new call stack created?

    Call the start() method on the Thread class.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 57 of 69

    Starting Threads

    What happens when a start() method is called on a Thread object?

    A new Thread of execution starts a new call stack is created. The newly created thread in now in the Runnable state. When given a chance by the JVM scheduler, the run() method is called.

    Once the run() method completes, what is the state of the thread?

    Dead state.

    Getting the name of the Thread

    What is the method to get the name of the executing Thread?

    getName()

    On which class is this method declared?

    Thread class.

    How do you set the name of the Thread.

    1. Using the constructor Thread(String name) or Thread(Runnable r, String name).

    2. Calling the setName() on the Thread object.

    How does an instance of a Runnable know the Thread name? How do you get the reference to the currently executing thread?

    static Thread.currentThread() will return the reference to the currently executing thread.

    Do threads get a default name?

    Yes. If you dont provide a name, it may be given a default name.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 58 of 69

    Starting multiple threads

    Can you start multiple threads?

    Yes of course

    Is the order of the threads that are being executed guaranteed?

    No

    Once a thread had been started, can you start it again

    No. Never.

    What will happen if you start a thread the second time?

    An IllegalThreadStateException will be thrown at runtime.

    Thread Scheduler

    Who decides which thread should be run at any given moment

    The Thread Scheduler

    What does it do? It decides which thread is eligible to run.

    It make sure that only 1 thread is run.

    There will be only 1 currently running thread. What are some of the keywords related to scheduling?

    Eligible Runnable state Currently running thread Queue behavior Runnable pool Influencing the scheduler

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 59 of 69

    Can you control the scheduler?

    No.

    Can you influence the scheduler and if so how?

    Yes.

    By the following methods:

    Method of the Thread class public static void sleep(Long millis) throws InterruptedException public static void yield() public final void join() throws InterruptedException public final void setPriority(int newPriority)

    Methods of the Object class public final void wait() throws InterruptedException public final void notify() public final void notifyAll()

    Thread States and Transitions

    2 states already seen

    New Runnable Dead

    What other states can a thread be?

    Running Waiting/Blocking/Sleeping

    What is the common thing about waiting/blocking/sleeping

    The thread is not eligible to run.

    Not runnable.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 60 of 69

    What does Blocked mean?

    Thread may be waiting for a resource or an objects lock.

    Events that send a blocked thread to runnable state?

    The event that sends the thread to runnable is

    The availability of the resource Of the object lock is suddenly available.

    What does Sleeping mean?

    The code puts the Thread to sleep by calling the sleep() method.

    What event makes the thread move from the sleep state to the runnable state

    Once the sleep time expires, the thread wakes up and is now put in the runnable state.

    What does wait() mean?

    The thread waits for a notification from another thread.

    Can one thread block another thread?

    No. The way threading is defined is that 1 thread does not have the knowledge about other threads. It can block the current thread, never an another thread.

    Suspend() stop() and resume() does this but these methods have been deprecated.

    Sleeping

    Key method

    Thread.sleep();

    What does interruption mean

    When a thread is sleeping, it can be interrupted and it will then throws the InterruptedException.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 61 of 69

    What do I have to remember about this method?

    Sleep() is a static method. You cannot put another thread to sleep. Only the currently executing thread.

    Thread Priorities

    What is the method used to set the priority?

    setPriority()

    Pre defined priorities

    MIN_PRIORITY NORM_ PRIORITY MAX_PRIORITY

    MIN 1 NORM 5 MAX 10

    Yielding from a thread

    Key method

    Yield()

    What does calling yield() do?

    It allows the thread scheduler to make other thread of the same priority run

    Is this behavior guaranteed?

    No

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 62 of 69

    Willing calling yield make the thread go to the blocked/waiting/sleeping State?

    No. It may takes it to the runnable state at the most and this also is not guaranteed

    Join() method

    Key Method

    Join()

    Is this method static?

    No. Why? This method is called on a thread object.

    What does t.join() mean?

    The currently executing thread is joined to the end of the thread on this the join() method is called.

    The current thread is blocked.

    t.join() means:

    Join me (the current thread) to the end of t, so that t must finish before I (the current thread) can run again.

    t.join(5000) means

    wait until thread t is done, but if it takes longer that 5,000 milliseconds, then stop waiting and become runnable anyway

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 63 of 69

    Synchronization Code

    Explain Race Condition.

    Multiple threads can access the same resource and corrupt data.

    Before a method/operation completes, another thread races in and reads/updates the data.

    What are 2 things to do to protect the data?

    1. Mark the variable private 2. Synchronize the code that modifies the variable.

    How does synchronization work?

    With locks.

    Acquiring locks are known as

    1. Getting the lock 2. Locking the object 3. Locking on the object 4. Synchronizing on the object

    What can you call the object whose lock we are acquiring?

    Monitor

    Lock and the monitor are they different.

    Technically yes.

    But the two can be used interchangeably

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 64 of 69

    Key points about locking and synchronization

    Only methods of or code blocks can be synchronized.

    How many locks does an object have?

    One

    Do you need to synchronize all the methods of a class?

    No, only the methods that access the mutable state needs to be synchronized.

    How many threads execute a synchronized method at a given time?

    Only 1 method can be executing an synchronized method at a given time.

    Only after a thread completes executing a method, will any other waiting thread be given the opportunity to run this method.

    If a thread goes to sleep, does it release its locks?

    No. It does not release them.

    Can a thread acquire multiple locks?

    Yes.

    Can a thread acquire the same lock twice?

    Yes. If it already has it, no problem.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 65 of 69

    Synchronizing static methods

    Can you synchronize static methods?

    Which lock is acquired for static methods?

    The lock on the methods java.lang.Class instance.

    Public synchronize static method() { Return 3;

    }

    Public synchronize static method() { Synchronize(MyClass.class) {

    Return 3; }

    }

    Equivalent to:

    Public synchronize static method() { Class c1 = Class.forName(MyClass) Synchronize(c1) {

    Return 3; }

    }

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 66 of 69

    More Synchronization points

    How do you describe as to what a thread that is waiting on a synchronized method doing?

    Blocked on the objects lock.

    Goes into a waiting pool for that particular object.

    Once the lock on the object is released (a thread which holds the lock relinquishes it after finishing the synchronized method), this thread may get the lock and only then it will go into the runnable state and then into the running state.

    What is the necessary condition for a synchronized method or block to block synchronized method or block.

    Only if the two are lock on the same object.

    Key goal of synchronization

    Threads working with the same data need to go one at a time.

    Comment on static synchronized method and a non-static synchronized method.

    Static synchronized method and a non-static synchronized method will not block each other.

    If you access a static field using a non-static method, two threads might invoke that method using two different this instances.

    A simple rule to make a class thread safe -

    Methods that access changeable fields need to be synchronized.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 67 of 69

    Thread interaction

    Important point about wait/notify

    Wait(), notify() and notifyAll() must be called from a synchronized context.

    A thread cant invoke a wait or notify method on an object unless it owns that objects lock.

    If the wait() method is called on an object whose lock is not held by the currently executing thread, IllegalMonitorStateException is thrown.

    IllegalMonitorStateException is not a checked exception.

    Exceptions related to threads

    Important exceptions

    IllegalThreadStateException not a checked exception IllegalMonitorStateException not a checked exception

    InterruptedException checked exception sleep() - static join() - non static wait() non static

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 68 of 69

    Summary - Points to keep in mind

    Final methods

    wait notify notifyAll join() setPriority()

    This means that a programmer cannot override the default functionality

    Static methods

    sleep() yield()

    Since these are not final can a programmer override these methods.

    When you see Obj.syncMethod() What do you think

    The syncMethod() is synchronized on the obj.

    InterruptedException

    Anytime you see sleep(), wait() and join() you make sure that the InterruptedException is caught. Else, the code will not compile.

    Calling start() on a dead thread

    Will throw the IllegalThreadStateException at runtime

    Calling wait on an object whose lock is not held

    Will throw the IllegalMonitorStateException at runtime

    Calling wait() from outside a

    TODO: to find out as to what will happen.

  • SCJP 6.0 Study Guide - CNTS

    Mahanthi Bukkapatnam Page 69 of 69

    synchronize block?

    Key classes, methods and exceptions

    java.lang.Thread start() (IllegalThreadStateException)

    java.lang.Runnable Public void run()

    public static void Sleep(long millis) throws InterruptedException public static void yield() public final void join() throws InterruptedException public final void setPriority(int newPriority)

    public final void wait() throws InterruptedException (IllegalMonitorStateException) public final void notify() public final void notifyAll()

    Runtime Exception, not checked exception

    Heading

    Line

    Line