Professional Documents
Culture Documents
(Part I)
SQL STAR INTERNATIONAL
June, 2009
SCJP Exam facts
• Consists of 72 questions
• The candidate has 210 minutes(3.5h) to
answer (~3 mins/q)
• At least 47 questions are needed to be
correct to pass (around 65%)
• Must buy a voucher from Sun and book the
test at least a week in advance.
• The test consists of multiple choice and
drag-and-drop questions, the latter
comprising 20-25% of the questions
2
Reserved words (1)
• First of all: be careful with the Capital or low case;
• Be careful with the API’s name, such as:
• Serializable, Runnable, Externalizable,Cloneable
• All the reserved key words are: (all low case)
• abstract boolean break byte case
• catch char class else extends
• const continue default do double
• final finally float for goto
• if implements import int instanceof
• long interface native new package
• private protected public return short
• static strictfp super switch synchronized
• this throw throws void transient
• try volatile while assert enum
3
Reserved words (2)
List some infrequently used:
• Strictfp: Marking a class as strictfp means that any
method code in the class will conform to the IEEE
754 standard rules for floating points. Without that
modifier, floating points used in the methods might
behave in a platform-dependent way.
• instanceof: only for class
• transient : only for variable
• throw /throws: method
• method name + throws + exception name;
• Inside method, use throw new exception(); to throw exception
• volatile: can be applied only to instance variables
• native: indicates that a method is implemented in
platform-dependent code, often in C.
• goto/const: keyword isn't used in Java at the moment.
4
Transient
• Only for instance variable
• Related to the Serialization
• transient instance variable: the JVM ignore this
variable when you attempt to serialize the object
containing it.
5
Volatile
• Only for instance variable
• volatile modifier: the JVM that a thread accessing the
variable must always reconcile its own private copy
of the variable with the master copy in memory.
6
Language Fundamentals
• "big farms need red tractors".
• The escape sequences are as follows: '\b'
(backspace), '\f' (formfeed), '\n' (newline), '\r'
(carriage return), '\t' (horizontal tab), '\\'
(backslash), '\"' (double quote), '\'' (single
quote).
7
Source file
declaration rules
Source file declaration rules
• Only one public class, or no public
class
• Can have multiple non-public class
• File name = public class name
• Sequence:
• package xxxx;
• import xxxx;
• public class xxxx { };
• No requirements for non-public classes
9
Classes
Basic concepts
• Every class in Java is a subclass of class Object,
(except of course class Object itself).
• Classes always have an equals, clone, notify, wait,
and other methods, available to use.
• specialized classes can actually help reduce bugs
• The top-level class only can be marked as public and
default
11
Class
declaration &
modifiers
Modifiers
• Access modifiers
• public (class can use)
• protected
• private
The fourth access control level:
• default: package-level access (class can use)
• Non-access modifiers
• strictfp is a keyword and can be used to modify a class
or a method
• final
• abstract
13
Class Access (1)
• default class (without add any modifier)
• Only be visible within the same package.
• Import won’t work neither;
• public class
• gives all classes from all packages access to the public
class.
• still need to import the public class if in different
packages.
14
Class Access (2)
• final class
• class can't be subclassed (no inherit from)
• abstract class
• class can never be instantiated;
• if even a single method is abstract, the whole class
must be declared abstract;
• The abstract method: end in a semicolon rather than
curly braces. public abstract void xxxx ();
• Can put nonabstract methods in an abstract class;
• Can't mark a class as both abstract and final
15
Extends from abstract class
• If not in the same package, must import it.
• Use class xxxx extends xxxx { }
• Have to implement all the abstract methods; (exactly
same, different argument doesn’t count ==
OVERLOAD)
• If overriding the non-abstract method, can use the
old method by super.xxxx();
• For the abstract method, can not reduce the
visibility. (Wrong: public private, Right: default
protected )
16
Interface
22
Class Members Modifiers(3)
• Protected vs. Default
• almost identical, but with one critical difference --
subclass.
• default member may be accessed only if the class
accessing the member belongs to the same package
(package)
• protected member can be accessed (through
inheritance) by a subclass & the subclass is in a
different package (package + kids ).
• Special case: subclass+ outside of package
• can't use a superclass reference to access a protected member:
use variable directly, not xxx.variable;
• The protected member can be accessed only through inheritance.
• Only the subclass and its sub-subclasses can access it.
23
Class Members Modifiers(4)
• Nonaccess Member Modifiers
• final
• abstract
• synchronized
• native,
• strictfp
• static.
24
Class Members Modifiers(5)
• final Methods: can't-be-overridden
• prevents a method from being overridden in a subclass
• final Arguments
• Void xxxMethod (Final int input1) {}
• can't be modified within the class
• a final argument must keep the same value that the parameter had
when it was passed into the method.
• Abstract Methods
• has no method body. Only have xxxx ();
• an abstract class can have no abstract method
• an abstract method require the class must be abstract
• The first concrete subclass of an abstract class must implement all
abstract methods of the superclass.
• Implementation ≠ overloaded
• Static Method
• Can not be override
25
Class Members Modifiers(6)
• Synchronized Methods
• indicates that a method can be accessed by only one thread at a
time
• Synchronized can be applied only to method
• Typical synchronized declaration:
• public synchronized Record xxxxx (int id) { }
• Native Methods
• indicates that a method is implemented in platform-dependent
code, often in C.
• Native can be applied only to method
• Typical native declaration: (there’s no body)
• public native xxxx ();
• Strictfp Methods
• strictfp forces floating points (and any floating-point operations)
to adhere to the IEEE 754 standard.
• With strictfp, you can predict how your floating points will behave
regardless of the underlying platform the JVM is running on.
26
Methods with Variable Argument Lists
(var-args)
• Basic concepts:
• Arguments: The things you specify between the parentheses
when you're invoking a method.
• Parameters: The things in the method's signature that indicate
what the method must receive when it's invoked.
• Declaration rules for var-args:
• void doStuff2(char c, int... x) { }
• Var-arg type: must specify the type of the argument(s) this
parameter of your method can receive.
• Basic syntax: To declare a method using a var-arg parameter,
you follow the type with an ellipsis (…), a space, and then the
name of the array that will hold the parameters received.
• Other parameters: It's legal to have other parameters in a
method that uses a var-arg.
• Var-args limits: The var-arg must be the last parameter in the
method's signature, and you can have only one var-arg in a
method.
27
Constructor Declarations
• Every class has a constructor
• constructors look an awful lot like methods
• constructor can't have a return type.
• must have the same name as the class
• can't be marked static, final or abstract
• Can be marked as public, private, protected
• If didn’t define the constructor, complier will create
one for you. Once defined any constructor, compiler
won’t do that automatically.
28
Variable Declarations(1)
Primitives & Reference variables
• Primitives:
• can be one of eight types: char, boolean, byte, short, int,
long, double, or float.
• Once has been declared, primitive type can never change,
( value can change).
• Reference variables
• is used to refer to (or access) an object.
• is declared to be of a specific type and that type can never be
changed.
• can be used to refer to any object of the declared type, or of a
subtype of the declared type (a compatible type).
• a reference variable refer to a subtype is about
polymorphism.
29
Variable Declarations(2)
Declaring Primitives & Reference Variables
• Primitive variables & Reference Variables can be
declared as:
• class variables (static),
• instance variables,
• method parameters,
• local variables.
• can declare in a single line
• int x, y, z;
30
Variable Declarations(3)
Primitive Types & Ranges
• boolean • ture /false (virtual-machine dependent. )
• char • 16bits 0~65535 char c = ‘c’;
• Basic concepts
• Can use any of the four access levels (which means they can be
marked with any of the three access modifiers)
• Can be marked
• final
• transient
• Cannot be marked
• abstract
• synchronized, only for method
• strictfp,
• native,
• static, because then they'd become class variables.
32
Variable Declarations(4)
Local (Automatic/Stack/Method) Variables
• are variables declared within a method
• are destroyed when the method has completed.
• local variables don't get default values, So must be initialized
with a value before be used.
• are always on the stack, not the heap (object is on the heap)
• local object == locally declared reference variable
• shadowing : Can declare a local variable with the same name as
an instance variable. Use keyword this refers to the object currently
running.
• Can be marked
• final
• Cannot be marked
• Access modifiers: public, private, protected, default
• transient,
• volatile,
• abstract,
• static 33
Final
• Final variable is impossible to be re-initialized, once
it has been initialized with an explicit value (not
default value)
• primitives: the assigned value can't be altered
• reference variable: can't ever be reassigned to refer to a
different object, while the data within the object can be
modified.
• Final is applied to:
• Class: cannot have subclass
• Method: cannot be overridden
• Variable: cannot be reassigned value/object
34
Static
• Exist independently of any instances created for the class.
• Same value: all instances of a given class share the same value
for any given static variable.
• Exist before you ever make a new instance of a class
• Can be marked
• Methods
• Variables
• A class nested within another class, but not within a method
• Initialization blocks
• Enum, but not the Enum as separate class
• Cannot be marked
• Constructors (makes no sense; a constructor is used only to
create instances)
• Classes (unless they are nested)
• Interfaces
• Method local inner classes
• Inner class methods and instance variables
35
• Local variables
Enums
Basic Concepts
• Restrict a variable to having one of only a few pre-
defined values
• enum CoffeeSize { BIG, HUGE, OVERWHELMING }
• CoffeeSize cs = CoffeeSize. BIG;
• Add “;” also ok:
• enum CoffeeSize { BIG, HUGE, OVERWHELMING };
• Not required that enum constants be in all caps, but
it is better
• Can be declared:
• outside a class: only can use public or default modifier
• a class member
• But not be declared within a method
• Cannot use public constructor
41
-- 2.2 --
Inheritance,
Is-A,
Has-A
5.5 Develop code that implements "is-a" and/or "has-a"
relationships.
inheritance
• Inheritance benefits:
• To promote code reuse
• To use polymorphism
• A class can only extends one class (only one parent
class)
• inherit public and protected variables and methods of
the superclass.
• To avoid "Deadly Diamond of Death,“, JAVA use
interface to instead of the multiple inheritance.
• Underlying IS-A, polymorphism, overriding,
overloading, and casting
• All classes (except class object), are subclasses of
type object, and therefore they inherit Object's
methods. 43
IS-A vs. HAS-A
• IS-A
• is based on class inheritance or interface
implementation.
• this thing is a type of that thing
• Keywords:
• extends: for class inheritance
• implements: for interface implementation
• HAS-A
• based on usage, rather than inheritance
• class A HAS-A B if code in class A has a
reference to an instance of class B.
44
-- 2.3 --
Polymorphism
5.2 Given a scenario, develop code that demonstrates the use of
polymorphism. Further, determine when casting will be necessary and
recognize compiler vs. runtime errors related to object reference casting.
Reference variable
• Polymorphism reference accesses the variable related to the
type of reference variable
• Polymorphism means “many forms.”
• Reference variable it the only way to access an object
• A reference variable can be of only one type, and once
declared, that type can never be changed
• But it can refer to any object of the same type or
any subtype
• As a variable, reference can be reassigned to other objects,
(unless the reference is declared final).
• ++ Can be declared as a class type or an interface type.
• As an interface type, variable can reference any
object of any class that implements the interface.
46
Compiler vs. JMV
• Compiler only knows about the declared reference
type.
• JVM at runtime knows what the object really is.
• Polymorphic method only apply to instance methods.
• Variable type determines the methods that can be
invoked. (method variable type)
• You can always refer to an object with a more general
reference variable type (a superclass or interface), but at
runtime, the ONLY things that are selected based on the
actual object (rather than the reference type) are instance
methods.
• ++ Not static methods. Not variables. (Base on the reference
type)
• Only instance methods are invoked based on the real object's
type.
47
-- 2.4 --
Overriding /
Overloading
1.5 Given a code example, determine if a method is correctly overriding or
overloading another method, and identify legal return values (including
covariant returns), for the method.
5.4 Given a scenario, develop code that declares and/or invokes overridden or
overloaded methods and code that declares and/or invokes superclass,
overridden, or overloaded constructors.
Overriding (1)
overriding == re-implementing a method you inherited
• Inherits a method from a superclass, the subclass
can override the method (unless marked as final)
• ++ In concrete class, force to override the abstract
methods (implement it) from abstract class.
• an overriding method must fulfill the contract of the
superclass == Guarantee the subclass be able to do
everything the superclass can do.
• Superclass Version + additional code
• use the keyword super: super.overriddenMethodName();
Rules:
• Overriding method’s argument list == the
overridden method’s. (don't match overloaded).
• The return type must be the same as the original
overridden method (or a subtype == covariant 49
returns.)
Overriding (2)
• ++ The access level CAN’T be more restrictive than
the overridden method's. (be careful with
INTERFACE, its methods are all public, so you must
mark method as public)
• The access level CAN be less restrictive than that of
the overridden method.
• Instance methods can be overridden only if they are
inherited by the subclass.
• A subclass within the same package as the
instance's superclass can override any superclass
method that is not marked private or final.
• A subclass in a different package can override only
those non-final methods marked public or protected
( the default methods can not be see out of the
package).
50
Overriding (3)
• ++ Must not throw new or broader checked
exceptions.
• May throw fewer or narrower checked exceptions,
or any unchecked exception.
• ++ Bottom line: an overriding method doesn't have to
declare any exceptions that it will never throw,
regardless of what the overridden method declares.
• ++ If a method can't be inherited, you cannot
override it. (always check class first)
• private methods are not inherited
• You cannot override a method marked final.
• You cannot override a method marked static.
51
Overloading
• Polymorphism applies to overriding, not to overloading.
• Let you reuse the same method name in a class, but with
different arguments
• ++ Overloaded methods MUST change the argument
list.
• Overloaded methods CAN change the return type.
• ++ Overloaded methods CAN change the access
modifier.
• ++ Overloaded methods CAN declare new or broader
checked exceptions.
• A method can be overloaded in the same class or in
a subclass.
• Be careful with the overridden and overloaded. They
are similar but different.
• key is: argument list is different
• ++ Static method is only overloaded, it is hidden. 52
++ Overridden vs. Overrided
• Real object type (not the reference variable
type), determines which overridden method
is used at runtime
• Reference variable type (not the real object
type) to determine which overloaded method
is invoked.
• the choice of which overloaded method to call is
NOT dynamically decided at runtime.
• static methods & variables base on the
reference type
53
-- 2.5 --
Reference
Variable Casting
61
Rules for Constructors (1)
• ++ The first statement of every constructor must be
a call to either this() or super().
• Compiler will add a call to super() unless you have
already put in a call to this() or super().
• The only way a constructor can be invoked is from
within another constructor (using super() or this()).
• A constructor can invoke another constructor of the same
class using the keyword this().
• super()
• If your superclass does not have a no-arg constructor, you
must create a constructor and insert a call to super() with
arguments matching those of the superclass constructor.
• this()
• May appear only as the first statement in a constructor.
• Calls to this() and super() cannot be in the same constructor.
62
Rules for Constructors (2)
• Instance members are accessible only after the super
constructor runs.
• ++ Constructors can use any access modifier, even private.
• Private constructor means only code within the class itself can
instantiate an object of that type.
• ++ Constructors are never inherited, thus they cannot be
overridden.
• Constructors can be overloaded, The argument list determines
which overloaded constructor is called.
• ++ Only static variables and methods can be accessed as part
of the call to super() or this().
• Because: static variable/blocks are execute before constructor,
and belong to class
• Example: super (Animal.NAME) is OK, because NAME is
declared as a static variable.
63
Overloaded Constructors
• ++ Remember: no default constructor once you
create one.
• Offer flexible ways to instantiate objects from your
class
• Once you call “this”, the default super() won’t be
inserted.
• ++ All the constructor calls this() could cause the
dead lock problem. It is a compiler error
64
-- 2.8 --
Static
1.3 Develop code that declares, initializes, and uses primitives, arrays,
enums, and objects as static, instance, and local variables. Also, use legal
identifiers for variable names.
Static Variables and Methods
• Use static methods to implement behaviors that are
not affected by the state of any instances.
• Static members are tied to the class, not an instance
• static = class, nonstatic = instance.
• There is only one copy of any static member
• Static variable:
• Will be shared by all instances of that class (Only one copy)
• Can be accessed without having an instance of a class.
• Static method:
• Can't access a nonstatic (instance) variable, because there is
no instance
• can't directly invoke a nonstatic method
• Most common mistakes is attempting to access an instance
variable from the static main() method
• Go with reference variable
66
Accessing Static Methods / Variables
• Can use a static method or variable without having
any instances of that class at all
• Do not need use the dot operator on the class name
67
++ Initialization order
• Always be:
• Static block (static method create but
not run)
• Then: initial blocks + constructor
68
-- 2.9 --
Coupling and
Cohesion
5. 1 Develop code that implements tight encapsulation, loose
coupling, and high cohesion in classes, and describe the benefits.
OO Basic concepts
• Do with the quality of an OO design, the
goals for an application are
• Ease of creation
• Ease of maintenance
• Ease of enhancement
• good OO design calls for
• loose coupling and shuns tight coupling
• high cohesion, and shuns low cohesion.
70
Coupling
• Coupling is the degree to which one class
knows about another class.
• Loosely coupled: class A has about class B, is what
class B has exposed through its interface
• Tightly coupled: class A relies on parts of class B that
are not part of class B's interface
• REALLY BAD: class A knows non-API stuff about class
B, and class B knows non-API stuff about class A
• Desirable state of having classes that are
well encapsulated, minimize references to
each other, and limit the breadth of API
usage.
71
Cohesion
• Cohesion is the degree to which a class has
a single, well-focused purpose
• All about how a single class is designed
• Higher cohesiveness: The more focused a class is
• key benefits:
• much easier to maintain (less frequently changed)
• more reusable than other classes
72
-- 3.1 --
Stack and Heap
Quick Review
• Instance variables and objects live on
the heap.
• Local variables live on the stack
74
-- 3.2 --
Literals,
Assignments,
and Variables
1.3 Develop code that declares, initializes, and uses primitives, arrays, enums, and
objects as static, instance, and local variables. Also, use legal identifiers for variable
names.
7.6 Write code that correctly applies the appropriate operators including assignment
operators (limited to: =, +=, -=) …
Literal Values for All Primitive Types
• Integer Literals:
• Decimal as is
• octal 0+…
• Hexadecimal 0X/0x + …(not case sensitive)
• Literals:
• Float: … + F/f (not case sensitive), default double
• Long: + L/l (not case sensitive), default int
• Boolean Literals: true or false
• Character Literals:
• single character in single quotes,
• \u + ….number
• Out of the range, you need cast it: 6553
• Literal Values for Strings: in double quotes 76
Assignment Operators (1)
• Variables are just bit holders
• Reference variable: A variable referring to an object
• Primitive Assignments
• literal integer is always implicitly an int
• For other primitive: compiler puts in the cast
• ++ Primitive Operators: always implicit an int
• the result of an expression involving anything int-sized or
smaller is always an int
• ++ byte x = (byte) 1 + 2;
• ++ x += 7; still be byte, needn’t cast
• Cast: implicit small to int, explicit large to small
• Explicit: The large-value-into-small-container
• Implicit: The small-value-into-large-container
77
Assignment Operators (2)
• Assigning Floating-Point Numbers
• every floating-point literal is implicitly a double (64 bits)
• cast the value or ….+F/f
• Assigning a Literal That Is Too Large for the Variable
• cut off the leftmost and get the lower bits to suit small
container
• Negative number: keep the left most as the sign, then flip all
of the bits, and then add 1
• ++ +=,-=,* = , and /= will all put in an implicit cast.
78
Assignments: Primitive Variable
vs. Reference Variable
• Assigning Primitive Variable Primitive Variable
• the right-hand variable are copied
• Assigning Reference Variable Reference Variable
• Won’t copy, just assign the right reference variable links to the
object which the left reference variable linking
• Reference Variable Assignments
• assign a newly created object to an object reference variable
• Makes a reference variable named AAA, of type XXX
• Creates a new XXX object on the heap
• Assigns the newly created XXX object to the reference variable
AAA
• assign null to an object reference variable means the variable is
not referring to any object.
• ++ CAN assign a subclass, CAN’T assign a superclass 79
++ Variable Scope
• Four basic scopes:
• Static variables have the longest scope; they are created when
the class is loaded, and they survive as long as the class stays
loaded in the JVM.
• Instance variables are the next most long-lived; they are
created when a new instance is created, and they live until the
instance is removed.
• Local variables are next; they live as long as their method
remains on the stack. As we'll soon see, however, local
variables can be alive, and still be "out of scope".
• Block variables live only as long as the code block is executing.
• ++ Typical of errors:
• access an instance variable from a static context (main())
• access a local variable from a nested method
• use a block variable after the code block has completed
• ++ Pay extra attention to code block scoping errors.
You might see them in switches, try-catches, for, do,
and while loops. 80
Instance variable vs. Local variables
• Instance variable:
• declared within the class but outside any
method or constructor
• Local variable:
• declared within a method or in the argument list
of the method
• stack, temporary, automatic, or method
variables
81
Primitive and Object Type Instance
Variables
• Variables are defined at the class level will auto initialized
• Primitive instance: are initialized to a default value each time a
new instance is created
• object reference: null
• byte, short, int, long : 0
• float, double 0.0
• boolean: false
• char : '\u0000'
• A good idea to initialize all your variables
• Object reference :
• A null value of object reference means it is not referring to any object on
the heap.
• ++ Array Instance:
• Array elements are always, always, always given default values,
regardless of where the array itself is declared or instantiated
• The default values depends on the elements of array get when they're
instance variables
82
Local (Stack, Automatic) Primitives
and Objects
• Local variables are defined within a method, and they include a
method's parameters
• Local variable must be assigned a value in the code, or the
compiler will complain.
• Local Primitives:
• always, always, always must be initialized before you attempt to use
them
• CAN declare a local variable without initializing it as long as you don't
use the variable (but what for……)
• CAN’T do initialization within a logically conditional block (if block or for
loop without a literal value of true or false in the test), the compiler can
produce an error.
• Local Object References:
• local references are not given a default value
• you must explicitly initialize the local variable
• Just set the darn thing to null explicitly, until you're ready to initialize it
to something else
• ++ Local Arrays:
• array elements are given their default values (0, false, null, '\u0000', etc.) 83
regardless of whether the array is declared as an instance or local variable
Assigning One Reference Variable to
Another
• The reference pattern is copied, but not the object
content.
• In Java, String objects are given special treatment:
• String objects are immutable; you can't change the value of a
String object
• any time we make any changes at all to a String, the VM will
update the reference variable to refer to a different object.
• ++ Must always: String s = ……, otherwise you will lost your
result.
84