Sunteți pe pagina 1din 25

Table of Contents

1.- Serialization..........................................................................................................................................3
2.- Java Types.............................................................................................................................................4
Enum type..............................................................................................................................................4
3.- String Classes........................................................................................................................................5
4.- Declarations, Initialization and Scoping...............................................................................................5
Variable Declarations............................................................................................................................5
Other Tips..............................................................................................................................................5
5.- Flow Control.........................................................................................................................................6
Other Tips..............................................................................................................................................6
6.- API Contents.........................................................................................................................................6
Some important classes.........................................................................................................................6
Pattern...............................................................................................................................................6
Matcher.............................................................................................................................................6
Streams.............................................................................................................................................7
DateFormat.......................................................................................................................................8
PriorityQueue....................................................................................................................................9
Console (SCJP 6)..............................................................................................................................9
Some important interfaces.....................................................................................................................9
Collections........................................................................................................................................9
NavigableMap<K,V> (SCJP 6)......................................................................................................11
NavigableSet<E> (SCJP 6).............................................................................................................11
Assertions............................................................................................................................................12
7.- Concurrency........................................................................................................................................12
How to create, start and stop threads...................................................................................................12
Thread constructors........................................................................................................................13
Thread priority................................................................................................................................13
Thread Synchronization..................................................................................................................14
8.- Object Oriented Concepts...................................................................................................................14
Tips......................................................................................................................................................14
Access Modifiers.................................................................................................................................14
9.- Fundamentals......................................................................................................................................14
Ternary operator..................................................................................................................................14
Variable parameters function...............................................................................................................14
Iterate...................................................................................................................................................15
Static Import........................................................................................................................................16
Exceptions and Errors.........................................................................................................................16
Static Blocks Errors........................................................................................................................17
Garbage Collection..............................................................................................................................17
Islands of Isolation..........................................................................................................................18
System.gc........................................................................................................................................18
Finalize() and Garbage Collector....................................................................................................18
Equals() and Hashcode().....................................................................................................................19
Other Tips............................................................................................................................................19
10.- Nested Classes..................................................................................................................................20
Static Nested Classes......................................................................................................................21
11.- File Reading/Writing.........................................................................................................................21
12.- Other Tips.........................................................................................................................................21
13.- SCJP 6 differences with SCJP5 .......................................................................................................21
Quickguide for SCJP 5-6 (CX-310-055) (CX-310-065)

1.- Serialization
• Convert an object into bits to be stored in a way that can be “resurrected” later.
• Classes:
◦ java.io
▪ ObjectInputStream
▪ ObjectOutputStream
• Interfaces:
◦ Serializable (empty interface)
▪ Sometimes is required to implement readObject() and writeObject().
▪ DefaultReadObject(): to recover non-static, non-transient fields.
▪ WriteReplace(), readResolved(),
▪ An object serialized on one JVM can be successfully desterilized on a different JVM.
▪ Serialization cannot be perfomed across different JVM versions unless serialversionuid
is overriden.
▪ Serialization can suceed only if the entire object graph of a class is Serializable and non
serializable references are marked as such.
▪ The values in field with the transient modifier will NOT survive serialization and
deserialization.
▪ It is legal to serialize an object of a type that has a supertype that does NOT implement
java .io. Serialization
◦ Externalizable (empty interface)
▪ To be used when a class needs to coordinate with its superclass to serialize itself.
▪ WriteExternal(), ReadExternal().

During deserialization, the fields of non-serializable classes will be initialized using the public
or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that
is serializable. The fields of serializable subclasses will be restored from the stream.
When traversing a graph, an object may be encountered that does not support the Serializable
interface. In this case the NotSerializableException will be thrown and will identify the class of the
non-serializable object.
Classes that require special handling during the serialization and deserialization process must
implement special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;

Tips:
• The constructor of Serializable objects do not run in Deserialization.\
2.- Java Types
Primitive data type Size in memory
boolean 1 byte
byte 1 byte
char 2 bytes
short 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes

Involving class (Java 1.5):


• Auto-boxing: data type -> class
• Auto-unboxing: class -> data type

TIPS:
• A primitive variable cannot be checked against null. autoboxing will not be applied .
• x++ will increment x but the updated value of x will not be visible until next line of execution.
• The result of byte + 1 is an int. An int will not fit into a byte.
• By default a decimal is a double.
• For autoboxing, is important to keep present Java's Pool (http://www.devx.com/tips/Tip/42276).

Enum type
An enum type is a type whose fields consist of a fixed set of constants. Common examples
include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Because they are constants, the names of an enum type's fields are in uppercase letters.
In the Java programming language, you define an enum type by using the enum keyword. For
example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}

