SCJP Exam Notes (Part II) : by June, 2008
SCJP Exam Notes (Part II) : by June, 2008
Notes
(Part II)
By Maggie Zhou
June, 2008
-- 3.3 -Passing
Variables into
Methods
7.3 Determine the effect upon object references and primitive values when
they are passed into methods that perform assignments or other modifying
operations on the parameters.
++ Shadowed variables
Array
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.
Basic concepts
## For exam ##
Declarations
multidimensional arrays:
String[][] occupantName;
String[] ManagerName []; // it's legal doesn't mean it's right
Constructing
To create an array object, Java must know how much space to allocate
on the heap, so you must specify the size of the array at creation time.
must have either a dimension expression or an initializer. If fail to do,
then a compile-time error is generated.
int scores[ ] = new int[5];
int[ ] scores = new int[ ] {1,2,3,4,5} ;
One-Dimensional Arrays
Multidimensional Arrays
an object of type int array (int[]), with each element in that array holding
a reference to another int array.
The second dimension holds the actual int primitives.
Must specify the first dimension, can not only define the second
without define the first
++ int [ ] [ ] x = new int [5] [ ] is legal new int [ ] [5] is illegal
the JVM needs to know only the size of the object assigned to the
variable myArray.
++ WRONG: int [ ] x = new short [ ]; short can put into int[ ], but
char [ ] can not assign to int[ ].
++ CANNOT define both size and initialize at the same time
Initialization
Array doesn't actually hold the objects, but instead
holds a reference to the object.
++ Array index number always begins with zero
Need to assign elements to reference the actual
created objects one by one.
++ Initialization Blocks
++ Instance init blocks are often used as a
place to put code that all the constructors
in a class should share. That way, the code
doesn't have to be duplicated across
constructors.
static blocks run only once, when the class
is first loaded
1.
2.
boolean
byte
char
double
float
short
int
long
Overview
| Boolean
| boolean or String
| Byte
| byte or String
| Character
| char
| Double
| double or String
| Float | float, double, or String
| Short | short or String
| Integer
| int or String
| Long | long or String
primitive xxxValue()
to convert a Wrapper to a primitive: int x = xxWrapper.intValue();
13
Autoboxing
-- 3.6 -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
Var-Args
the compiler will choose the older style before it chooses the
newer style, keeping existing code more robust
byte x, byte y
static void go (int x, int y) {} > static void go (byte... x) {}
-- 3.7 -Garbage
Collection
7.4 Given a code example, recognize the point at which an object becomes
eligible for garbage collection, and determine what is and is not guaranteed
by the garbage collection system. Recognize the behaviors of System.gc and
finalization.
Memory management
Nulling a Reference
Reassigning a Reference Variable
Isolating a Reference
instance variables so that they refer to each other, but their links
to the outside world have been nulled.
20
finalize()
CAN be overridden
normally it should be overridden to clean-up non-Java resources ie
closing a file
use a try-catch-finally statement and to always call super.finalize()
} finally {
super.finalize();
21
-- 4.1 -Operators
7.6 Write code that correctly applies the appropriate operators including assignment
operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --),
relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical
operators (limited to: &, |, ^, !, &&, | |), and the conditional operator (? :), to produce
a desired result. Write code that determines the equality of two objects or two
primitives.
Basic concepts
23
Assignment Operators
(=)
24
"Equality" Operators
(== , !=)
Logical Operators
26
++ instanceof
++ Trick:
Integer [] x x instanceof Object true, not Integer
yet
Integer[1] instanceof Object and Integer, Number
are true
27
Other operators
++ Conditional Operator:
X = (boolean expression) ? value to assign if true : value to
assign if false;
28
if
else if () {} may be unreachable
Only legal expression in an if test is a boolean.
++ Boolean x if (x= true) is legal
Be prepared for questions that not only fail to indent
nicely, but intentionally indent in a misleading way
30
switch
switch (expression) { }
++ only accept: variables and values that can be automatically
promoted to an int
Can use an enum
Case constant:
Case variable must be constant
must evaluate to the same type as the switch expression
++ Byte expression case 128 is out of range
++ final int a = 1; is a constant, compile time constant
++ final int b; b= 1; not a constant
Cannot using the same value
case constants are evaluated from the top down, and the first
case constant that matches the switch's expression is the
execution entry point.
The default case doesn't have to come at the end of the switch.
31
While and do
while
++ expression of a while loop must be declared
before the expression is evaluated illegal: while
(boolean x = true) {}
The expression result must be a boolean
do
33
for
/* loop body */
}
None of the three sections of the for declaration are required for( ; ; ) {}
Initialization expression :
Can declare more than one, Separate with comma
++ Be careful the scope problem: for(int x; ;) can not use x out of for
loop
++ int x = 0; for(; x<10;) { x++ } is legal and x can be used out of for loop
Conditional expression
Only one test expression
Interation Expression
After the body run finished
34
35
++ Special controls
continue
statements must be inside a loop
break
statements must be used inside either a loop or switch
statement
Execution jumps immediately to the 1st statement after
the for loop.
return
Execution jumps immediately back to the calling method.
system.exit()
All program execution stops; the VM shuts down.
36
Labeled Statements
A label statement
++ must be placed just before the statement
37
-- 5.4 -Handling
Exceptions
2.4 Develop code that makes use of exceptions and exception
handling clauses (try, catch, finally), and declares methods and
overriding methods that throw exceptions.
2.5 Recognize the effect of an exception arising at a specific point
in a code fragment, Note that the exception may he a runtime
exception, a checked exception, or an error.
40
Checked/Runtime exception
Checked exception:
Compiler guarantees the exceptions have been checked
Multiple Throw/Catch
Multiple Throw
42
43
Exception hierarchy
++ Override method
It's okay for an overriding method to throw the same
exceptions, narrower exceptions, or no exceptions.
it's okay for the overriding method to throw any runtime
exceptions.
44
Error
Objects of type Error are not Exception
objects, although they do represent
exceptional conditions.
++ Also use throw keyword
Error is unchecked
-- 5.5 -Common
Exceptions
& Errors
2.6 Understand which of these are thrown by the virtual
machine and recognize situations in which others should be
thrown programmatically
Categories of Exceptions/Errors
AssertionError,
StackOverflowError,
ClassCastException,
IllegalArgumentException,
IllegalStateException,
ExceptionInInitializerError,
NoClassDefFoundError,
ArrayIndexOutOfBoundsException,
NumberFormatException,
NullPointerException.
Distinguish
Checked exceptions
++ are subclass's of Exception excluding class RuntimeException and its
subclasses.
Checked Exceptions forces programmers to deal with the exception that
may be thrown.
Example: Arithmetic exception. When a checked exception occurs in a
method, the method must either catch the exception and take the
appropriate action, or pass the exception on to its caller
Unchecked exceptions
are RuntimeException and any of its subclasses. Class Error and its
subclasses also are unchecked.
Unchecked exceptions , however, the compiler doesn't force the
programmers to either catch the exception or declare it in a throws
clause.
In fact, the programmers may not even know that the exception could be
thrown. Example: ArrayIndexOutOfBounds Exception.
They are either irrecoverable (Errors) and the program should not
attempt to deal with them, or they are logical programming errors.
(Runtime Exceptions).
48
Common Errors
51
++ subclass of IllegalArgumentException
-- 5.6 -Assertion
Mechanism
2.3 Develop code that makes use of assertions, and distinguish
appropriate from inappropriate uses of assertions.
Expression2 - system.out.println(xxxx)
Optional
++ Must have a result of any value
A method with return
Enabling Assertions
Command Line
assert Is an Identifier
assert Is a Keyword
Compilation fails.
Compilation fails.
Code compiles.
Compilation fails.
Code compiles.
Compilation fails.
Code compiles.
Compilation fails.
Code compiles.
Command Line
What It Means
Enable assertions.
java -ea:com.foo.Bar
java -ea:com.foo
55
Assert expression should leave the program in the same state it was in before
the expression!
56
Strings
String Class
++ Strings
58
59
chained methods
Determine what the leftmost method call will return (let's call it x).
Use x as the object invoking the second (from the left) method. If
there are only two chained methods, the result of the second
method call is the expression's result.
If there is a third method, the result of the second method call is
used to Invoke the third method, whose result is the expression's
result
62
++ Exam watch
63
File I/O
File
The API says that the class File is "An abstract
representation of file and directory pathnames."
lets you manage (add, rename, and delete) files and
directories
FileReader
used to read character files. Its read() methods are
fairly low-level, allowing you to read single characters,
the whole stream of characters, or a fixed number of
characters.
usually wrapped by higher-level objects such as
BufferedReaders, which improve performance and
provide more convenient ways to work with the data.
66
BufferedReader
used to make lower-level Reader classes like FileReader more
efficient and easier to use.
Compared to FileReaders, BufferedReaders read relatively large
chunks of data from a file at once, and keep this data in a buffer.
When you ask for the next character or line of data, it is retrieved
from the buffer, which minimizes the number of times that timeintensive, file read operations are performed.
In addition, BufferedReader provides more convenient methods
such as readLine(), that allow you to get the next line of
characters from a file.
File Writer
used to write to character files.
Its write() methods allow you to write character(s) or Strings to a
file.
FileWriters are usually wrapped by higher-level Writer objects
such as BufferedWriters or PrintWriters, which provide better
performance and higher-level, more flexible methods to write
data.
67
BufferedWriter
used to make lower-level classes like FileWriters more efficient
and easier to use.
Compared to FileWriters, BufferedWriters write relatively large
chunks of data to a file at once, minimizing the number of times
that slow, file writing operations are performed.
In addition, the BufferedWriter class provides a newLine() method
that makes it easy to create platform-specific line separators
automatically.
PrintWriter
has been enhanced significantly in Java 5. Because of newly
created methods and constructors (like building a PrintWriter with
a File or a String), you might find that you can use PrintWriter in
places where you previously needed a Writer to be wrapped with
a FileWriter and/or a BufferedWriter.
New methods like format(),printf(), and append() make
PrintWriters very flexible and powerful.
68
Write/Read a file
BufferedWriter: Writer
close() ,flush() ,newLine() , write()
PrintWriter: Writer
close() , flush(), format()*, printf()*, print(), println() ,write()
BufferedReader: Reader
read(), readLine()
70
java.io.File
java.lang.Object
java.io.File
71
java.io.FileReader
throws IOException
throws FileNotFoundException
java.lang.Object
java.io.Reader
java.io.InputStreamReader
java.io.FileReader
java.lang.Object
java.io.Reader
java.io.BufferedReader
72
java.io.FileWriter
throws IOException
java.lang.Object
java.io.Writer
java.io.OutputStreamWriter
java.io.FileWriter
java.lang.Object
java.io.Writer
java.io.BufferedWriter
java.lang.Object
java.io.Writer
java.io.PrintWriter
73
FilenameFilter
+ java.io.FilenameFilter is an interface
which has one method:
boolean accept(File dir, String name)
can pass FilenameFilter to File's list() or
listFiles()
File xxxdir = new File(folder);
String[] a = xxxdir.list();
File[] b = xxxdir.listFile();
Console (1)
java.lang.Object
java.io.Console
import java.io.Console;
Console c = System.console();
String readLine()
char[] readPassword(): for security purpose
75
Console (2)
Void flush()
Console format(String fmt, Object... args)
Console printf (String fmt, Object... args):
Reader reader()
Retrieves the unique Reader object associated with this console.
PrintWriter writer():
Retrieves the unique PrintWriter object associated with this console.
String readLine()
String readLine(String fmt, Object... args):
char[] readPassword()
char[] readPassword(String fmt, Object... args)
Reads a password or passphrase from the console with echoing
disabled
76