Sun Certified Java Programmer (Java 2)
Basic Object Oriented Concept
Object
An instance of a class
Has state and behavior
State is contained in its member variables
Behavior is implemented through its methods.
Message
For objects to interact with one another
Result of a message is a method invocation which performs actions or modifies the state of the receiving object
Classes
An object`s class is the object`s type
The ability to derive one class from another and inherit its state and behavior
Most general classes appear higher in the class hierarchy
Most specific classes appear lower in the class hierarchy
Subclasses inherit state and behavior from their superclasses
Interface
A collection of method definitions without actual implementations
For defining a protocol of behavior that can be implemented by any class anywhere in the class hierarchy.
Packages
A collection of related classes and interfaces
java.lang is imported by default automatically
Java Language Fundamentals
The order for every "heading" is as follows:
package declarations -- package my.applications.uinterfaces;
import statements -- import java.awt.*
class definitions -- public class myClass { .....
Order of public vs. non-public class definitions doesn`t matter.
Allows only one top-level public class per source file
Name of source file must be the same as name of the public class
main() method must be:
public
static
Not return a value (void return type)
Take an array of strings:(String[] args) or (String args[]) doesn`t matter
`args` is just a common name, you can use any name you like. However, there must be a set of "[]"
Legal examples:
public static void main(String[] args)
static public void main(String args[])
Command line arguments are placed in the String array starting at 0 after the java command and the program name
For non-applet java application, there must be a main method
For applet, you do not use main()
Applet:
a subclass of Panel, which itself is a subclass of Container
init() - called when applet is first instantiated.
start() - called when the web page containing the applet is to be displayed
stop() - called when the web browser is about to show another web page and quit the current one
HTML required to display an applet in a web page:
<APPLET CODE=MyProgram.class WIDTH=200 HEIGHT=400>
</APPLET>
PARAM tag allows you to pass a value to an applet:
<PARAM NAME=message VALUE="Hi, My Java!">
To use these values in your applet, use the getParameter(String paramname ) method to return the value as a string:
greeting=getParameter("message");
Java Identifier
Consists of letters and digits
Must begin with a letter , "$" or "_"
Unlimited length
Cannot be the same as a reserved keyword
Java Reserved Word
Reserved Keywords cover categories such as primitive types, flow control statements, access modifiers, class, method, and variable declarations, special constants, and unused words
abstract - boolean - break - byte - case - catch - char - class - const - continue - default - do - double - else - extends - final - finally - float - for - goto - if - implements - import - instanceof - int - interface - long - native - new - null - package - private - protected - public - return - short - static - super - switch - synchronized - this - throw - throws - transient - try - void - volatile - while
True, false and null are literals, not keywords
Primitives
Occupy pre-defined numbers of bits
Have standard implicit initial values
Type conversion
You cannot assign booleans to any other type.
You cannot assign a byte to a char.
You can assign a variable of type X to type Y only if Y contains a wider range of values than X.
Primitives in order of `width` are char/short, int, long, float, double.
For Objects, you can assign object X to object Y only if they are of the same class, or X is a subclass of Y, which is called "upcasting".
Promotion
In arithmetic operations, variable may be widened automatically for the purpose of evaluating the expression
The variables themselves would not be changed, but for its calculations Java uses a widened value.
Casting
Similar to forcing a type conversion - values can be casted between different primitive types
Done by placing the destination cast type keyword between parentheses before the source type expression
Some cast operations may result in loss of information
Variables derived from these primitive types that are declared in nested blocks could only be accessible within that block and its sub-blocks, and are destroyed when the block they belong to is stopped
Major primitive types:
Primitive Type
Size
Range of Values
Byte
8 bit
-27 to 27-1
Short
16 bit
-215 to 215-1
Int
32 bit, all are signed
-231 to 231-1
Long
64 bit
-263 to 2 63-1
Char
16 bit unicode
`\u0000` to `\uffff`
(0 to 216-1 )
Java unicode escape format: a "\u" followed by four hexadecimal digits. e.g.,
char x=`\u1234`
Other primitive types:
Long - can be denoted by a trailing "l" or "L"
Float - can be denoted by a trailing "f" or "F"
Double - can be denoted by a trailing "d" or "D"
Booleans - true or false only, cannot be cast to or from other types
Array - declared using the square brackets "[]". Example of legal declarations :
int[] x;
int x[];
int i[][]; declares a two dimensional array.
Can be created dynamically using the new keyword
Can be created statically using an explicit element list
Array element counts from 0. For example, int[10] actually has 10 elements, from 0 to 9, not from 1 to 10
Array can be constructed after declaration, or to have everything done on the single line
int[] i;
i = new int[10];
OR
int i[] = new int[10];
Array members can be initialized either through a FOR loop, or through direct assignment
int myarray[] = new int[10];
for(int j=0; j<myarray.length;j++){
myarray[j]=j;
}
OR
char mychar[]= new char[] {`a`,`e`,`i`,`o`,`u`};
Do not get confused with string. Strings are implemented using the String and StringBuffer classes.
Bitwise Operation
numerics can be manipulated at the bit level using the shift and bitwise operators
Java includes two separate shift-right operators for signed and unsigned operations, the ">>" and the ">>>"
>> performs a signed right-shift. If the first bit on the left is 1, then when it right-shifts the bits, it fills in a 1s on the left. If the leftmost bit is 0, then when it right-shifts the bits, it fills in a 0s on the left. The first bit represents the sign of a number to preserve the sign of the number.
>>> performs an unsigned right-shift. The left side is always filled with 0s.
<< performs a left-shift. The right side is always filled with 0s.
Java Operator
Operators that compare values
equal to, "=="
not equal to, "!="
greater than, ">"
less than, "<"
greater than or equal to, ">="
less than or equal to, "<="
Logical Operators
logical AND, "&"
logical OR, "|"
logical XOR, "^"
boolean NOT, "!"
short-circuit logical AND, "&&"
short-circuit logical OR, "||"
Operator precedence determines the order of evaluation when different operators are used, although precedence can be explicitly set with parentheses "()".
Multiple operators of the same precedence are evaluated from left to right
In logical boolean expressions, the right operand is only evaluated after the left hand operand has been evaluated first.
For short-circuit logical expression, if the left hand condition does not evaluate to true, the right hand condition will not be evaluated at all
For Objects, == determines whether the variables reference the same object in memory, rather than comparing their contents.
For example, when
String x = "Hey";
String y = "Hey";
Java creates only one String object, so the result of comparison is always true.
To avoid the above situation, use the NEW keyword so that string x and y can be of different objects.
In Booleans, equals() returns true if the two objects contain the same Boolean value.
In String, equals() returns true if the Strings contain the same sequence of characters.
Java Modifiers
private
Accessible only from inside the class
Cannot be inherited by subclasses
protected
Accessible only by classes in the same package or subclasses of this class
public
Can be accessed by anyone
static
Belongs to the class, not to any particular instance of the class
For variables, there is only one copy for all instances of the class. If an instance changes the value, the other instances see that changes
For methods, it can be called without having created an instance, and cannot be used the this keyword, nor be referred to instance variables and methods directly without creating an instance For inner classes, they can be instantiated without having an instance of the enclosing class
Methods of the inner class cannot refer to instance variables or methods of the enclosing class directly
final
Variable`s value cannot be changed
Methods cannot be overridden
Classes cannot be subclassed.
native
Method written in non java language
Outside the JVM in a library
Optimized for speed
abstract
Method which is not implemented with code body
synchronized
method makes non-atomic modifications to the class or instance
for static method, lock for the class is acquired before executing the method
for non-static method, a lock for the specific object instance is acquired
transient
field is not part of the object`s persistent state
should not be serialized
volatile
field may be accessed by unsynchronized threads
certain code optimizations must not be performed on it
none
class- non-public class is accessible only in its package
interface - non-public interface is accessible only in its package
member - member that is not private, protected, or public is accessible only within its package
Summary of Class Member Accessibility
Accessible to:
Visibility
public
protected
package
private
Same class
yes
yes
yes
yes
Different Class but same package
yes
yes
yes
no
Subclass in different package
yes
yes
no
no
Non-subclass in different package
yes
no
no
no
Flow Control
if/else
if (response == yes) {
. . .
// code to perform yes action
. . .
} else {
. . .
// code to perform Cancel action
. . .
}
- if can be used without braces
- Argument for if() must be a boolean or an expression which evaluates to a boolean
switch/case
switch (month)
case 1: System.out.println("January"); break;
System.out.println("February"); break;
System.out.println("March"); break;
default: System.out.println("Hi!");
break;
}
- After the correct case is executed, it will continue to execute all those after it unless you put in a break, return or throw statement
for
for (i = 0; i < length; i++) {
// do something . . .
}
- Uses pre-increment instead of post-increment. E.g. there is no difference between for(int i=0;i<5;++myvar) and for(int i=0;i<5;myvar++)
while/ Do while
do {
statements
while (booleanExpression);
break/continue
- Break causes the current loop to be abandoned, while continue causes execution to skip the rest of the code in the current iteration and start at the top of the loop with the next iteration
- Affects only the execution of loop that they are in
- Labeled versions of break/continue allow you to jump to/break out of wherever the label is
- Java does not support GOTO
return
- Use return to exit from the current method and jump back to the statement of the calling method
- To have return really return a value, put the value (or an expression that calculates the value) after the return keyword; e.g., return ++myvar;
- The value returned must match the type of method`s declared return value
- If the method is declared void, use the form of return that doesn`t return a value - simply a return with nothing but semi colon after it.
Confusions among classes, overloaded and overridden methods
To determine at run time if an object is an instance of a specified class or some subclass of that class, we can use the instanceof operator.
SomeObject instanceof SomeClass evaluates as true if SomeObject is an instance of SomeClass, or is an instance of a subclass of Someclass.
SomeObject instanceof SomeInterface evaluates as true if SomeObject is an instance of a class which implements SomeInterface.
To identify a method in Java, we look at the name of the method and the arguments it takes. Sometimes we refer this to a method`s signature.
If the arguments are different but the method names are the same, you are dealing with an overloaded method.
If the arguments and the method names are the same, you are dealing with an overridden method, that the method of the superclass has been replaced by that of the subclass.
You cannot define two methods within the same class with the same name and the same arguments.
The return type is not part of a methods signature. Overloaded methods are completely different methods that can return completely different types.
The overriding method must return the same type as the method in the superclass.
If the object is an instance of the derived class, then the overridden version defined in the derived class will be used instead of the one defined in the parent superclass.
Here is how you define a CAT subclass from the superclass ANIMAL using the extends keyword: class CAT extends Animal { ?..
super.someMethod() will call the version of someMethod() in the immediate super class. An attempt to use the superclass`s superclass`s method using by using super.super.someMethod() is not allowed
To use this() and/or super() to access overloaded or parent-class constructors, you must place them at the very beginning of the code block in the constructor, and that you can only make one of these types of calls
this() is used to call any of the other overloaded constructors defined in the class before performing actions specific to current constructor
A static inner class cannot refer to instance variables and methods of the containing class directly unless you create an instance and refer to the variable/class in that instance.
If the inner class is defined inside a method, it has access to those method ˉs local variables that are declared final
A non-static inner class is defined by being placed inside the class definition (for the inner class) or inside another class definition (the outer class). It has access to all member variables and methods of the containing class.
An anonymous inner class is defined where it is instantiated inside a method, and is implementing an interface or extending a class without using the implements or extends keywords. Since they are anonymous, they cannot have any constructor
Inner x = new Inner(); is the code fragment needed to construct an instance of Inner where Inner is an inner class defined in the current class. To write code to construct an instance on an inner class where either no this object exists, or the current this object is not an instance of the outer class, you must create an instance of the outer class first: Outer.Inner y = new Outer().new Inner();
Garbage Collection
When your program has no more references to an object, the object is finalized and is then garbage collected automatically by Java.
Finalization - Java runtime system gives the object a chance to clean up after itself before it is garbage collected. This is done through a call to the object`s finalize() method.
You can increase the likelihood of object finalization and garbage collection using the System class`s runFinalization() method which in turns will call the finalize() methods on all objects that are waiting to be garbage collected. You can also ask the garbage collector to run by calling System`s gc() method.
Thread Control
A thread is a single sequential flow of control within a program.
Java is designed for multi-threaded operations.
Java threads are implemented by the Thread class, which is part of the java.lang package.
From the programmer`s perspective, thread class implementation is system independent, although the actual implementation of concurrent operation is provided by a system-specific implementation.
The thread`s run() method is where all the operations take place. You provide the body to a Thread by subclassing the Thread class and overriding its run() method, or by creating a Thread with a Runnable object as its target.
A thread`s state indicates what the Thread is currently doing:
New - creates a new thread but does not start it, making it merely an empty Thread object with no system resources being allocated for it
Runnable - the start() method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread`s run() method.
Not Runnable - a thread becomes "Not Runnable" state when someone invokes its sleep() method / suspend() method, uses its wait() method to wait on a condition variable, or that the thread is blocking on I/O.
Dead - a thread can die either from natural causes, such as the run() method has completed, or being killed by calling its stop() method. In any case, the thread can never be restarted
A thread`s priority tells the thread scheduler when this thread can be run in relation to other threads. Daemon threads are threads that provide services for other threads
Synchronizing Threads - if independent and concurrently running threads are sharing data or resources, they must consider the state and activities of other threads by using Object`s notify() and wait() methods to coordinate with each other. You can also synchronize threads around a condition variable through the use of monitors, which prevent two threads from simultaneously accessing the same variable.
A thread is put into a Waiting state by calling the wait() method. notify()/ notifyAll() tell the thread / all the waiting threads the lock for this object has become available.
Error and Exception
All Java methods use the throw statement to throw an exception.
The throw statement requires a single argument: a throwable object.
Throwable has two direct descendants: Error and Exception:
Error - dynamic error or some other "hard" failure in the virtual machine
Exception - a problem occurred but that the problem is not a serious systemic problem that you can catch and trap the problem. Runtime Exceptions are exceptions that occur within the Java virtual machine during runtime, such as NullPointerException which occurs when a method tries to access a member of an object through a null reference. Sometimes unpredictable, the compiler allows runtime exceptions to go uncaught, although you can catch these exceptions just like other exceptions. A method is not required to specify that it throws RuntimeExceptions though.
Java requires that methods either catch or specify all checked exceptions that can be thrown within the scope of that method
An example of throwing an exception: public Object mypopupbox() throws EmptyStackException { ?
A popular way to handle exceptions is to place code inside a try { } block.
You can create one or more catch() { } blocks after the try block with code to deal with all different types of exceptions that might be thrown
Finally blocks execute whether the code executes without an exception, or an exception is thrown and successfully caught, or an exception is thrown and not caught. Except for code in a finally block, the execution of the remaining method is stopped if there is an exception that is thrown but not caught, or that the exception is not caught correctly.
Commonly used methods for numeric and string
abs()- gets the absolute value
ceil(double) - gets the smallest double value that is not less than the argument
floor(double)- gets the largest double value that is not greater than the argument
max(value1,value2)- finds out the greater value
min(value1,value2)- finds out the smaller value
random()- generates a random number between 0.0 and 1.0
round(double)- round to the closest long
sqrt(double) - gets the square root of a double value
length()- gets the string length
toUpperCase()- converts string to uppercase
toLowerCase()- converts String to lowercase
equalsIgnoreCase(String)- compares the content of two string objects while ignoring the case.
charAt(int)- returns the character at the specified index
concat(String)- concatenates the specified string to the end of the current string
substring(int)- returns a new string that is a substring of the current string.
trim()-removes all white space from both ends of the string
toString()- returns a string representation of the object
Collection classes/interfaces in the java.util package
Set
Cannot contain any duplicate elements
Has no explicit order to its elements
SortedSet
A Set which maintains its elements in ascending order.
List
A collection which can contain duplicate elements
Elements are ordered
Stack
A subset of Vector
Last-in, first-out
Map
Holds keys for us to look up
cannot have duplicate keys
Standard I/O Streams
The three standard streams managed by the java.lang.System class are:
standard input-- System.in, typically reads input entered by user.
standard output-- System.out, typically displays information to the user.
standard error-- System.err, used to display error messages to the user.
Input and Output Stream
java.io package contains the InputStream class and the OutputStream classes:
FileInputStream and FileOutputStream - read data from or write data to a file
PipedInputStream and PipedOutputStream - implement the input and output components of a pipe that channels the output from one program or thread into the input of another.
ByteArrayInputStream and ByteArrayOutputStream - read data from or write data to a byte array in memory.
SequenceInputStream - concatenate multiple input streams into one.
StringBufferInputStream - allow programs to read from a StringBuffer as if it were an input stream.
Java AWT
Stands for Abstract Window Toolkit
An uniform interface to various windowing environments
Interface between java.awt and the native windows toolkit is provided by the java.awt.Toolkit class and the package java.awt.peer
Framework for any GUI application is provided by the java.awt.Component class and its subclasses, that every GUI element except menus corresponds to a subclass of Component Menus subclasses the java.awt.MenuComponent class.
Component class represents a GUI component that has size, font, and color attributes, can redraw itself and handle events which occur within it`s display area. Common methods include:
hide()- hide the component
show()- show the component
disable()- disable the component by mostly graying it out
enable()- enable a disabled component
repaint()- paint the component as soon as possible.
handleEvent()- for you to override in order to provide specific responses to user events
validate()- verify that the component has been created and displays properly
Container Components
Belong to a subclass of the java.awt.Container class
Know how to add() and remove() components to or from the container and how to layout() the various components using a layout manager
Component that is not an instance of Window or a subclass must be added to a container to be visible on screen
Label
Displays a line of text that cannot be edited by user
List
Presents a scrollable list of items identified by string names
Scrollbar
Mostly automatically generated when required by List or TextArea components. orientation specified by the constants Scrollbar.HORIZONTAL and Scrollbar.VERTICAL
Five basic operations: line up, line down, page up, page down, and absolute positioning
TextField
Holds a single line of text in a little window in which user is allowed to edit text
You can set a TextField to read-only by using setEditable(false)
TextArea
a text pane containing lines of editable text
Event Handling
GUI is event driven
When an event occurs, the native windows toolkit first receives the event. The event is then passed to the AWT class that represents the component. The handleEvent() method of the corresponding object is then invoked. Until the Event is fully handled by some event handler, it continues to propagate up the container hierarchy, passing from each component to its parent container. Common event-handler methods include:
mouseDown(), mouseDrag(), mouseUp(), mouseMove(), mouseEnter(), mouseExit(), keyDown(), keyUp()
Layout Managers
When you add components into a container, it is the layout manager of the container which determines the actual size and location of each component.
All containers have a default layout manager, but you can designate which layout manager to use by passing a new instance of the LayoutManager to the container`s setLayout() method
BorderLayout
Possible placements are "North," "South," "East," "West," and "Center."
Components around the edges are laid out first and the center component gets the leftover room
Components are stretched out to meet the edges of the container
CardLayout
Lets several components occupy the same space
Only one component visible at a time
User flips through the "cards"
FlowLayout
Components are arranged left to right in a row until no more can fit in, then a new row is begun.
Each row is centered in the parent component by default.
GridLayout
Arranges components in a grid of same size rectangular cells
Contents of each cell are resized to fill the cell
Cells are populated from left to right in each row and then down to the next row
GridBagLayout
Based on a rectangular array of cells
Each component may occupy a rectangular area covering several cells
Each child component has an associated GridBagConstraints object to give hints to the layout manager about its minimum size and preferred position in the container.