Java programming language enum types are much more powerful than their counterparts in other
languages. The enum declaration defines a class (called an enum type). The enum class body can
include methods and other fields. The compiler automatically adds some special methods when it
creates an enum. For example, they have a static values method that returns an array containing all
of the values of the enum in the order they are declared. This method is commonly used in combination
with the for-each construct to iterate over the values of an enum type. For example, this code from the
Planet class example below iterates over all the planets in the solar system.
Suppose you want to add data and behavior to an enum. For example consider the planets of the solar
system. Each planet knows its mass and radius, and can calculate its surface gravity and the weight of
an object on the planet. Here is how it looks:
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7),
PLUTO (1.27e+22, 1.137e6);

private final double mass; // in kilograms


private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }

// universal gravitational constant (m3 kg-1 s-2)


public static final double G = 6.67300E-11;

public double surfaceGravity() {


return G * mass / (radius * radius);
}
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}

for (Planet p : Planet.values()) {


System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}

Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple
inheritance, an enum cannot extend anything else.

TIPS:
• Enum cannot be iterable.
• Enums cannot be declared within methods.
• Much more information:
http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/guide/language/enums.html
3.- String Classes
• String: Strings are constant; their values cannot be changed after they are created. String
buffers support mutable strings. Because String objects are immutable they can be shared. E.g.:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
• StringBuffer: A thread-safe, mutable sequence of characters. A string buffer is like a String but
can be modified.
• StringBuilder: A mutable sequence of characters. This class provides an API compatible with
StringBuffer, but with no guarantee of synchronization.
TIPS:
• The equals() and hashCode() methods are implemented correctly only for the String Class.
(why?)
• Formatting strings
(http://download-llnw.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax)

4.- Declarations, Initialization and Scoping

Variable Declarations
• Instance variable: defined without any modifier, just “Type vname”.
• Static: class variable. Isn't necessary to create an instance to use it.
• Volatile: prevents Java compiler to make optimizations to this variable.
• Transient: prevents JVM to serialize this variable.
• Final: constant value.
• e.g.: public static final double PI= 3.1415...

Other Tips
• Final and Abstract never go together. Static methods cannot be overriden .
• Getter and Setter of boolean standard is isBoolean and setBoolean(boolean) .
• A static method can be called from a non static context but not vice versa .
• A static method can be called without the need for a object instance. The same is not true for
non static methods .
• Abstract classes can be empty and classes that have abstracts methods in them must be marked
abstract .
• Abstract classes can be empty and an implementing subclass must surely implement all
methods if it is not abstract.
• Member variables default to null and local variables default to 0.
5.- Flow Control

Other Tips
- It is not advisable to use assertions to assert arguments of public methods.
- It is not advisable to use assertions to assert command line arguments or methods that modify class
state.

- Asserts should not be used to check arguments of public methods .


- Static methods cannot override instance methods.

6.- API Contents

Some important classes

Pattern
A compiled representation of a regular expression. A regular expression, specified as a string,
must first be compiled into an instance of this class. The resulting pattern can then be used to create a
Matcher object that can match arbitrary character sequences against the regular expression. It has a
method called “matcher” which returns a Matcher.
To escape a regular expression is necessary to backslash de regular expression (e.g:
Pattern.compile(“\\s+”), search for one or more whitespaces).

Matcher
An engine that performs match operations on a character sequence by interpreting a Pattern
(e.g: Matcher matcher= pattern.matcher(“123 a 34 a “);).
A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a
matcher can be used to perform three different kinds of match operations:
• The matches method attempts to match the entire input sequence against the pattern.
• The lookingAt method attempts to match the input sequence, starting at the beginning, against
the pattern.
• The find method scans the input sequence looking for the next subsequence that matches the
pattern.

Streams
{Input|Output}Stream
This abstract class is the superclass of all classes representing an input stream of bytes.
Applications that need to define a subclass of InputStream must always provide a method that returns
the next byte of input.
• FileInputStream:
A FileInputStream obtains input bytes from a file in a file system. What files are
available depends on the host environment. FileInputStream is meant for reading
streams of raw bytes such as image data. For reading streams of characters, consider
using FileReader.
In FileOutputStream: Some platforms, in particular, allow a file to be opened for
writing by only one FileOutputStream (or other file-writing object) at a time. In such
situations the constructors in this class will fail if the file involved is already open.
• InputStream:
InputStream is the Java API for reading IDL types from CDR marshal streams. These
methods are used by the ORB to unmarshal IDL types as well as to extract IDL types out
of Anys. The _array versions of the methods can be directly used to read sequences and
arrays of IDL types.
• ObjectInputStream:
An ObjectInputStream deserializes primitive data and objects previously written using
an ObjectOutputStream. ObjectOutputStream and ObjectInputStream can provide
an application with persistent storage for graphs of objects when used with a
FileOutputStream and FileInputStream respectively.
ObjectInputStream is used to recover those objects previously serialized. Other uses
include passing objects between hosts using a socket stream or for marshaling and
unmarshaling arguments and parameters in a remote communication system.
• BufferedInputStream:
A BufferedInputStream adds functionality to another input stream-namely, the ability
to buffer the input and to support the mark and reset methods.
When the BufferedInputStream is created, an internal buffer array is created. As bytes
from the stream are read or skipped, the internal buffer is refilled as necessary from the
contained input stream, many bytes at a time. The mark operation remembers a point in
the input stream and the reset operation causes all the bytes read since the most recent
mark operation to be reread before new bytes are taken from the contained input stream.
• DataInputStream:
A data input stream lets an application read primitive Java data types from an underlying
input stream in a machine-independent way. An application uses a data output stream to
write data that can later be read by a data input stream.

TIP:
• The objects must be read in the same order in which they are written.
• Readers cannot buffer on their own without the help of a BufferedReader
• The readLine() method is available in BufferedReader alone. As of Java 5 PrintWriter can
accept both a File and a String.

Examples:
Write:
File file = new File(""); Writer writer = new FileWriter(file);
BufferedWriter bufferedWriter= new BufferedWriter(writer);

Read:
File file = new File(""); FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);

