JAVA QUIRKS v1

 

 

this also works with if statements (including labelled break)

 

 

 

 

(but not recommended as compilers use them too.

 

eg:  (n != 0) && (100/n ==2) ß no div0 error can occur

 

parameter evaluation runs on all parameters before precedence evaluation starts:

E.g: compare((a++),(a-1))

 

only evaluated once. This is significant if the evaluation has side effects.

 

(often for tests). JAR files contain a manifest which indicates which class to run.

 

(but not recommended as compilers use them too)

 

of that class.

 

 

 

 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

 

((MySuperclass)this).myMethod() which will call the subclass due to polymorphism.

 

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.

 

 

 

ABSTRACT


 

EXCEPTIONS

 

 

 

details of the original cause in the stack trace.

 

 

 

INTERFACES

 

 

 

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.

 

 

Failure to methods with the correct return will throw a ‘does not implement’ compile error.

 

MATHS

 

 

 

Divide by 0 errors never occur!

For example 1/negzero = -infinity

 

 

 

 

 

 

 

 

 

NESTED TYPES

 

its static members (including private ones). It is part of the containing class’s namespace.

 

 

 

 

 

This also applies to both local classes and anonymous classes.

 

 

 

 

class, that is hidden by a member within the/an inner class.

 

 a containing class outer class, that is hidden by a member within the/an inner class.

 

 

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()

}

 


 

it is used immediately where or after it is defined, the class name is not needed to help understanding.

 

{ … initialisation code …}

 

 

getMoose(){

                return new Animal(4){

                                … definition…

                                String getDiet(){return new String(“grass”)}

                                }

}

 

OBJECTS

 

 

 

otherwise collections such as  hashmap etc will not function correctly.

 

 

 

@Override

Public Object clone(){try{return super.clone();}catch(CloneNotSupportedException e){throw new AssertionError(e);}

 

STATIC

 

 


THREADING

execute in the right order using the event dispatch thread.

 

 

 

 

 

 

inconsistency or deadlock  if more than one volatile is used. Volatile is handled incorrectly on some virtual machines.

 

 

 

 

 

Calling await releases the lock on the object. await also accepts a timeout.

 

the lock gets released. If it is a static class the whole class is locked otherwise just the instance is locked.

 

 

The caller must be within a synchronised method or statement or hold a lock on the object or an IllegalMonitorStateException occurs.

 

 

Whereas semaphores can be released by anything.

 

 

a reference to it through the applications threadgroup. The thread is automatically

destroyed when the app closes or it completes

 

 


TYPES

 

 

This memory now gets released when the string is garbage collected.

 

 

SCOPE

myMethod(){

int x = 1; ß method scope (masks instance scope)

while (true){

                                int x = 1; ß local scope (masks method scope)

                                x--;

                                if(x == 0) break;

}

}

 

 

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.

 

 

 

 

 

A signed jar file signs every file it contains. It can be signed several times.

 

JAVABEANS

 

 

 

 

 

 

which is serviced when any property changes. Java.beans.PropertyChangeSupport may be a helpful class.

 

 

 

If any throw a propertyVetoException the new value is wrong.

 

Throw TooManyListenersException if it is a unicast event  (only one listener allowed) and too many listeners register.

 

class to ensure all the data members in the class are consistent.

 

INITIALIZATION

 

 

 

 

CONSTRUCTORS

 

 

 

 

 

You must declare it yourself if you ever wish to inherit from the class.

 

one non-public constructor to ensure default constructor is not created. Default public

constructors are a security risk.

 

 

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

 

 

 

It is NOT part of the methods signature so it could be changed by an over-ridding subclass method.

 

 

 

 

FINALLY

 

 

 

 

 

 

FINALIZE

 

 

 


**********************************************************************

**********************************************************************

**********************************************************************

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

 

 

ARRAYS

for(int x = 0; i<10; i++){mda[i]= new int[10]:}

has the same effect as:

int[][] mda = new int[10][10];

 


COLLECTIONS

 

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

 

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

 

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

 

%.2f                        ß rounds to 100ths

%d                          ß double (don’t use %g)

 

 

ENUM

 

 


GENERICS

                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)

 

Class MyStack<E>{

                Private E[] stuff = new E[10]; //allocate storage for ten generic values

}

 

 

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)

 

 

but you can pass arrays created elsewhere into a method or class that uses parameterised types.

 

public interface Command<X extends Exception>{public void doIt(args) throws X;}

 

JUNIT

assertEquals(…)

assertFalse(…)

assertTrue(…)

assertNull(…)

assertNotNull(…)

assertSame(…)                     ß tests references

assertNotSame(…)

fail()                                        ß used to explicitly fail a test

 

 

 

RANDOM

 

 

SERIALIZABLE

 

 

is not thrown if you load a derived class.

 

 

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

 

 

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.

 

to recognise the single array object as one parameter.

 

 

PARSING

 

 

 

 

**********************************************************************

**********************************************************************

**********************************************************************

                                                 SWING

**********************************************************************

**********************************************************************

**********************************************************************

 

update runables execute in the right order using the event dispatch thread.

 

 

JButton

 

 

Use ae.getSource() or JButton.setActionCommand(string) read by ae.getActionCommand()

 

 

 

JComponent

 

 

JCheckBox

JCheckBox.getSelected();

 


JComboBox

 

JFRAME basics

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);

 

 

JLabel

 

JList

 

 

 

JMenuBar

 

 

JRadioButton

ButtonGroup.add(button)                                  ßAdds to a button group.

ButtonGroup.setSelected(button,true)             ß selects a button

ButtonGroup.isSelected(button)                       ß tests a button

 

JOptionPane

JOptionPane.showConfirmDialog()

JOptionPane.showMessageDialog()

JOptionPane.OptionDialog()

 

 

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

 

JSlider

setMaximum

setValue

addChangeListener ß implements adjustmentValueChanged()

setMinorTickSpacing

setMajorTickSpacing

setPaintTicks

setPaintLabels

setLableTable(Slider.CreateStandardLabels(10));

 

JToolBar

means the MenuItem and JButton on the toolbar enabled states are then linked.

 

UImanager

UIManager.setLookAndFeel();

SwingUtilities.updateComponentTreeUI(this)

 

Javax.swing.platform.motif.MotifLookAndFeel

Javax.swing.platform.windows.WindowsLookAndFeel

        Com.apple.mrj.swing.MacLookAndFeel