My Last Minute Notes
The following is the note what I made when preparing for SCJP. If you understand it well, I am sure you will pass the exam.
Basic
super() and this() allow constructor chained within classes. Either super() or this() will be called first within the constructor to do some init stuff.
Method overloading is to refer the method defined has the same name
as other methods, but different parameter list and return type. The method will
be decided at compile time.
Method overriding is to refer the method defined has the same signature
(name + parameter list) and return type as the method in the super class. It
will be decided at run time.
The argument to the if() must evaluate to a boolean (unlike C/C++). The argument to switch() may evaluate to any one of the following: byte, char, short, int.
Define classes, including member variables and member methods. Declare classes using modifiers public, abstract, or final. Declare variables using the private, protected, public, static, final, native, or abstract modifiers to those members.
Threads 1. Thread Creation
There are two ways to implement threads:
a. Implementing Runnable Interface.
b. Extending the Thread Class.
e.g.:
class MyThread implements Runnable {
public void run() {//the only method defined in the Interface //do something
}} public class Test { public static void main(String arg[]) { MyThread myTh = new MyThread(); Thread aTh = new Thread(myTh); //or new Thread(myTh, "threadName") aTh.start(); //start a new thread }}
or:
class MyThread extends Thread {
public void run() {//Thread class defines this already, don't have to do //do something
}} public class Test { public static void main(String arg[]) { MyThread myTh = new MyThread(); myTh.start(); }}
Synchronization
There are two ways to synchronize code:
a. Synchronized methods
b. Synchronized blocks //synchronized(<object ref.>) {<code block>}
2. Blocked
yield() is a static method of the Thread class, which causes the
currently executing thread to yield.
sleep(milliseconds) throws InterruptedException is a static
method of the Thread class, which needs try(), catch() to compile.
The difference is yield() yields only to other threads of the SAME PRIORITY
and DOES NOT RELEASE the lock. sleep() also DOES NOT RELEASE THE LOCK
but it allows other low-priority ones also to get a chance. But wait()
/wait(..) RELEASES ITS LOCK naively and depends on others to get its lock back
in order to go to ready state.
(public void interrupt() Interrupts this thread)
e.g. Thread.yield(); Thread.sleep(1000);
Monitor, wait(), and notify()
They are implemented in the Object class, not in Thread. When any version
of this wait method is invoked on an object it MUST be enclosed in a try ..catch..InterruptedException
block because at any time it may be interrupted by another thread by calling
interrupt on this thread or by calling notify() / notifyAll() . They may only
be called in synchronized code. A call to wait from within synchronized
code causes the thread to give up its lock and go to sleep. This normally happens
to allow another thread to obtain the lock and continue some processing. If
no synchronized or no monitor, IllegalMonitorStateException
will be thrown. Obtaining lock is done througn the synchronized keyword. Otherwise
no compile error will occur. But at run time IllegalMOnitorStateException will
occur.
A monitor is an instance of any class that has synchronized code.
A typical example of using the wait/notify protocol to allow communication
between Threads appears to involve apparently endless loops such as
//producing code
As true is notorious for staying true this, code looks at first glance
like it will just loop forever. The wait method however effectively means give
up the lock on the object and wait until the notify or notifyAll
method tells you to wake up.
while(true){
try{
wait();
}catch (InterruptedException e) {}
}
//some producing action goes here
notifyAll();
A thread group represents a set of threads. In addition, a thread group can also include other thread groups. A thread can only access its own thread group.
Daemon threads (belongs to the system) run in the background and do not prevent a program from terminating. For example, the garbage collector is a daemon thread. A program can include a mixture of daemon and non-daemon threads. The Java virtual machine will exit when only daemon threads remain in a program. http://www.javaranch.com/maha/Discussions/Threads/threads.html
paint(), update(), and repaint() The best way to do all draqing oerations is inside paint(). A graphics context
is passed to paint() to have its clip region set, the default clip region is
the entire component. There are four classes of blank components that you need
to provide your own paint() methods make them visible, Applet, Canvas, Frame,
Panel.
e.g.
public void paint(Graphics g) {
g.setColor(new Color(188, 188, 188);//or g.setColor(Color.cyan);
//the pre-defined colors are static variables (lowerCase, not const) and type
is Color.
g.setFont(new Font("FontName", Font.BOLD, 12);
...}
The update() clears the component to its background color and then calls paint().
The repaint() (no parameter) calls update() every 100 milliseconds (most
platforms) and clears the request flag. So that, the virtual machine never gets
overwhelmed by events. If you don't need any components to be cleared, you can
always override update().
e.g.
public void update(Graphics g) {
paint(g);
}
Inner Classes
1. The top-level nested classe or interface - it is defined as a static member
of an enclosing top-level class or interface. A method in the class can only
directly access static members in the enclosing class or interface, but
not instance members in the enclosing context. A static method cannot access
directly other non-static variables in its own class.
e.g.
class TopLevelClass { static class NestedTopLevelClass { private static int iStatic; private int jNonStatic; }2. The non-static inner class can only exist with an instance of its enclosing class. It can not have static members.
static class NestedNestedClass { private int k;
public void nonStaticMethod() { int jj=jNonStatic; //wrong int ii=iStatic; int kk=k; } public static void staticMethod() { int kk=k; //wrong } } public class client { TopLevelClass.NestedTopLevelClass aNestedObj =
new TopLevelClass.NestedTopLevelClass(); }
class TopLevelClass { static class NestedTopLevelClass { private static int iStatic; private int jNonStatic; }
public class NestedNestedClass { private int k; private static int iii; //wrong
public void nonStaticMethod() { int jj=jNonStatic; //wrong int ii=NestedTopLevelClass.this.iStatic; int kk=k; } } public class client { TopLevelClass.NestedTopLevelClass aNestedObj =
new TopLevelClass().new NestedTopLevelClass(); } // <enclosing object ref>.new
3. Local Classes
A local class is defined in a block, i.e. {}. It is only visible within the
context of the block. It can not be specified with the keyword static.
If it is within a static method, it is implicitly static. Local classes can
not have any accessibility, just like local variables.
Access Rules
A local class can access final local variables in the scope of the local
context, i.e. enclosing method.
A non-static local class can access members defined in the enclosing class.
A static local class can only directly access static members defined
in the enclosing class.
4. Anonymous Classes
The keyword static is not used explicitly. The context determinds
it.
An anonymous class that extends an existing class specified by: new <superclass
name> (<optional argument list>) {<class declarations>}.
When instantiating an anonymous class that implements an interface specified,
the syntax is:
new <interface name> () {<class declarations>}.
An anonymous class cannot have any constructors.
Access rules for anonymous classes are the same as for local classes.
Keywords
Classes can be modified from their default state using any of the three keywords: public, abstract, and final. So, can’t have a static class, only static methods.
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. Java letters include _ and $. Digits include 0..9.
The elements of an array are always (even inside a method) initialised to their default values when no explicit assignment has been made to the element.
ConstructorsThe JVM does not call an object’s constructor when an object is cloned.
Constructors never return a value. If you do specify a return value, the JVM will interpret your intended constructor as a method (tricky).
If a class contains no constructor declarations, then a default constructor
that takes no arguments is supplied. This default constructor invokes the no-args
superclass constructor, i.e. calls super(); If, in a constructor, you
do not make a direct call to super or this (with or without args)
[note: must be on the first line] then super(no args) will first be invoked
then any code in the constructor will be executed. A call to this in
a constructor must also be on the first line.
The garbage collector runs in low memory situations. As soon as you lose the reference to an object, that object becomes eligible for garbage collection. Setting your object reference to null makes it a candidate for garbage collection.
You can directly invoke the garbage collector by getting an object which represents the current runtime and invoking that object’s gc() method. You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen
If you want to perform some task when your object is about to be garbage collected, you can override the java.lang.Object method called finalize(). This method is declared as protected, does not return a value, and throws a Throwable object, i.e. protected void finalize() throws Throwable.
Always invoke the superclass’s finalize() method if you override finalize(). The JVM only invokes finalize() once per object. Since this is the case, do not resurrect an object in finalize as when the object is finalized again its finalize() method will not be called. Instead you should create a clone of the object if you must bring the object back to life.
OperatorsThe equals() method (defined at the ‘highest’ level as a method of Object) is used to test the value of an object. The == operator is used to test the object references themselves. By default, equals() returns true only if the objects reside in the same memory location, i.e. if the object references are equal. So, by default, equals() and == do the same things. This will be the case for all classes that do not override equals(). String, Wrappers (including Integer, Long, Float, Double, Character and Boolean), BitSet, Date and File classes all override equals() so that the value true is returned if the values are equal.
Math Class1. Random returns value between 0.0 and 1.0 (more than and equal to 0.0 and
less than 1).
2. Round chops off the part after the point but leaves the sign and return int
or long.
<type1> abs (<type1> i);
double {ceil, floor} (double d);
<type1> {max, min}(<type1> i, <type1>j);
double random();
int round(float f); // round(-8.5) = -8 not -9
long round(double d);
double {sin, cos, tan, sqrt}(double d);
All members (attributes & methods) of interface are implicitly public.
All attributes defined in interface are implicitly static and final.
All methods defined in interface are NOT static.
1. Wrapper classes are final.
2. Override equals(Object) method. Not (==).
3. <wrapper class>.valueOf(String) //to wrapper class
4. <wrapper obj>.primitiveTypeValue(); //to primitive class
IndexOf/lastIndexOf()
String a = "pay"; String b="lay"; a.concat("2"); // a="pay" a = a.replace('p', 'd'); // a="day"
substring()
String substring(int beginIndex); //Returns a substring starting
with startIndex and extending to the end of the String
String substring(int beginIndex, int endIndex); //Returns a substring starting
with startIndex and extending to (but not including) endIndex
1. Invoking a method which declares it throws exceptions is not possible unless
either the code is placed in a try-catch, or the calling method declares
that it throws the exceptions, i.e. checked exceptions must be caught
or rethrown. If the try-catch approach is used, then the try-catch must cope
with all of the exceptions which a method declares it throws.
2. Code in a finally block will always be executed, whether an exception is
thrown or not and whether any exception thrown is caught or not. Only terminating
the program will stop the finally code from being executed.
3. A method can only throw those exceptions listed in its throws clause (declared), or subclasses of those exceptions. A method can throw any unchecked exception, even if it is not declared in its throws clause.
4. When you override a method, you must list those exceptions that the override code might throw. You can list only those exceptions, or subclasses of those exceptions, that are defined in the method definition you are inheriting from, i.e. you cannot add new exception types to those you inherit. You can choose to throw a subset of those exceptions listed in the method’s superclass, however, a subclass further down the hierarchy cannot then re-list the exceptions dropped above it.
MethodWhich variable is accessed depends on the type of object reference which the variable was declared to hold. Which method gets invoked depends on the underlying object.
A native method does not have a body, or even a set of braces, e.g. public native void method();
CollectionCollection - A basic interface
Set - interface that maintain unique elements. e.g. HashSet
SortedSet - TreeSet
List - the elements are in order. e.g. Vector, LinkedList, ArrayList
Map - A basic interface. e.g. HashMap, HashTable
SortedMap - mappings in key order. e.g. TreeMap
Vector provides thread-safe operations, but ArrayList doesn't.
HashMap class (has null) is not thread-safe, the HashTable (non null) class
is.
java.io
File(String path); File(String path, String name); File (File dir, String name);
boolean exists()/boolean car{Read,Write}()/boolean isDirectory()/boolean
isFile()
boolean createNewFile()/boolean delete()/boolean mkdir()/String[]
list()
The file class offers delete() to delete a file or directory, mkdir()
and mkdirs() to create directories. To determine if a file exists invoke
exists(). A new file object can be created by invoking createNewFile().
The File class contains the list() which returns a string array containing
all of the files in a directory. This is very handy for checking to see if a
file is available before attempting to open it.
When creating a subclass of InputStream, public int read() throws IOException
must be overridden.
If a RandomAccessFile is opened for read on a file that does not exist, the
FileNotFoundException is thrown. seek() and read/writeData()
The FileInputStream and FileOutputStream take some kind of File as a constructor because they are low level classes. This can be a String containing the file name, and instance of the File class or a File descriptor. FileInputStream(String pathname); FileInputStream(File file). Other low level classes are Input/OutputStream (network sockets), ByteArrayInput/OutputStream, and PipedInput/OutputStream (synchronized communication).
The high level classes extend the superclasses FilterInput/OutputStream. They deal with streams. DataInputStream, DataOutputStream and RandomAccessFile know how to work with Java data types because they implement the DataInput and DataOutput interfaces, whereas FileInputStream and FileOutputStream know only how to work with individual bytes, and FileReader and FileWriter to char.
The low level readers are FileReader/Writer. They have the same constructor as low level stream classes.
InputStreamReader(InputStream in[, String encoding]); //convert between
streams of bytes and Unicode char.
new OutputStreamWriter(new FileOutputStream("out.txt"), "8859_7");
When can use try/catch. the relationship with inputstream?
AWT The layout managers are: Flow Layout, or FlowLayout, or Flow, etc.
Container includes Panel, Window (Frame, Dialog), and ScrollPane.
Menu Components
java.lang.Object -> MenuComponent -> {MenuBar, MenuItem}
MenuItem -> {Menu, CheckboxMenuItem}
One GridBagConstraints can be used for all components in a frame.
EventsAll event handlers have void return type.
Event classes
java.util.EventObject -> java.awt.AWTEvent -> ActionEvent, AdjustmentEvent,
ComponentEvent, ItemEvent, and TextEvent.
ComponentEvent -> ContainerEvent, FocusEvent, InputEvent{KeyEvent, MouseEvent},
PaintEvent, WindowEvent.
Object getSource() //returns the object that originated the event
int getID() //returns the ID of the event
Event handle methods
a. to delegate event handling to a listener object.
b. to explicitly enable the originating component to handle its own events.
Event listeners
A listener is an object to which a component has delegated the task of handling
a particular kind of event. It must implement the interface that contains the
event-handling method.
e.g.
class MyListener implements xxxListener { public void xxxMethod(xxxEvent ae) { } } ... MyListener mylistener = new MyListener(); theComponent.addxxxListener(mylistener); //theComponent.removexxxListener(mylistener); ...
ActionListener/addActionListener()/actionPerformed(ActionEvent) //activate
a component
AdjustmentListener/addAdjustmentListener()/adjustmentValueChanged(AdjustmentEvent)
//scroll bar
ItemListener/TextListener/
ComponentListener/addComponentListener()/componentHidden/Moved/..(ComponentEvent)
ContainerListener/addContainerListener()/componentAdded/Removed(ContainerEvent)
FocusListener/KeyListener/MouseMotionListener/WindowListener
Explicit event enabling
a. Create a subclass of the component and override the method that receives
events and dispatches them to listeners.
class MyBtn extends Button { public MyBtn(String label) { super(label); enableEvents(AWTEvent.XXX_EVENT_MASK); //receive an event } public void processxxxEvent(xxxEvent ae) { //dispatch event super.processxxxEvent(ae) } //must call because the superclass version for calling xxxPerformed() in listener } or making the subclass an event listener class MyBtn extends Button implements xxxListener { public MyBtn(String label) { super(label); addxxxListener(this); //automatically call enableEvents() } public void xxxMethod (xxxEvent ae) { //Handle the event here. } }
Adapters
An adapter is simply a class that implements an interface by providing do-nothing
methods. When you use the adapter, you do not need to write all no-use methods
defined in xxxListener interface. Adapter classes are: ComponentAdapter/ContainerAdapter/FocusAdapter/KeyAdapter/MouseAdapter/MouseMotionAdapter/WindowAdapter
When the user clicks a button, doubleclicks a list item, chooses a menu item, or presses return in a text field, an action event occurs. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.
The only AWT class that implements Adjustable is Scrollbar.
AWT components that generate item events are checkboxes, checkbox menu items, choices, and lists.
Text events are generated after the text in a text component has changed somehow. The 1.1 AWT components that generate text events are text fields and text areas.
Window events are generated by a Window just after the window is opened, closed, iconified, deiconified, activated, or deactivated.
The component hidden and component visible events occur only as the result of calls to a Component's setVisible method (or its deprecated equivalents, show and hide). For example, a window might be miniaturized into an icon (iconified), without a component hidden event being generated.
Container events are generated by a Container just after a component is added to or removed from the container. These events are for notification only -- no container listener need be present for components to be successfully added or removed.
Key events tell you when the user types at the keyboard. Specifically, key events are generated by the component with the keyboard focus when the user presses or releases keyboard keys.
Mouse events tell you when the user uses the mouse (or similar input device) to interact with a component. Mouse events occur when the cursor enters or exits a component's on-screen area and when the user presses or releases the mouse button.
Mouse motion events tell you when the user uses the mouse (or a similar input device) to move the onscreen cursor.
Focus events are generated whenever a component gains or loses the keyboard focus -- the ability to receive keyboard events. You can request that a component get the focus by invoking the Component requestFocus method.
GridBagLayoutThe ipadX represents the internal padding of the component and affects the size of the component.
Setting the weightY may affect the component's cell height and the component's height.
Setting the insets of a component affect the component's cell and not the component's size.
Changing the width of a cell changes the width of all of the cells in that particular column.