DateFormat
DateFormat is an abstract class for date/time formatting subclasses which formats and parses
dates or time in a language-independent manner. The date/time formatting subclass, such as
SimpleDateFormat, allows for formatting (i.e., date -> text), parsing (text -> date), and normalization.
The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
E.g:
To format a date for the current Locale, use one of the static factory methods:
myString = DateFormat.getDateInstance().format(myDate);

If you are formatting multiple dates, it is more efficient to get the format and use it multiple times so that the system doesn't have
to fetch the information about the local language and country conventions multiple times.
DateFormat df = DateFormat.getDateInstance();
for (int i = 0; i < myDate.length; ++i) {
output.println(df.format(myDate[i]) + "; ");
}

To format a date for a different Locale, specify it in the call to getDateInstance().


DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);

You can use a DateFormat to parse also.


myDate = df.parse(myString);

When formatting dates, you can choose the following formats. The exact results depends on the
locale, but generally:
• SHORT is completely numeric, such as 12.13.52 or 3:30pm
• MEDIUM is longer, such as Jan 12, 1952
• LONG is longer, such as January 12, 1952 or 3:30:32pm
• FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm
PST.
TIP:
• There is no setLocale() method within this class.
• The Date() constructor forms a Date object based on today's date.

PriorityQueue
An unbounded priority queue based on a priority heap. This queue orders elements according to
an order specified at construction time, which is specified either according to their natural order (see
Comparable), or according to a Comparator, depending on which constructor is used. A priority
queue does not permit null elements. A priority queue relying on natural ordering also does not permit
insertion of non-comparable objects (doing so may result in ClassCastException).
The head of this queue is the least element with respect to the specified ordering. If multiple
elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The
queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

Console (SCJP 6)
Methods to access the character-based console device, if any, associated with the current Java
virtual machine.
Whether a virtual machine has a console is dependent upon the underlying platform and also
upon the manner in which the virtual machine is invoked. If the virtual machine is started from an
interactive command line without redirecting the standard input and output streams then its console will
exist and will typically be connected to the keyboard and display from which the virtual machine was
launched. If the virtual machine is started automatically, for example by a background job scheduler,
then it will typically not have a console.

Some important interfaces

Collections
Collection (Interface)
• All Superinterfaces:
◦ Iterable<E>
• Some Subinterfaces:
◦ List<E>, Queue<E>, Set<E>, SortedSet<E>
• Some implementing classes:
◦ AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet,
ArrayBlockingQueue, ArrayList, AttributeList, EnumSet, HashSet, LinkedHashSet,
LinkedList, PriorityQueue, TreeSet, Vector.
The root interface in the collection hierarchy. A collection represents a group of objects, known
as its elements. Some collections allow duplicate elements and others do not. Some are ordered and
others unordered. The JDK does not provide any direct implementations of this interface: it provides
implementations of more specific subinterfaces like Set and List. This interface is typically used to
pass collections around and manipulate them where maximum generality is desired.
Collection is an interface and Collections is a class with static methods.

Set
A collection that contains no duplicate elements. More formally, sets contain no pair of elements
e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface
models the mathematical set abstraction.
Note: Great care must be exercised if mutable objects are used as set elements. The behavior of
a set is not specified if the value of an object is changed in a manner that affects equals comparisons
while the object is an element in the set. A special case of this prohibition is that it is not permissible for
a set to contain itself as an element.

