Professional Documents
Culture Documents
Kathy Sierra
Bert Bates
McGraw Hill
ISBN: 978-0-07-159106-5
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
Mahanthi Bukkapatnam
Page 2 of 69
Mahanthi Bukkapatnam
Page 3 of 69
Mahanthi Bukkapatnam
Page 4 of 69
Mahanthi Bukkapatnam
Page 5 of 69
Legal Identifier
First char
1. $
2. _
3. Letter
Subsequent chars
1. $
2. _
3. Letter
4. Number
Size
Unlimited
Restrictions
Case
Case sensitive
Valid JavaBean
method signatures
get
set
isMyStatus()
public void addMyListener(MyListener m)
public void removeMyListener(MyListener m)
Mahanthi Bukkapatnam
Page 6 of 69
Declare Classes
Non-access
modifiers for a class
strictfp
final
abstract
Mahanthi Bukkapatnam
1. Class
2. Method
Page 7 of 69
Declare Interfaces
Interface methods:
How to think about
methods in an
interface?
Interface constants:
Constants in an
interface
Static methods in an
interface?
No not allowed
Cannot be
Extends and
interfaces
1. final
2. strictfp
3. native
Inplement and
interface
Can a interface
method be
protected?
Mahanthi Bukkapatnam
Page 8 of 69
final arguments
What modifiers
cannot go together.
Other method
modifiers
Mahanthi Bukkapatnam
synchronized - Threads
strictfp
- floating point, scientific computing
native
- integrating legacy code.
Page 9 of 69
Variable args
0 or more.
Constructors
Return type of a
constructor
What happens if a
return type is
specified
Nothing.
Mahanthi Bukkapatnam
Page 10 of 69
Modifiers allowed
only for methods
1.
2.
3.
4.
abstract
synchronized
strictfp
native
1. transient
2. volatile
Mahanthi Bukkapatnam
1. final
Page 11 of 69
Transient variables
Transient means
Volatile variables
Volatile means
Mahanthi Bukkapatnam
Page 12 of 69
Enums
2 places enums can
be declared
Outside a class
Inside a class
Can be declared in a
method?
No Never
Semicolon rule
Yes
Block and overriding You can start a block and override specific methods for that
for individual enum
particular enum.
Mahanthi Bukkapatnam
Page 13 of 69
Abstract methods
requirement
Some rules
Mahanthi Bukkapatnam
Page 14 of 69
Overloading
Some rules
Must Change
Arguments must change
Optional
1. Return type
2. Access modifier
3. Throw new or broader exceptions
Mahanthi Bukkapatnam
Page 15 of 69
The compiler makes sure that the two types belong to the same
inheritance tree
Animal animal = new Animal()
Dog dog = (Dog) animal;
Downcast
If the compiler knows for sure it is not the same type, it will give
an error.
Downcast in not that safe
Casting across
inheritance tree
Mahanthi Bukkapatnam
Page 16 of 69
Covariant what is
it
Overloading
requirements
Mahanthi Bukkapatnam
Page 17 of 69
Mahanthi Bukkapatnam
Page 18 of 69
Syntax of a default
constructor
Scenario in which
the default
constructor will not
be created
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
If the constructor
does not have this()
or super() what will
the compiler put in?
Mahanthi Bukkapatnam
super();
Page 19 of 69
super()
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.
Statics
Coupling and cohesion
Mahanthi Bukkapatnam
Page 20 of 69
Chapter 3: Assignments
Literals, Assignments and Variables
What exception is
thrown from a static
init block?
ExceptionInInitializationError
Mahanthi Bukkapatnam
Page 21 of 69
Yes
Given a string
representation of a
value, how do you
get its primitive?
parseXXXX()
Given a string
representation, how
do you get the
wrapper object
valueOf()
Given a wrapper
how do you convert
into other
primitives?
From wrappers,
how do you get the
Hex and the Octal
version of the value?
xxxxValue();
Boolean
Mahanthi Bukkapatnam
Page 22 of 69
Byte
Character
== return true if the values are within \u0000 to \u007f. Else false
Overloading
Order for matching a
method for
overloading
Primitive widening
Auto Boxing
Var args
Garbage Collection
How to invoke the
garbage collector
System.gc();
finalize() method(?)
Mahanthi Bukkapatnam
Page 23 of 69
Chapter 4: Operators
Assignment Operators
instanceof Comparison
RACL
Relational Operators
Arithmetic Operators
Conditional Operators
Logical Operators
TODO
Mahanthi Bukkapatnam
Page 24 of 69
The case constant has to fall within the valid range of the switch
expression data type.
Yes.
Mahanthi Bukkapatnam
Page 25 of 69
1. Iteration expression
2. evaluating the conditional expression
Labeled Statements
Yes
Mahanthi Bukkapatnam
Page 26 of 69
Exception handling
A return statement is
encountered, will the
finally block execute
Order of the
exception handlers.
Common exception
Mahanthi Bukkapatnam
Page 27 of 69
Assertion
What exception is
thrown when an
assertion fails
AssertionError
Example of
assertions
assert( x < y );
assert( x < y ) : Message goes here..;
-ea
-enableassertions
-da
-disableassertions
Selective enabling
-ea:com.packagename.com
Mahanthi Bukkapatnam
Page 28 of 69
Serialization
TODO
Mahanthi Bukkapatnam
Page 29 of 69
Chapter 7: Collections
hashCode() and equals()
Overriding equals
Equals contract.
Reflexive
Symmetric
Transitive
Consistent
Null
equals() and
hashCode()
instanceof operator
Transient variables
and equals()
Mahanthi Bukkapatnam
Page 30 of 69
Collections
Operations on a collection
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
Collection
List
Set
NavigableSet
SortedSet
Queue
Map
NavigableMap
SortedMap
Maps
Key Concrete
Classes
HashMap
Hashtable
TreeMap
LinkedHashMap
Sets
HashSet
LinkedHashSet
TreeSet
Mahanthi Bukkapatnam
Page 31 of 69
Queues
PriorityQueue
Utilities
Collections
Arrays
Difference
Mahanthi Bukkapatnam
Page 32 of 69
List interface
Main concept of a
list
Main difference
between ArrayList
and Vector
ArrayList
LinkedList
Mahanthi Bukkapatnam
Page 33 of 69
Set Interface
HashSet and
hashCode() relation
LinkedHashSet and
HashSet difference
Tree Set
Ascending Order by natural order.
TreeSet implements NavigableSet.
NavigableSet implements SortedSet
Mahanthi Bukkapatnam
Page 34 of 69
Map interface
HashMap
Hashtable
LinkedHashMap
TreeMap
Sorted Order.
Mahanthi Bukkapatnam
Page 35 of 69
Queue Interface
Main point
PriorityQueue
Collections.sort( list );
Comparable Interface
Comparable
interface
Implementation
point
Mahanthi Bukkapatnam
Page 36 of 69
Key Method
compareTo()
Comparator 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()
Collections
Collections.sort(list)
Collections.sort(list, comparator)
Arrays
Arrays.sort( array )
Arrays.sort( array, comparator)
Search method
binarySearch()
Successful search
Page 37 of 69
Unsuccessful search
0 -> -1
1 -> -2
2 -> -3
As 0 is a valid searh index.
Sorted.
If not sorted, results unpredictable.
Comparator
requirements.
toArray()
Arrays
asList()
Backed collections
Mahanthi Bukkapatnam
Page 38 of 69
Using Lists
Iterator
Iterator<Dog> i3 = d.iterator();
While( i3.hasNext() ) {
Dog d2 = I3.next(); //No need for the cast here as we are
using generics
}
Using Sets
Using Maps
Key methods
Lower()
Floor()
Higher()
Ceiling()
less than
less than or equal
greater than
greater than or equal
LowerKey()
FloorKey()
HigherKey()
CeilingKey()
Mahanthi Bukkapatnam
Page 39 of 69
Polling
Key Idea
Key methods
pollFirst()
pollFirstEntry() retrieves and removes the key value pair.
pollLast()
pollLastEntry()
Descending Order
Key methods
TreeSet.descendingSet()
TreeMap.descendingMap()
Backed Collection
TODO
Mahanthi Bukkapatnam
Page 40 of 69
Chapter 7: Generics
Generics and Collections
Before Java 5
Short coming of
Collections before
Java 5
Advantage of
Generics with
collections.
Mahanthi Bukkapatnam
Page 41 of 69
Yes. No problem.
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.
Mahanthi Bukkapatnam
Page 42 of 69
Base type
Generic Type
Compare Generic
and Array example
Generic Methods
Base type
What is the
?
mechanism by which
you tell the compiler Public void addAnimal(List<Animal> animals)
that you will not be
adding anything into
the collection, but
Public void addAnimal(List<? extends Animal> animals)
still let the method
take in generic
subtypes?
Mahanthi Bukkapatnam
Page 43 of 69
Do you have an
equivalent for
extends?
Parameterized Types
Class
Example
Instantiation
Mahanthi Bukkapatnam
Page 44 of 69
Yes.
Public class RentalGeneric<T, X> { //T is the parameter type
}
NO
The following is not legal:
Public class NumberHolder<? Extends Number>{//NOTLEGAL
}
Methods
Example
Example 2
Mahanthi Bukkapatnam
Page 45 of 69
What is the
Inner class instance has access to all members of the outer class
relationship the inner instance even Private member of the outer class
class shares with the
outer class?
4 Types of inner
classes
Mahanthi Bukkapatnam
Page 46 of 69
Example
Class MyOuter {
Private int x = 7;
Class MyInner {
Public void method() {
System.out.println( X = + x );
}
}
}
Requitement for
Instantiating an
Inner class
2 places an inner
class instance is
instantiated
Example for
instantiating an inner
class from the
outside the outer
class
Weird point
Mahanthi Bukkapatnam
Page 47 of 69
How do you
reference the outer
class instance?
MyOuter.this
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
In a method.
Only after you declare the class, can you instantiate an object of
the method local inner class
Mahanthi Bukkapatnam
Page 48 of 69
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.
Mahanthi Bukkapatnam
Page 49 of 69
Class Popcorn {
Public void pop() {
}
}
Class Food {
Popcorn p = new Popcorn() {
Public void pop() {
}
};
}
interface Popcorn {
Public void pop() {
}
}
Class Food {
Popcorn p = new Popcorn() {
Public void pop() {
}
};
}
Key point to
remember
Mahanthi Bukkapatnam
Page 50 of 69
Example
Class MyOuter {
Static class MyInner {
}
}
Instantiation:
MyOuter.MyInner inner = new MyOuter.MyInner();
Key point
Mahanthi Bukkapatnam
Page 51 of 69
Chapter 9: Threads
Overview
What sections are in
this chapter?
Mahanthi Bukkapatnam
Page 52 of 69
Thread of execution
A thread means:
a thread of execution that has its own call stack
It is called main.
In which method
does the action
happen?
start()
yield()
sleep()
run()
run() method.
The thread of execution will always begin by invoking the run()
method.
Mahanthi Bukkapatnam
Page 53 of 69
Mahanthi Bukkapatnam
Page 54 of 69
Defining Threads
Of the 2 ways to
Implementing the Runnable interface
create threads, which
is preferable.
No.
Only the run() method will be invoked from the new thread of
execution.
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.);
}
}
Mahanthi Bukkapatnam
Page 55 of 69
Instantiating Threads
How do you
instantiate a subclass
of the
java.lang.Thread
class
How do you
instantiate a thread
when a class has
implemented the
Runnable interface?
Overloaded
constructors to keep
in mind
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String s)
When is a new
thread created?
When is a new call
stack created?
Mahanthi Bukkapatnam
Page 56 of 69
Starting Threads
What happens when
a start() method is
called on a Thread
object?
Dead state.
getName()
Thread class.
How does an
instance of a
Runnable know the
Thread name?
How do you get the
reference to the
currently executing
thread?
Do threads get a
default name?
Mahanthi Bukkapatnam
Page 57 of 69
Yes of course
No
No. Never.
Thread Scheduler
Who decides which
thread should be run
at any given moment
Mahanthi Bukkapatnam
Eligible
Runnable state
Queue behavior
Runnable pool
Page 58 of 69
No.
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()
New
Runnable
Dead
Running
Waiting/Blocking/Sleeping
Mahanthi Bukkapatnam
Page 59 of 69
Sleeping
Key method
Thread.sleep();
What does
interruption mean
Mahanthi Bukkapatnam
Page 60 of 69
What do I have to
remember about this
method?
Thread Priorities
What is the method
used to set the
priority?
setPriority()
MIN_PRIORITY
NORM_ PRIORITY
MAX_PRIORITY
MIN
1
NORM 5
MAX
10
Yielding from a thread
Key method
Yield()
Is this behavior
guaranteed?
No
Mahanthi Bukkapatnam
Page 61 of 69
Join() method
Key Method
Join()
Is this method static? No. Why? This method is called on a thread object.
Mahanthi Bukkapatnam
Page 62 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.
How does
synchronization
work?
With locks.
Monitor
Technically yes.
But the two can be used interchangeably
Mahanthi Bukkapatnam
Page 63 of 69
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.
If a thread goes to
sleep, does it release
its locks?
Yes.
Mahanthi Bukkapatnam
Page 64 of 69
Which lock is
acquired for static
methods?
Equivalent to:
Public synchronize static method() {
Class c1 = Class.forName(MyClass)
Synchronize(c1) {
Return 3;
}
}
Mahanthi Bukkapatnam
Page 65 of 69
What is the
necessary condition
for a synchronized
method or block to
block synchronized
method or block.
Key goal of
synchronization
Comment on static
synchronized
method and a nonstatic synchronized
method.
A simple rule to
make a class thread
safe -
Mahanthi Bukkapatnam
Page 66 of 69
Thread interaction
Important point
about wait/notify
Mahanthi Bukkapatnam
Page 67 of 69
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.
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
Calling wait on an
object whose lock is
not held
Mahanthi Bukkapatnam
Page 68 of 69
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()
Heading
Line
Line
Mahanthi Bukkapatnam
Page 69 of 69