Monterrey, NL, Mex. July  2009

SCJP study notes

Notes from the book:

 SCJP Sun Certified Programmer for Java 6 Study Guide

Katherine Sierra, Bert Bates


Some people [especially interviewers] doubt that I’m good [or at least not so bad] writing Java code, I think because I am still young.

So I will take the SCJP exam, anyway my employer is paying for the exam, I can review Java concepts, and it is not going to hurt in my resume.

1 Declarations and Access Control

Methods and instance (nonlocal) variables are known as "members."

Classes can also be modified with final, abstract, or strictfp.

The strictfp modifier applies only to classes and methods.

The transient modifier applies only to instance variables.

The volatile modifier applies only to instance variables.

2  Object Orientation

A reference variable can be of only one type, and once declared, that type

can never be changed (although the object it references can change).

An interface describes a contract that the

implementing class must follow.

En el constructor el compilador inserta super(); en cascada.**

If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.


Since java're allowed to change the return type in the

overriding method as long as the new return type is a subtype of the declared return

type of the overridden (superclass) method.

Must not have a more restrictive access modifier.

 May have a less restrictive access modifier.

 Must not throw new or broader checked exceptions.

 May throw fewer or narrower checked exceptions, or any

unchecked exception.

El polimorfismo solo aplica para métodos.(No variables o constantes, estos van con el tipo declarado)

3 Assignments

Leer este capítulo, escoger métodos.

There are three ways to represent integer numbers in the Java language: decimal

(base 10), octal (base 8), and hexadecimal (base 16).

float f = 23.467890; // Compiler error, possible loss of precision

float g = 49837849.029847F;
// OK; has the suffix "F"

double d = 110599.995011D;
// Optional, not required

char letterN = '\u004E';
// The letter 'N'

Literals for longs end in L or l.

Float literals end in F or f, double literals end in a digit or D or d.

For any given object, finalize() will be called only once (at most) by the

garbage collector.

finalize() is run once before the gc deletes an object

You can uneligibilize an object for GC from within finalize().

First of all, remember that any

code that you can put into a normal method you can put into finalize().

Scope refers to the lifetime of a variable.

 There are four basic scopes:

 -Static variables live basically as long as their class lives.

 -Instance variables live as long as their object lives.

 -Local variables live as long as their method is on the stack; however, if

  their method invokes another method, they are temporarily unavailable.

 -Block variables (e.g., in a for or an if) live until the block completes.

Floating-point numbers are implicitly doubles

Narrowing a primitive truncates the high order bits.

Compound assignments (e.g. +=), perform an automatic cast

xxxValue() Takes no arguments, returns a primitive

parseXxx() Takes a String, returns a primitive, throws NFE

valueOf() Takes a String, returns a wrapped object, throws NFE

You can combine var-args with either widening or boxing.

widening,autobox, var-args.

int[] weightList = new int[5];
byte b = 4;
char c = 'c';
short s = 7;
weightList[0] = b;
// OK, byte is smaller than int
weightList[1] = c;
// OK, char is smaller than int
weightList[2] = s;
// OK, short is smaller than int

primero se ejecutan los bloques estáticos, después los init y después el constructor

Hay que analizar.

  wide and autobox-NO

  box and wide - YES

4 Operators

& Non - short circuit and

-,++ prefix run before to be used in the expression

-,++  postfix run AFTER to be used in the expression

Concat runs from left to right and if either operand is a string the operands are concateneted.

5 Flow Control, Exceptions, and Assertions

You know you're not supposed to make assumptions

Switch must evaluate char,byte,short,int or enum(java6)

 only evaluates cases compile time constants.

final int a =1;
final int b;
b = 2;
int x = 0;
case a://ok
case b: //compiler error

pag 393 de la 6*****

A basic for statement has three parts: declaration and/or initialization, boolean evaluation, and the iteration expression

Obviamente las excepciones deben ser cachadas de la más específica a la más general

ASSERT: The first expression must be a boolean, the second any value(like sys.out)

assert (y > x);
assert (y > x): "y is " + y + " x is " + x;
// more code assuming y is greater than x

Pueden activarse a todo, por paquete o clase

java -ea com.geeksanonymous.TestClass

java -enableassertions com.geeksanonymous.TestClass