List
An ordered collection (also known as a sequence). The user of this interface has precise control
over where in the list each element is inserted. The user can access elements by their integer index
(position in the list), and search for elements in the list.

Map
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to
at most one value.
This interface takes the place of the Dictionary class, which was a totally abstract class rather than an
interface.
The Map interface provides three collection views, which allow a map's contents to be viewed as a set
of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order
in which the iterators on the map's collection views return their elements. Some map implementations,
like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do
not.

TIPS:
• The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and
permits nulls.
• Maps can be iterated either by using the key-set or the entry set.
• When sorting the jvm gives preference to space, then CAPS and then to lower case alphabets.
• You may define the collection elements' type by defining the variable like this (it's called
Generics):
◦ CollectionType <E> myCollection.
◦ CollectionType <? extends E> myCollection (Only E, and its subclasses).
◦ CollectionType <? super E> myCollection (Only E, and its superclasses).
Tips:
• Collections.sort() method only takes arguments that are Comparables

NavigableMap<K,V> (SCJP 6)
A SortedMap extended with navigation methods returning the closest matches for given search
targets. Methods lowerEntry, floorEntry, ceilingEntry, and higherEntry return Map.Entry objects
associated with keys respectively less than, less than or equal, greater than or equal, and greater than a
given key, returning null if there is no such key. Similarly, methods lowerKey, floorKey, ceilingKey,
and higherKey return only the associated keys. All of these methods are designed for locating, not
traversing entries.
A NavigableMap may be accessed and traversed in either ascending or descending key order.
The descendingMap method returns a view of the map with the senses of all relational and directional
methods inverted. The performance of ascending operations and views is likely to be faster than that of
descending ones. Methods subMap, headMap, and tailMap differ from the like-named SortedMap
methods in accepting additional arguments describing whether lower and upper bounds are inclusive
versus exclusive. Submaps of any NavigableMap must implement the NavigableMap interface.

NavigableSet<E> (SCJP 6)
A SortedSet extended with navigation methods reporting closest matches for given search
targets. Methods lower, floor, ceiling, and higher return elements respectively less than, less than or
equal, greater than or equal, and greater than a given element, returning null if there is no such element.
A NavigableSet may be accessed and traversed in either ascending or descending order. The
descendingSet method returns a view of the set with the senses of all relational and directional
methods inverted. The performance of ascending operations and views is likely to be faster than that of
descending ones. This interface additionally defines methods pollFirst and pollLast that return and
remove the lowest and highest element, if one exists, else returning null. Methods subSet, headSet, and
tailSet differ from the like-named SortedSet methods in accepting additional arguments describing
whether lower and upper bounds are inclusive versus exclusive. Subsets of any NavigableSet must
implement the NavigableSet interface.

The return values of navigation methods may be ambiguous in implementations that permit null
elements. However, even in this case the result can be disambiguated by checking contains(null). To
avoid such issues, implementations of this interface are encouraged to not permit insertion of null
elements. (Note that sorted sets of Comparable elements intrinsically do not permit null.)

Methods subSet(E, E), headSet(E), and tailSet(E) are specified to return SortedSet to allow
existing implementations of SortedSet to be compatibly retrofitted to implement NavigableSet, but
extensions and implementations of this interface are encouraged to override these methods to return
NavigableSet.

This interface is a member of the Java Collections Framework.


Assertions
(http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html)
The assertion statement has two forms. The first, simpler form is:
assert Expression1 ;

where Expression1 is a boolean expression. When the system runs the assertion, it evaluates
Expression1 and if it is false throws an AssertionError with no detail message.
The second form of the assertion statement is:
assert Expression1 : Expression2 ;

where:
• Expression1 is a boolean expression.
• Expression2 is an expression that has a value. (It cannot be an invocation of a method that is
declared void.)

Use this version of the assert statement to provide a detail message for the AssertionError. The
system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the
string representation of the value as the error's detail message.
By default, assertions are disabled at runtime. Two command-line switches allow you to
selectively enable or disable assertions.
To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable
assertions at various granularities, use the -disableassertions, or -da, switch.

TIPS:
• In java 1.3 assertions do not existed, so you could define “int assertion”;

7.- Concurrency

How to create, start and stop threads


There are two ways to create threads:
• Inherit from the Thread class and overriding its run() method.
• Implementing the Runnable interface, giving an implementation only for its run() method.
To execute a thread, is necessary to:
• Create an instance of the derived class.
• Invoke the start() method of the object. This method calls run() (run() cannot be called
directly).
• The thread is alive until the run() method ends its execution.
There are two methods to stop a thread but both are insecure: stop() and destroy(). The best way is to
use a flag in the run() method to know if the thread is stopped, catching InterruptedException and
manually establishing cleaning activities.

