Documente Academic
Documente Profesional
Documente Cultură
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
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);
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)
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.
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]) + "; ");
}
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.
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.
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
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.
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.
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:
allows you to print an arbitrary number of objects. It can be called like this:
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:
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.
Garbage Collection
1.0 Introduction
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()
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.
Runtime.getRuntime().gc()
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.
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.
Possible Tricks/Traps
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();)
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
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.
LabeledStatementNoShortIf:
Identifier : StatementNoShortIf
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)