In 1.4 you can use assert as a keyword or as an identifier, but not both.

6  Strings, I/O, Formatting, and Parsing

To make Java more memory efficient, the

JVM sets aside a special area of memory called the "String constant pool.When the

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

File The API says that the class File is "An abstract representation of file

and directory pathnames." The File class isn't used to actually read or write

data; it's used to work at a higher level, making new empty files, searching for

files, deleting files, making directories, and working with paths.

FileReader This class is 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. FileReaders are usually wrapped

by higher-level objects such as BufferedReaders, which improve performance

and provide more convenient ways to work with the data.

BufferedReader This class is 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

time-intensive, file read operations are performed. Has readLine().

FileWriter This class is 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.

BufferedWriter This class is 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. The BufferedWriter class also provides a newLine()

method to create platform-specific line separators automatically.

PrintWriter This class 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.

Stream classes are used to read and write bytes, and Readers and Writers

are used to read and write characters. Since all of the fi le I/O on the exam is related to characters, if you see API class names containing the word "Stream" the question is probably about serialization.

File file = new File("file.txt") //just creates the file name
//creates a new empty file if it doesn't exists, true if   created.

En writers: terminar con flush() , close()


ObjectOutputStream.writeObject() // serialize and write

ObjectInputStream.readObject() // read and deserialize

 FileOutputStream fs = new FileOutputStream("testSer.ser");

 ObjectOutputStream os = new ObjectOutputStream(fs);

 os.writeObject(c); // 3


Constructors don't run on deserialized classes that implements Serializable

Cuando no se puede serializar(no se implementó serializable) .NotSerializableException

Tabla 488

private void writeObject() --Hace algo extra cuando se serializa

File(String parent, String child)

 parent - directory

 child - file

 if parent is null is like File(cFile)

Readers doesn't have flush(), this is only for writers

7  Generics and Collections

static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
// Correct

class LinkedList<T> {
public LinkedList() {

-It is reflexive. For any reference value x, x.equals(x) should return true.

-It is symmetric. If x equals y then y equals x

-It is transitive. If x equals y and y equals z then z equals x

-It is consistent:Same value through many invocations while objects state are equal

-For any non-null reference value x, x.equals(null) should return false.

8 Inner Classes

public static void main(String[] args) {
MyOuter mo =
new MyOuter(); // gotta get an instance!
MyOuter.MyInner inner = mo.
new MyInner();

To instantiate an inner class, you must have a reference to an instance of the

outer class

From code within the inner class, the keyword this holds a reference to

the inner class instance. To reference the outer this (in other words, the

instance of the outer class that this inner instance is tied to) precede the

keyword this with the outer class name as follows: MyOuter.this;

The only modifiers you can apply to a method-local inner class are abstract

and final. (Never both at the same time, though.)

9 Threads

You can call start() on a Thread object only once. If start() is called

more than once on a Thread object, it will throw a RuntimeException.

When a Thread object is created, it does not become a thread of execution

until its start() method is invoked. When a Thread object exists but hasn't

been started, it is in the new state and is not considered alive.

If not explicitly set, a thread's priority will have the same priority as the

priority of the thread that created it.

The yield() method may cause a running thread to back out if there are

runnable threads of the same priority. There is no guarantee that this will

happen, and there is no guarantee that when the thread backs out there

will be a different thread selected to run. A thread might yield and then

immediately reenter the running state.

Yield - Causes the currently executing thread object to temporarily pause and allow other threads to execute.

Think of the join() method as saying, "Hey thread, I want to join on to the end

of you. Let me know when you're done, so I can enter the runnable state."

notifyAll() wait() and notify() must be called from a synchronized block.

To call wait in an object the thread must own the lock

10 Development

javac [options] [source files]

-d directory to place generated class files

System properties

java -DcmdProp=cmdVal TestProps

Properties p = System.getProperties();

JAR stands for Java Archive


is a new feature in java 5

Before static imports:

public class TestStatic {
public static void main(String[] args) {

After static imports:
  import static java.lang.System.out; // 1
static java.lang.Integer.*; // 2

public class TestStaticImport {
public static void main(String[] args) {
// 3
// 4

An absolute path starts with a / or a \.

Monterrey, NL, Mex. Julio del 2009