In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class
that implements Runnable can run without subclassing Thread by instantiating a Thread instance and
passing itself in as the target. In most cases, the Runnable interface should be used if you are only
planning to override the run() method and no other Thread methods. This is important because classes
should not be subclassed unless the programmer intends on modifying or enhancing the fundamental
behavior of the class.

Entering a synced block or method means a) you obtain the lock associated with a particular object and
b) no other thread can obtain that same lock until you either exit the synced block or method, or call
wait() on it.

Another methods:
• sleep()
• suspend()
• resume()
• interrupt()
• isInterrupted()
• yield()
• wait()
• notify()
• notifyAll()

Thread constructors
• Public Thread();
• Public Thread(Runnable thread);
• Public Thread(Runnale thread, String name);
• Public Thread(String name);
• Public Thread(ThreadGroup group, Runnable thread);
• Public Thread(ThreadGroup group, Runnable thread, String name);
• Public Thread(ThreadGroup group, String name);

Thread priority
With getPriority() and setPriority(int newPriority) it can consulted and set the value of the priority of a
thread. The value of the priority is a int that goes between MAX_PRIORITY and MIN_PRIORITY.
Also there is a NORM_PRIORITY.

Thread Synchronization
A method can be synchronized by using the reserved word synchronized before the return type. This is
used to provide access only to one object at a time.
Also exists a synchronized block to synchronize an object in a given time:
synchronized (myObject) { //code;}

TIP:
• Only Objects can be synchronized. Pay attention to what a method returns to understand if the
code can synchronize on it or not. for example, println() returns void and you cannot
synchronize on it. toString() returns a String object and you can this synchronize on it.
• Threads cannot be started twice.

More information: http://stackoverflow.com/questions/2120248/how-to-synchronize-a-static-variable-


among-threads-running-different-instances-of

8.- Object Oriented Concepts

Tips
• Variables in Java are always passed by value.
• Subclass can't constrict the access modifier. You can override a default or protected method
with a public one, but not the reverse (e.g.: toString())
• Non static can't be accessed from a static context.

Access Modifiers
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
default (no modifier) Y Y N N
private Y N N N
9.- Fundamentals

Ternary operator
• e.g: minVal = (a < b) ? a : b;
• Ternary operator expects a return value.

Variable parameters function


(Passing arguments: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html)
You can use a construct called varargs to pass an arbitrary number of values to a method. You
use varargs when you don't know how many of a particular type of argument will be passed to the
method. It's a shortcut to creating an array manually (the previous method could have used varargs
rather than an array).
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a
space, and the parameter name. The method can then be called with any number of that parameter,
including none.

public Polygon polygonFrom(Point... corners) {


int numberOfSides = corners.length;
double squareOfSide1, lengthOfSide1;
squareOfSide1 = (corners[1].x - corners[0].x)*(corners[1].x - corners[0].x)
+ (corners[1].y - corners[0].y)*(corners[1].y - corners[0].y) ;
lengthOfSide1 = Math.sqrt(squareOfSide1);
// more method body code follows that creates
// and returns a polygon connecting the Points
}

You can see that, inside the method, corners is treated like an array. The method can be called
either with an array or with a sequence of arguments. The code in the method body will treat the
parameter as an array in either case.
You will most commonly see varargs with the printing methods; for example, this printf
method:

public PrintStream printf(String format, Object... args)

allows you to print an arbitrary number of objects. It can be called like this:

System.out.printf("%s: %d, %s%n", name, idnum, address);

or like this
System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, email);
or with yet a different number of arguments.

Iterate
Interesting links:
• http://www.javapractices.com/topic/TopicAction.do?Id=88
• http://www.javapractices.com/topic/TopicAction.do?Id=125

