JAVA QUIRKS v1
- The package declaration must come before any
imports.
- break; ß causes exit of control statement… switch, for,
while etc.
this
also works with if statements (including labelled break)
- continue; ß skip remaining statements in loop body
- break and continue accept lables eg:
mylable:for(x=0;x<y;x++){… break mylable …}
- instanceof ß operator used: xxx instanceof int;
- Identifiers cannot start with a number or contain
a – sign. _ and $ are allowed
(but not recommended as compilers use them too.
- Logic execution is left-to-right and short
circuits :
eg: (n != 0)
&& (100/n ==2) ß no div0 error can occur
- Parameter evaluation is left-to-right which
matters if there are side-effects, and
parameter evaluation runs on all parameters before precedence
evaluation starts:
E.g: compare((a++),(a-1))
- A[i] += 10 evaluates quicker than a[i] = a[i] +
10; as the left-hand parameter is
only evaluated once. This is significant if the
evaluation has side effects.
- Any class can have a main method that is run if
it is called from the command line
(often for tests). JAR files contain a manifest which
indicates which class to run.
- Identifiers cannot start with a number or contain
a – sign. _ and $ are allowed
(but not recommended as compilers use them too)
- Import static java.lang.Math.*; ß the static keyword imports just the static
members
of that class.
- Number x =
Double(42); ß this is called a widening conversion
- goto ß reserved keyword, not currently used.
- Java.awt and java.util both contain List. The
following determines which list to use
if the full
namespace is not given in the code:
import java.util.* ß on demand importing
import java.awt.*
import.java.util.List ß use this one as the default
- Invoke an overridden method using
super.myMethod() which is not the same as:
((MySuperclass)this).myMethod() which will call the
subclass due to polymorphism.
- Return types are not part of the method signature
(when over-riding).
As of 5.0 overriding methods may give a narrower
return type than their
subclass (e.g. return their own class rather than the
subclass)
this is known as a covariant return.
- System.gc() is only a hint, garbage collection is
not certain to run.
- The args[0] in static void main(String[] args) is
the parameter after the file or class.
ABSTRACT
- If a class has abstract methods it must itself be
declared abstract.
EXCEPTIONS
- Catch derived exceptions first as superclass exceptions
also match; execution recommences AFTER the last catch block.
- An overridden superclass method cannot throw
exception types not thrown by the superclass, but it can throw less if it
wants.
- If a finally or catch block throws an exception
that does not get caught within the finally, it replaces any unhandled
exception.
- Rethrow exceptions in a catch block using: throw
new MyException(“snafu”, passed exception); ß this includes the
details of the original cause in the stack trace.
- Exceptions extending Exception must be caught to
compile (they are checked exceptions)
- Exceptions extending RuntimeException don’t need
catching and will get caught by the java default handler.
INTERFACES
- A new interface can extend (i.e. inheret from)
any number of existing interfaces.
- Can contain a static member class.
- The only fields allowed are those that are
declared as static final.
- Are good because you can only inherit from one
class, so inheriting from a default implementation
prevents you inheriting from other classes. You could
use a longer inheritance chain to overcome this,
or use an object adapter pattern / proxy to combine
several default implementations into one class.
- The down side is if you later add a new method to
the interface you also break all the classes that implement the existing
interface.
- Return types are part of the interfaces method
signatures (unlike when you over-ride a class method where narrower types
are allowed).
Failure to methods with the correct return will throw
a ‘does not implement’ compile error.
MATHS
- Things cannot be promoted to type char.
- Short (16 bit value) is signed.
- Postfix an f for float literal values.
- float and double have special values for
infinity, -infinity, -1/infinity, 0/0
Divide
by 0 errors never occur!
For
example 1/negzero = -infinity
- NaN is not equal to any other number including
itself.
- NaN = (0/0) can only be detected using
Double.isNAN()
- Double defines MIN_VALUE MAX_VALUE NEGATIVE_INFINITY POSITIVE_INFINITY NaN
- >>> = rightshift, moving 0 into msb,
there is no <<<
- The number of places shifted undergoes modulus 32
first. E.g. <<64 does nothing
- % modulo also works with floats
- String(“1” + 1) evaluates to 11 as the + is also
string concatation.
- A leading zero on a literal means it is treated
as octal! For example 010 is 8 in decimal.
NESTED TYPES
- Static member classes are declared within a containing class and only
have access to
its static members (including private ones). It is
part of the containing class’s namespace.
- Static member classes cannot be defined within
other non-static nested classes.
- Things outside the class declaration can gain
access to the static nested class using ContainingClass.MyInnerClass.
- Non-Static member class. For example the Iterator returned by calling
iterator() on a Collection instance.
- Has access to all fields of the containing class
including those declared private.
- Cannot contain static members as it is inside
another class except those declared static final.
This also
applies to both local classes and anonymous classes.
- Interfaces, enumerated types and annotations are
not allowed as these are inherently static.
- Has access to all fields of the containing class
including those declared private.
- Cannot have the same name as the containing class
or package.
- OuterClass.this.OuterClassField ß Use to obtain to a member of the containing
class, that is hidden by a member within the/an inner
class.
- OuterClass.super.OuterClassField ß Use to obtain a member of the superclass of
a containing
class outer class, that is hidden by a member within the/an inner class.
- OuterClass.new .innerClass() ß also a valid syntax.
- Local class. Everything the local class uses from the
containing class must be declared final.
This could be achieved by including final in the
parameter blocks of the containing class.
getItterator(){
… define MyItteratorClass … ß can contain a constructor
return new MyItteratorClass()
}
- Cannot accept public, private, protected or
static modifiers. They are limited in scope to the method that called
them.
- Anonymous class Similar
to local classes. Useful if the class is short, only one instance is
needed,
it is used immediately where or after it is defined,
the class name is not needed to help understanding.
- Contains no constructor but an instance
initializer is allowed that could call its superclass such as:
{ … initialisation code …}
- Can extend an existing class or be used to
implement an interface.
- Example that extending class Animal by calling
its constructor that injects the number of legs:
getMoose(){
return new Animal(4){
… definition…
String
getDiet(){return new String(“grass”)}
}
}
OBJECTS
- If obj1.equals(obj2) and obj2.equals(obj3) then
obj1.equals(obj3) should return true.
- Default Object.equals() method just compares the
references. If it is called on two arrays it just compares the references.
- Java.util.Array equals() method is better calling
.equals on all elements in the array.
- Classes over-ridding equals() should override
hashcode() so it produces the same value if objects are equal,
otherwise collections such as hashmap etc will not function correctly.
- Default Object.clone() only creates an object
with identical fields, it is not recursive!
- Default Object.clone() is a native method
producing a byte-for-byte copy.
- Default Object.clone() is protected, so from
outside the package you could inherit from a cloned object to gain access
to its protected members.
- To make something generally cloneable add
implements Cloneable and add a public clone() method eg:
@Override
Public
Object clone(){try{return super.clone();}catch(CloneNotSupportedException
e){throw new AssertionError(e);}
STATIC
- Static variables cannot be declared in methods!
- Static methods cannot be over-ridden
THREADING
- Swing is not threadsafe. Use
SwingUtilities.invokeLater(runnable) to ensure all GUI update runnables
execute in the right order using the event dispatch
thread.
- Thread states are: New, Runnable, Blocked,
Waiting, TimedWait and Terminated.
- Use assert Thread.holdsLock(object) to check you
have a lock.
- Thread.sleep(ms) ß throws InterruptedException. Releases the
processor but does not release any locked objects.
- Thread.yeald() ß causes the thread (or caller) to release the
processor then attempt to reacquire it.
- Thread scheduling algorithms are platform
dependent, so things like yeald() are not ensured to act the same on all
platforms
- volatile ß keyword ensures threads do not cache the field
and flush it immediately. Care must be taken to ensure concurrency does
not cause
inconsistency or deadlock if more than one volatile is used. Volatile is handled incorrectly on some
virtual machines.
- volatile operates faster than a synchronised
block, which flushes the thread cache on exit.
- Priority levels range from 1 to 10 (highest), 5 =
NORM_PRIORITY
- ReenterantLock(true) ß implements a fairness policy so longest waiting
thread with the same priority goes first, but lowers performance slightly.
- Call newCondition on a lock object to create a
new condition, locks can have several conditions.
- Call await() on a condition object to wait until
another thread calls signal() or signalAll() on the same condition.
Calling await releases the lock on the object. await
also accepts a timeout.
- synchronised
can be apply to individual methods or a class. If exceptions are
thrown within the synchronised method
the lock gets released. If it is a static class the
whole class is locked otherwise just the instance is locked.
- If you come across a syncronised block and your
thread already holds the lock on it it is allowed to continue.
- wait(), notify(), notifyAll() release the objects that the thread has
locked, re-acquiring them later.
The caller must be within a synchronised method or
statement or hold a lock on the object or an IllegalMonitorStateException
occurs.
- Interrupt does not function in the java.io
package but works in java.nio
- Mutexes (also known as monitors.. for example a
lock on an object) can only be released by the thread that owns the object
lock.
Whereas semaphores can be released by anything.
- Lock objects in the same sequence in all critical
sections ß avoids a deadlock.
- You do not need to maintain a reference to a
thread, once it is created JAVA holds
a reference to it through the applications
threadgroup. The thread is automatically
destroyed when the app closes or it completes
- run() in runnable has a void (not integer) return
type… a nasty certification question.
TYPES
- Short, byte cannot be promoted to char (an
unsigned 16bit value)
- Char needs to be initialised using ‘ ‘ not “ “
- String.intern() returns the string constant that
was created (in permGen memory) at compile time, or it to the list.
This memory now gets released when the string is
garbage collected.
- StringBuilder is an unsynchronised version of
stringBuffer. Use append rather than the + operator, and setLength(0) to
empty the builder for re-use.
SCOPE
- int x; ß instance scope (could be accessed with this.x)
myMethod(){
int
x = 1; ß method scope (masks instance scope)
while
(true){
int x = 1; ß local scope (masks method scope)
x--;
if(x == 0)
break;
}
}
- No declaration =
package scope… different from public, private or protected.
- public = can be
used anywhere
- protected allows
package access AND any subclass defined outside the
package.
In this case the only instance that a subclass can access is the superclass
that was created during its construction.
The
final keyword should be used to limit overriding behaviour.
- Obj.getpackage.isSealed(myURL) could be used to
semi-militarize a package, but this could still be spoofed by somome
mimicing your website.
- Only one class declaration in a file can be
public.
- Top level classes cannot be declared private.
- Inner classes have access to all instance
variables of the outer class.
- Packages can be sealed so all classes loaded must
be signed by the same entity, to prevent class insertion.
A signed jar file signs every file it contains. It can
be signed several times.
JAVABEANS
- Classes start with a capital. Fields and methods
don’t. Enums and static finals use all capitals.
- Throw TooManyListenersException if unicast event
(only one listener allowed)
- getP() ß used to get a property (P)
- isP() ß used to get a boolean property(P)
- setP() ß used to set a property
- getP(), getP(int), setP(int, object), setP(array)
ß used for indexed properties (e.g. arrays)
- add/removePropertyChangeListener(propertyChangeListener)
ß needed if any bound properties are used,
which is serviced when any property changes.
Java.beans.PropertyChangeSupport may be a helpful class.
- addPropertyChangeListener(String,
propertyChangeListener) ß named bound property, optional
- add/removePChangeListener(PChangeListener) ß optional listener for a specific property
- add/removeVetoableChangeListener() ß used for constrained properties. Must call
VetoableChange on all the listeners passing the new value.
If any throw a propertyVetoException the new value is
wrong.
- Events should extend java.util.EventObject and
are passed to listeners extending java.util.EventListener.
Throw TooManyListenersException if it is a unicast
event (only one listener allowed) and
too many listeners register.
- Using JavaBeans allows subclasses to over-ride
the getters and setters of their super
class to ensure all the data members in the class are
consistent.
INITIALIZATION
- Class fields get initialised to 0 or null.
- Method fields don’t and throw a compile error if
used.
- The contents of new array instances get
automatically initialised to 0 or null.
- Static fields can declared or initialised with
the method: static {
implementation }
CONSTRUCTORS
- Constructors have no return type and the same
name as the class.
- this(parameters) ß call another constructor. Must be the
constructor’s first statement.
- this.MyClass(parameters) ß Trying to call the constructor directly throws
an error.
- super(parameters) ß call superclass constructor. Must be the
constructor’s first statement.
- Classes not declared public have package scope
default constructors.
- If you specify a constructor, the compiler does
not create its own default public constructor.
You must declare it yourself if you ever wish to
inherit from the class.
- If you want a public class that is not to be
instantiated out of a package, define at least
one non-public constructor to ensure default
constructor is not created. Default public
constructors are a security risk.
- Defining a private constructor prevents a class
being instantiated (useful for utilities) except by an outer class or a
nested class.
Public
class Cl{ private Cl(){ … Cl
constructor code …}
… other Cl class
methods and fields ….
Public static Cl
getInstance(){ return ClSingletonHolder.instance;}
… other Cl class
methods and fields ….
Private
static class ClSingletonHolder{
Static
Cl instance = Cl();
}
// end of nested ClSingletonHolder class declaration
}// end of Cl
class declaration
FINAL
- Can be used to make a field or local variable
constant.
- Can be used in a methods parameter list to ensure
the method does not modify it.
- Can be used in for/in loops: for(final int x: myArray){ … }
- Can be used on parameters. This indicates the
method cannot change it (although it can change its internal state if it’s
a reference type).
It is NOT part of the methods signature so it could be
changed by an over-ridding subclass method.
- May be necessary so that a local inner class can
have access to it.
- Can be used on methods or classes to indicate
they cannot be overridden (improving performance)
- Private methods are implicitly final.
FINALLY
- See also the exceptions section.
- Called if a try block completes, returns or an
exception is thrown.
- Exceptions thrown in a finally clause cause any
exception not yet handled to be lost.
- Good place to close files, free resources and
locks
- If it contains a return, continue or break any
existing exception (or return value) is lost.
- If it calls a method that threw an exception
(which is not caught within the finally statement) then any existing
exception is lost.
FINALIZE
- Called when an object is garbage collected…this
may never happen, use finally if possible.
- Not automatically chained by java. Call a
superclasses finalize explicitly: super.finalize()
- Exceptions causes finalize to exit, but they are
not processed.
- Runtime.addShutdownHook can also be used to
delete files etc if the VM exits
**********************************************************************
**********************************************************************
**********************************************************************
ACTUALLY DOING STUFF
**********************************************************************
**********************************************************************
**********************************************************************
ANNOTATIONS
To use java doc put before the method
/**
* comment
*/
Javadoc
annotations
@depreciated
@author
name
@version
text
@param
parametername description
@return
description
@exception
fullclassname description
@throws
(as above)
@see
reference
@since
version
Compiler
annotations
@Override ß good to use to ensure the method signature is
correct.
@Depreciated ß used by compiler
ASSERTIONS
- assert(condition):message;
- On command line use –ea or –ea class or –ea
package to enable assertions.
ARRAYS
- int[][] mda = new int[10][0]
for(int
x = 0; i<10; i++){mda[i]= new int[10]:}
has
the same effect as:
int[][]
mda = new int[10][10];
- type x = new type[]{… initialiser values…} ß This is a valid syntax if array length is not
included.
COLLECTIONS
- Before 5.0 wrapper classes could not be used like
primitives (e.g. added with +). Primitives needed to be boxed before being
added to collections.
- Set not
allowed to contain duplicates
Class
|
Representation
|
Order
|
restrictions
|
operations
|
itteration
|
notes
|
HashSet
|
hashtable
|
none
|
none
|
O(1)
|
O(capacity)
|
Best general perpose
|
LinkedHashSet
|
Linked hashtable
|
Insertion order
|
none
|
O(1)
|
O(n)
|
Preserves insert order
|
EnumSet
|
Bit fields
|
Enum delaration
|
Enum values
|
O(1)
|
O(n)
|
Holds non-null enum values
only
|
TreeSet
|
Red-black tree
|
Sorted assending
|
comparable
|
O(log(n))
|
O(n)
|
Comparable elements or
comparator
|
CopyOnWriteArraySet
|
array
|
Insertion order
|
none
|
O(n)
|
O(n)
|
Thread safe
without synchronised methods
|
- List lists
allow duplicates
Class
|
Representation
|
Random Access
|
Notes
|
ArrayList
|
array
|
yes
|
Best allrounder
|
LinkedList
|
Double-linkedlist
|
no
|
Efficient insert and delete
|
CopyOnWriteArrayList
|
array
|
yes
|
Threadsafe, fast traversal
slow modification
|
Vector
|
array
|
yes
|
Legacy class, synchronised
methods
|
Stack
|
array
|
yes
|
Vector with push, pop, peek
|
- Map contain
two related values
Class
|
Representation
|
Since
|
Null keys
|
Null values
|
Notes
|
HashMap
|
hashtable
|
1.2
|
yes
|
yes
|
General purpose
|
ConcurrentHashMap
|
hashtable
|
5.0
|
no
|
no
|
Threadsafe see ConcurrentMap
|
EnumMap
|
array
|
5.0
|
no
|
yes
|
Keys are enum instances
|
LinkedHashMap
|
Hashtable plus list
|
1.4
|
yes
|
yes
|
Preserves insertion order
|
TreeMap
|
Red-black tree
|
1.2
|
no
|
yes
|
Sorted key values,
operations are O(log(n)) see SortedMap
|
identityHashMap
|
hashtable
|
1.4
|
yes
|
yes
|
Compares with == not .equals
|
WeakHashMap
|
hashtable
|
1.2
|
yes
|
yes
|
Doesn’t prevent garbage collection
of keys
|
HashTable
|
hashtable
|
1.0
|
no
|
no
|
Legacy class, synchronised
methods
|
Properties
|
hashtable
|
1.0
|
no
|
no
|
Extends hashTable with
string methods
|
OUTPUT
- Avoid using \n in outputs (or / in URLs) as these
may be platform specific. Use println.
- System.out.println(“string %s”, myString);
%.2f
ß rounds to 100ths
%d ß double (don’t use %g)
- String.substring(start,finish) returns characters
up to (finish-1)
ENUM
- private enum MyEnumClass{FRED, BILL, TED};
- if ( shot
== MyEnumClass.TED)System.out.println(“teds dead”);
GENERICS
- Arraylist<? extends Number> ß uses an upper bound, indicating it must extend
number Arraylist<? extends Number & Serializable> ß two upper bounds
You could put object but this would limit you to
calling only Object methods.
Arraylist<?
super Number> ß lower bound, it must be a superclass of Number (less used)
- Defining a class that takes generics:
Class
MyStack<E>{
Private E[] stuff = new E[10];
//allocate storage for ten generic values
}
- Compiler will try to use a non-generic if it is
available.
- You cannot cast an instance using a generic to a
type that uses a wider generic:
ArrayList<Integer>
a = new ArrayList<Integer>();
ArrayList<Object>
b = a; ß error b uses a wider type than a.
ArrayList
c = a; ß allowed for backward compatibility (avoid using)
- Consider using CheckedMap and CheckedList with
legacy code.
- You cannot create parameterised types eg … = new
ArrayList<Integer>[10];
but you can pass arrays created elsewhere into a
method or class that uses parameterised types.
- You cannot make subclasses of Throwable generic.
But the following is allowed:
public interface Command<X extends
Exception>{public void doIt(args) throws X;}
JUNIT
- JUnit tests extend TestCase and have
assertEquals(…)
assertFalse(…)
assertTrue(…)
assertNull(…)
assertNotNull(…)
assertSame(…) ß tests references
assertNotSame(…)
fail() ß used to explicitly fail a test
- Setup() and tearDown methods are called before
and after each call on a TestCase
- TestSuite allows you to compose a sequence of
TestCases
RANDOM
- new java.util.Random().nextInt();
- new java.util.Random().nextInt(6); ß numbers 0 to 5
SERIALIZABLE
- A tag interface indicating ObjectInputStream and
ObjectOutputStream can serialize it.
- Any instance variable that is not an array or
simple type must be declared serializable or transient for serialization
to work.
- Run the serialver app to get a serialversion ID
of your class. This can be pasted into derived classes to ensure
InvalidClassException
is not thrown if you load a derived class.
- Create your own serialization using the
Externalizable interface
- Alternatively add the following functions
180 private void
writeObject(ObjectOutputStream out) throws IOException
190 {
200
out.defaultWriteObject();
220 }
230 private void
readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
240 {
250
// our "pseudo-constructor"
260
in.defaultReadObject();
270
// now we are a "live" object again, so let's
run rebuild and start
280
startAnimation();
290
300 }
QUEUES
- ArrayBlockingQueue LinkedBlockinQueue DelayQueue
SynchronousQueue
VARARGS
▼ …elipsis indicates many parameters – must be
last one!
Average( double … nums)
{ for(double d: nums) sum +=
d;
}
Nums is automatically
converted into an array.
- If you wish to pass in an array of Objects (say
to printf) in the call put:
(object)MyArray ß this causes the compiler
to recognise the single array object as one parameter.
- public void main(String args[]) ß special case used for command line version
PARSING
- int I = Integer.parseInt(“42”);
- I = Scanner.nextInt(InputString); ß throws InputMissmatchException
**********************************************************************
**********************************************************************
**********************************************************************
SWING
**********************************************************************
**********************************************************************
**********************************************************************
- Swing is not threadsafe. Use
SwingUtilities.invokeLater(runnable) to ensure all GUI
update runables execute in the right order using the
event dispatch thread.
- There is no guarantee of the order listeners are
notified.
JButton
- JButton.setToolTipText(String);
- JButton(name, new ImageIcon(filename));
- JButton.addActionListener(listener) ß implements actionPerformed(ActionEvent ae);
Use ae.getSource() or JButton.setActionCommand(string)
read by ae.getActionCommand()
- JButton.revalidate() ß efficiently causes whole enclosing frame to
re-layout and repaint
JComponent
- Override paintComponent(Graphics g) ß final instruction should be a call to
super.paintComponent() so that it causes child windows (if any) to repaint
themselves.
- The graphics object sent to paint() or
paintComponent() can be safely cast to Graphics2D.
JCheckBox
JCheckBox.getSelected();
JComboBox
- Uses ComboBoxModel or DefaultComboBoxModel
JFRAME basics
- MyFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyFrame.setSize(300,200);
MyFrame.setLayout(new FlowLayout()); ß GridLayout, BorderLayout, BoxLayout
MyFrame.add(m);
MyFrame.Pack(); ß sets JFrame just large enough to contain its
components
MyFrame.setVisible(true);
- Calling LayoutContainer(getContentPane()); causes
the content pane to be re-layed out and repainted, alternatively call
validate() on the container.
JLabel
- JLabel.setBorder(BorderFactory.createEtchedBoarder());
JList
- (String) list.getModel().getElementAt(s[0])
JMenuBar
- JMenuBar add JMenu add JMenuItem(myAction) ß class that extends AbstractAction overridding
actionPerformed.
- Create an instance of myAction using
MyAction(name, imageIcon). You can then call .setEnabled(false) on it to
disable it.
JRadioButton
ButtonGroup.add(button) ßAdds to a button group.
ButtonGroup.setSelected(button,true) ß selects a button
ButtonGroup.isSelected(button) ß tests a button
JOptionPane
- JOptionPane.showInputDialog() ß various constructors determine return type
JOptionPane.showConfirmDialog()
JOptionPane.showMessageDialog()
JOptionPane.OptionDialog()
- JOptionPane.showMessageDialog(message,
mesagetype, optiontype)
Message
types
ERROR_MESSAGE
INFORMATION_MESSAGE
PLAIN_MESSAGE
QUESTION_MESSAGE
Option
Types
DEFAULT_OPTION
OK_CANCEL_OPTION
YES_NO_CANCEL_OPTION
YES_NO_OPTION
Returned
values
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
JScrollPane
- JScrollPane(object) ß place object in scrollpane, then place the
scrollpane in applet etc
JSlider
setMaximum
setValue
addChangeListener
ß implements
adjustmentValueChanged()
setMinorTickSpacing
setMajorTickSpacing
setPaintTicks
setPaintLabels
setLableTable(Slider.CreateStandardLabels(10));
JToolBar
- Add JButtons created using JButton(myAction) ß calling setEnabled on myAction
means the MenuItem and JButton on the toolbar enabled
states are then linked.
UImanager
- UIManager.getInstalledLookAndFeels(name of
implementing class)
UIManager.setLookAndFeel();
SwingUtilities.updateComponentTreeUI(this)
- Javax.swing.platform.metal.MetalLookAndFeel
Javax.swing.platform.motif.MotifLookAndFeel
Javax.swing.platform.windows.WindowsLookAndFeel
Com.apple.mrj.swing.MacLookAndFeel