Static Import
(http://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.html)
Static imports should be made such that the * succeeds the class name. Normal imports can
mention the class name or the * wildcard after a package

In order to access static members, it is necessary to qualify references with the class they came
from. For example, one must say:

double r = Math.cos(Math.PI * theta);

In order to get around this, people sometimes put static members into an interface and inherit
from that interface. This is a bad idea. In fact, it's such a bad idea that there's a name for it: the
Constant Interface Antipattern (see Effective Java Item 17). The problem is that a class's use of the
static members of another class is a mere implementation detail. When a class implements an interface,
it becomes part of the class's public API. Implementation details should not leak into public APIs.
The static import construct allows unqualified access to static members without inheriting from
the type containing the static members. Instead, the program imports the members, either individually:
import static java.lang.Math.PI;

or en masse:
import static java.lang.Math.*;

Once the static members have been imported, they may be used without qualification:
double r = cos(PI * theta);

The static import declaration is analogous to the normal import declaration. Where the normal
import declaration imports classes from packages, allowing them to be used without package
qualification, the static import declaration imports static members from classes, allowing them to be
used without class qualification.
So when should you use static import? Very sparingly! Only use it when you'd otherwise be
tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface
Antipattern). In other words, use it when you require frequent access to static members from one or two
classes. If you overuse the static import feature, it can make your program unreadable and
unmaintainable, polluting its namespace with all the static members you import. Readers of your code
(including you, a few months after you wrote it) will not know which class a static member comes
from. Importing all of the static members from a class can be particularly harmful to readability; if you
need only one or two members, import them individually. Used appropriately, static import can make
your program more readable, by removing the boilerplate of repetition of class names.

Exceptions and Errors


Tips:
• Wider exception hierarchy must be at the bottom of the catch pile
• Errors cannot be caught by the exception hierarchy. the finally block will however run
regardless of whether errors or exceptions are thrown
• Throwable can be catch with the Try-Catch statement.
• Difference between them is that error isn't necessary to catch or declare.
• Isn't necessary to declare RuntimeExceptions either.
• Any overriding method can throw an exception that is more narrow. It can however not throw
an exception that is broader. Such statements will not compile. It is also acceptable if the
method does not throw an appropriate exception.
• ReaderExcepion is not a know exception type and calls to super.method() must appropriately
handle de exception that it throws.

Static Blocks Errors


public class ExceptionInInitializerError
extends LinkageError

Signals that an unexpected exception has occurred in a static initializer. An


ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a
static initializer or the initializer for a static variable.
As of release 1.4, this exception has been retrofitted to conform to the general purpose
exception-chaining mechanism. The "saved throwable object" that may be provided at construction
time and accessed via the getException() method is now known as the cause, and may be accessed via
the Throwable.getCause() method, as well as the aforementioned "legacy method."

Garbage Collection
1.0 Introduction

• For many applications garbage collection performance is not significant


• Default collector should be first choice
2.0 Generations
• Most straightforward GC will just iterate over every object in the heap and determine if any
other objects reference it.
• This gets really slow as the number of objects in the heap increase
• GC's therefor make assumptions about how your application runs.
• Most common assumption is that an object is most likely to die shortly after it was created:
called infant mortality
• This assumes that an object that has been around for a while, will likely stay around for a while.
• GC organizes objects into generations (young, tenured, and perm) This is important!
Additional information (Source): Tuning GC http://www.petefreitag.com/articles/gctuning/

Islands of Isolation
• "If an object obj1 is garbage collected, but another object obj2 contains a reference to it, then
obj2 is also eligible for garbage collection"
• "If object obj2 can access object obj1 that is eligible for garbage collection, then obj2 is also
eligible for garbage collection"
This is called "Island of Isolation". An "island of isolation" describes one or more objects have NO
references to them from active parts of an application.
(http://www.xyzws.com/Javafaq/what-is-islands-of-isolation-in-garbage-collection/42)

System.gc
Public static void gc()

Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling
unused objects in order to make the memory they currently occupy available for quick reuse.
When control returns from the method call, the Java Virtual Machine has made a best effort to
reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc()

Finalize() and Garbage Collector


protected void finalize()
throws Throwable

Called by the garbage collector on an object when garbage collection determines that there are no
more references to the object. A subclass overrides the finalize method to dispose of system
resources or to perform other cleanup.

The general contract of finalize is that it is invoked if and when the JavaTM virtual machine
has determined that there is no longer any means by which this object can be accessed by any
thread that has not yet died, except as a result of an action taken by the finalization of some other
object or class which is ready to be finalized. The finalize method may take any action,
including making this object available again to other threads; the usual purpose of finalize,
however, is to perform cleanup actions before the object is irrevocably discarded. For example,
the finalize method for an object that represents an input/output connection might perform
explicit I/O transactions to break the connection before the object is permanently discarded.

The finalize method of class Object performs no special action; it simply returns normally.
Subclasses of Object may override this definition.

The Java programming language does not guarantee which thread will invoke the finalize
method for any given object. It is guaranteed, however, that the thread that invokes finalize will
not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught
exception is thrown by the finalize method, the exception is ignored and finalization of that
object terminates.

After the finalize method has been invoked for an object, no further action is taken until the
Java virtual machine has again determined that there is no longer any means by which this object
can be accessed by any thread that has not yet died, including possible actions by other objects or
classes which are ready to be finalized, at which point the object may be discarded.

The finalize method is never invoked more than once by a Java virtual machine for any
given object.

Any exception thrown by the finalize method causes the finalization of this object to be
halted, but is otherwise ignored.

Equals() and Hashcode()


TIPS:
• Hash code implementations should ensure that two objects for comparison fall under the same
hash bucket.
• Equals(Object o) is the firm of the function. If you want to override it you can't do things like
equals(String o).
• If two objects compared using equals returns true, then their hashcode must be the same.

Other Tips
1. When extending a class always ensure that it has a public constructor, since the compiler will
try to call it by default.
2. High cohesion ensures better responsibility boundaries for each class.
3. The methods main is static and cannot have a body that references non static variables.
4. Polymorphism is exhibited wherever a base class calls a subclass implementation .
5. The static init blocks run first. Normal init blocks run next followed by constructors and
methods.
6. If the [] characters appear before the variable name then any further array definitions will have
one more dimension associated with them.
7. first static initializer are run in order. then non static initializers are executed. this is followed by
constructors. after execution of constructors the methods are called.
8. the compiler knows before that the operation a + b will not fit into a byte, since the byte is final
9. Watch out for unreachable statements in the code. i.e.: If “x++” after a “throw new
Exception();” is never reachable since throw new Exception() will execute and the exception is
thrown to the catch block. This results in a compile error.
10. Static methods cannot be overridden:
Static methods are class-methods, not object-methods.
Normally, in OO, you specify for which object you want to invoke a method.
This means that the invocation always needs to carry information on what
object the method is invoked on and what the type of the object is.

This is not necessary for class-methods. Static methods can be invoked


regardless of the fact that you have an object of that type or a derived
type. And since it cannot assume the existence of an object, it also cannot
make use of information regarding overriding of methods, hence it calls the
static method that belongs to the class it belongs to.
(http://www.velocityreviews.com/forums/t144410-overriding-static-methods-why-
doesn-t-it-work.html)
11. Transient variables are ignored in subclassing.
12. A constructor cannot be declared Public void.
13. By default an interface houses variables that are public static and final.
14. Iterators cannot be used in the enhanced for loop. A comparable that returns an Iterator can
however be used. An ArrayList IS A Comparable.
15. Final methods cannot be overridden (compile error)
16. Static methods cannot be overridden (nothing happen)
17. Variables cannot be overridden (if subclass doesn't have it, it can call super?)
18. INTEGER.MAX_VALUE + 1 return negative in cyclic way
19. Object[] ar = new object[4]
20. Primitive cannot be checked against null

Possible Tricks/Traps

• Two top-level public classes cannot be in the same source file.


• main() cannot call an instance (non-static) method.
• Methods can have the same name as the constructor(s).
• Watch for thread initiation with classes that don't have a run() method.
• Local classes cannot access non-final variables.
• Case statements must have values within permissible range.
• Watch for Math class being an option for immutable classes.
• instanceOf is not the same as instanceof.
• Constructors can be private.
• Assignment statements can be mistaken for a comparison; e.g., if(a=true)...
• Watch for System.exit() in try-catch-finally blocks.
• Watch for uninitialized variable references with no path of proper initialization.
• Order of try-catch-finally blocks matters.
• main() can be declared final.
• -0.0 == 0.0 is true.
• A class without abstract methods can still be declared abstract.
• RandomAccessFile descends from Object and implements DataInput and DataOutput.
• Map does not implement Collection.
• Dictionary is a class, not an interface.
• Collection (singular) is an Interface, but Collections (plural) is a helper class.
• Class declarations can come in any order (e.g., derived first, base next, etc.).
• Forward references to variables gives a compiler error.
• Multi-dimensional arrays can be "sparse" -- i.e., if you imagine the array as a matrix, every row need not
have the same number of columns.
• Arrays, whether local or class-level, are always initialized
• Strings are initialized to null, not empty string.
• An empty string is not the same as a null reference.
• A declaration cannot be labelled.
• continue must be in a loop (e.g., for, do, while). It cannot appear in case constructs.
• Primitive array types can never be assigned to each other, even though the primitives themselves can
be assigned. For example, ArrayofLongPrimitives = ArrayofIntegerPrimitives gives compiler error even
though longvar = intvar is perfectly valid.
• A constructor can throw any exception.
• Initializer blocks are executed in the order of declaration.
• Instance initializers are executed only if an object is constructed.
• All comparisons involving NaN and a non-NaN always result in false.
• Default type of a numeric literal with a decimal point is double.
• int and long operations / and % can throw an ArithmeticException, while float and double / and % never
will (even in case of division by zero).
• == gives compiler error if the operands are cast-incompatible.
• You can never cast objects of sibling classes (sharing the same parent).
• equals() returns false if the object types are different. It does not raise a compiler error.
• No inner class can have a static member.
• File class has no methods to deal with the contents of the file.
• InputStream and OutputStream are abstract classes, while DataInput and DataOutput are
interfaces.

10.- Nested Classes


http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that
are declared static are simply called static nested classes. Non-static nested classes are called inner
classes.
There are several compelling reasons for using nested classes, among them:
• It is a way of logically grouping classes that are only used in one place.
• It increases encapsulation.
• Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it
in that class and keep the two together. Nesting such "helper classes" makes their package more
streamlined.
Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members
of A that would otherwise be declared private. By hiding class B within class A, A's members can
be declared private and B can access them. In addition, B itself can be hidden from the outside world.
More readable, maintainable code—Nesting small classes within top-level classes places the code
closer to where it is used.

TIPS:
• Inner classes can be created only if a reference of the outer class is available (Tear rabbit = new
Tear(); Tear.Rain terrain = rabbit.new Rain();)

Static Nested Classes


As with class methods and variables, a static nested class is associated with its outer class. And like
static class methods, a static nested class cannot refer directly to instance variables or methods defined
in its enclosing class — it can use them only through an object reference.

Note: A static nested class interacts with the instance members of its outer class (and other
classes) just like any other top-level class. In effect, a static nested class is behaviorally a
top-level class that has been nested in another top-level class for packaging convenience.

Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();

http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html

11.- File Reading/Writing


See section 6.- API Contents/Some Important Classes/Streams
Tips:
• When a writer or reader expects a file to be present a FileNotfoundException may be thrown.

12.- Other Tips


• Is not necessary to declare a method to throw RuntimeException and its subclasses.
True
• A protected method in class X can be overridden by any subclass of X.
• A public static method in class X can be called by a subclass of X without explicitly referencing
the class.
• A method with the same signature as a private final method in class X can be implemented in a
subclass of X.

Not True
• A final method in class X can be abstract if and only if X is abstract.
• A private static method can be called only within other static methods in class X.
• A non-static public final method in class X can be overridden in any subclass of X.
• A protected method in class X can be overridden by a subclass of X only if the subclass is in the
same package as X.

13.- Labeled Statements


Statements may have label prefixes.
LabeledStatement:
Identifier : Statement

LabeledStatementNoShortIf:
Identifier : StatementNoShortIf

The Identifier is declared to be the label of the immediately contained Statement.


Unlike C and C++, the Java programming language has no goto statement; identifier statement labels
are used with break (§14.14) or continue (§14.15) statements appearing anywhere within the
labeled statement.
The scope of a label declared by a labeled statement is the statement immediately enclosed by the
labeled statement.
Let l be a label, and let m be the immediately enclosing method, constructor, instance initializer or
static initializer. It is a compile-time error if l shadows (§6.3.1) the declaration of another label
immediately enclosed in m.
There is no restriction against using the same identifier as a label and as the name of a package, class,
interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not
obscure (§6.3.2) a package, class, interface, method, field, parameter, or local variable with the same
name. Use of an identifier as a class, interface, method, field, local variable or as the parameter of an
exception handler (§14.19) does not obscure a statement label with the same name.
A labeled statement is executed by executing the immediately contained Statement. If the statement is
labeled by an Identifier and the contained Statement completes abruptly because of a break with the
same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion
of the Statement, the labeled statement completes abruptly for the same reason.
(http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html)
14.- SCJP 6 differences with SCJP5
Exam objectives: Several new API classes/interfaces have been added: java.io.Console,
java.util.NavigableSet, java.util.NavigableMap. Explicit garbage collector calls (i.e. System.gc()) will
no longer be tested, but candidates will still be expected to understand garbage collection and the
finalize() method. Also, the following topics will be tested in greater depth: exception handling,
collections, assertions, threads, and flow control. See this topic, java.io.Console, java.util.NavigableSet
and SCJP 6 vs SCJP 5 for more detail.

PERSONAL QUESTIONS:
When a subclass call its constructor, it calls the superclass constructor also. It happens the same with
interfaces? (I guess not → CORRECT!)
- 6- "Nothing can be added to this collection since the '? extends' keywords are used → The problem is
“? Extends Serializable”
4- seguro R x → DONE
- Java: if superclass implements interface, subclass inherits that? → YES
- comparable, comparator V
- overridden vs overloaded V
- java -Dprop.custom=gobstopper Commander -> Sets a new system property called prop.custom
and value gobstopper. It can then be accesed through System.getProperty(“prop.custom”) and
System.getProperties().getProperty(“prop.custom”).
- Arrays.sort comparable
- metdos navigableset
- Wait(1)

S-ar putea să vă placă și