Java Language Fundamentals
This quick tutorial contains bullet points useful for interviews or quick reference. For a detailed java tutorial click here.
- Identifiers are names of variables, functions, classes etc. The name used
as an identifier must follow the following rules in JavaTM technology.
- Each character is either a digit, letter, underscore(_) or currency symbol ($,¢, £ or ¥)
- First character cannot be a digit.
- The identifier name must not be a reserved word.
- A keyword or reserved word in Java technology has special meaning and
cannot be used as a user defined identifier. The list of keywords in Java
technology is given below. It is important to completely remember this list as
you can expect a question in Java Certification exam related to this.
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 strictfp super switch synchronized this throw throws transient try void volatile while It is important to note the following
- const and goto are not currently in use.
- null, true, and false are reserved literals but can be considered as reserved words for the purpose of exam.
- It is important to understand that Java language is case-sensitive. So even though super is a keyword, Super is not.
- All the Java technology keywords are in lower case.
- strictfp is a new keyword added in Java 2.
- The list of keywords as defined by Sun is present here.
- A literal in Java technology denotes a constant value. So for example 0 is
an integer literal, and 'c' is a character literal. The reserved literals true
and false are used to represent boolean literals. "This is a string" is a
string literal.
- Integer literals can also be specified as octal (base 8), or hexadecimal
(base 16). Octal and hexadecimal have 0 and 0x prefix respectively. So 03 and
0x3 are representation of integer three in octal and hexa-decimal
respectively.
- Java technology supports three type of comments
- A single line comment starting with //
- A multi-line comment enclosed between /* and */
- A documentation or javadoc comment is enclosed between /** and */. These comments can be used to generate HTML documents using the javadoc utility, which is part of Java language.
- Java technology supports the following primitive types - boolean (for
representing true or false), a character type called char, four integer types
(byte, short, int and long) and two floating point types (float and double).
The details of these types are given below -
Data types Width (in bytes) Minimum value Maximum Value byte 1 -27 27 - 1 short 2 -215 215-1 int 4 -231 231 - 1 long 8 -263 263 - 1 char 2 0x0 0xffff float 4 1.401298e-45 3.402823e+38 double 8 4.940656e-324 1.797693e+308 - Corresponding to all the primitive type there is a wrapper class defined.
These classes provide useful methods for manipulating primitive data values
and objects.
Data types Wrapper class int Integer short Short long Long byte Byte char Character float Float double Double -
Instance variables (data members of a class) and static variables are
initialized to default values. Local variables (i.e. variables defined in
blocks or inside member functions) are not initialized to default values.
Local variables must be explicitly initialized before they are used. If local
variables are used before initialization, compilation error gets generated.
The defaults for static and instance variables are given in the table below.
Data types Default Values boolean false char '\u0000' Integer types (byte, short, int, long) 0 Floating types (float, double) 0.0F or 0.0 D Object References null public static void main(String args[]) {
int i;
System.out.println(i);
}
In this example printing of i generates a compilation error because local variable i is used before being initialized. The initialization of instance and static variables is an important concept both for understanding of Java language, and for Java Certification exam.
- A Java source file has the following elements in this specific order.
- An optional package statement. All classes and interfaces defined in
the file belong to this package. If the package statement is not
specified, the classes defined in the file belong to a default package. An
example of a package statement is -
package testpackage; - Zero or more import statements. The import statement makes any classes
defined in the specified package directly available. For example if a Java
source file has a statement importing the class "java.class.Button", then
a class in the file may use Button class directly without providing the
names of the package which defines the Button class. Some examples of
import statement are -
import java.awt.*; // All classes in the awt package are imported.
import java.applet.Applet; - Any number of class and interface definitions may follow the optional package and import statements.
If a file has all three of the above constructs, they must come in the specific order of package statement, one or more import statements, followed by any number of class or interface definitions. Also all the above three constructs are optional. So an empty file is a legal Java file.
- An optional package statement. All classes and interfaces defined in
the file belong to this package. If the package statement is not
specified, the classes defined in the file belong to a default package. An
example of a package statement is -
- The Java interpreter executes a method called main, defined in the class
specified in command line arguments. The main method is the entry point for
execution of a class. In Java technology the main method must have the
following signature -
public static void main(String args[])
The java interpreter is invoked with the name of the class as an argument. The class name is followed by possible set of arguments for the main function of the class. When a Java program is invoked then the Java interpreter name "java" and the class name are not passed to the main() method of the class. The rest of the command line arguments are passed as an array of String. For example invokingjava Sky blue gray
would invoke main method of Sky class with an array of two elements - blue and gray.
-
Operators and assignments
- Commonly used operators
- Following are some of the commonly used JavaTM technology operators -
Multiplication (*), Addition (+), Subtraction (-), logical and (&&)
Conditional Operator ?:, Assignment (=), left shift (<<), right shift (>> and
>>>), Equality comparison (==), Non-equality comparison (!=).
- Conversion rules in Assignments
- In the description below, I am giving basic conversion rules for assignment when source and destination are of different types.
- If source and destination are of the same type, assignment happens without any issues.
- If source is of smaller size than destination but source and destination are of compatible types, then no casting is required. Implicit widening takes place in this case. An example is assigning an int to a long.
- If source and destination are of compatible types, but source is of larger size than destination, explicit casting is required. In this case, if no casting is provided then the program does not compile.
- Floating point numbers
- Decimal numbers (for example 1.3) are of type double by default. To make them of type float they must be followed by F (say, 1.3F).
- The equality operator
- The equality operator (==) when applied to objects return true if two objects have same reference value, false otherwise. The example below illustrates this --
String str1 = "first string";
String str2 = new String("first string");
String str3 = "first string";
boolean test1 = (str1 == str2);
boolean test2 = (str1 == str3);
In the example above, test1 is set to false because str1 and str2 point to different references. As str1 and str3 point to the same reference, test2 gets set to true. When a string is initialized without using the new operator, and with an existing string, then the new string also points to the first string's location. So in the example above, str1 and str3 point to the same pool of memory and hence test2 gets set to true. The string str2 on the other hand is created using the new operator and hence points to a different block of memory. Hence test1 gets set to false.
- The conditional operators && and ||
- Operator && returns true if both operands are true, false otherwise. Operator || returns false if both operands are false, true otherwise. The important thing to note about these operators is that they are short-circuited. This means that the left operand is evaluated before the right operator. If the result of the operation can be evaluated after computing the left operand, then the right side is not computed. In this respect these operators are different from their bit-wise counterparts - bit-wise and (&), and bit-wise or (|). The bit-wise operators are not short-circuited. This means both the operands of bit-wise operator are always evaluated independent of result of evaluations.
- Storing integral types
- All the integer types in Java technology are internally stored in two's complement. In two's complement, positive numbers have their corresponding binary representation. Two's complement representation of negative numbers is generated using the following three step process -
- First get the binary representation of the number.
- Then interchange zeros and ones in the binary representation.
- Finally add one to the result. So for example two's complement of -18
would be (assuming one byte representation) -
- Converting 18 to binary -- 0001 0010
- Interchanging 0s and 1s -- 1110 1101
- Adding 1 -- 1110 1110
So 1110 1110 would be binary representation of -18 using two bytes and using two's complement representation.
- The shift operators
- The shift left operator in Java technology is "<<". There are two operators for doing the right shift - signed right shift (>>) and zero fill right shift (>>>).
The left shift operator fills the right bits by zero. The effect of each left shift is multiplying the number by two. The example below illustrates this -
int i = 13; // i is 00000000 00000000 00000000 0000 1101
i = i << 2; // i is 00000000 00000000 00000000 0011 0100After this left shift, i becomes 52 which is same as multiplying i by 4
Zero fill shift right is represented by the symbol >>>. This operator fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number is positive, negative otherwise.) The example below illustrates applying the operator >>> on a number.
int b = 13; // 00000000 00000000 00000000 0000 1101
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect of applying the operator >>> on a negative number.
int b = -11; //11111111 11111111 11111111 1111 0101
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101So the result of applying zero fill right shift operator with operand two on -11 is 1073741821.
Signed right shift operator (>>) fills the left most bit by the sign bit. The result of applying the signed shift bit has the same sign as the left operand. For positive numbers the signed right shift operator and the zero fill right shift operator both give the same results. For negative numbers, their results are different. The example below illustrates the signed right shift.
int b = -11; // 11111111 11111111 11111111 1111 0101
b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2's complement of -3)
// Here the sign bit 1 gets filled in the two most significant bits.The new value of b becomes -3.
Declaration and Access Control - Array Fundamentals
- Arrays are used to represent fixed number of elements of the same
type. The following are legal syntax for declaring one-dimensional arrays.
int anArray[];
int[] anArray;
int []anArray;
It is important to note that the size of the array is not included in the declaration. Memory is allocated for an array using the new operator as shown below.
anArray = new int[10];
The declaration and memory allocation may be combined together as shown below.
int anArray[] = new int[10];
The elements of the array are implicitly initialized to default values based on array types (0 for integral types, null for objects etc.). This is true for both local arrays as well as arrays which are data members. In this respect arrays are different from normal variables. Variable defined inside a method are not implicitly initialized, where as array elements are implicitly initialized.- Array Initializations
- Arrays are initialized using the syntax below
int intArray[] = {1,2,3,4};
The length operator can be used to access the number of elements in an array (for example - intArray.length).- Multidimensional Arrays
- The following are legal examples of declaration of a two dimensional array.
int[] arr[];
int[][] arr;
int arr[][];
int []arr[];
When creating multi-dimensional arrays the initial index must be created before a later index. The following examples are legal.
int arr[][] = new int[5][5];
int arr[][] = new int[5][];
The following example will not compile;
int arr[][] = new int[][5];
- Class Fundamentals
- A class defines a new type and contains methods and variables. The example below illustrates a simple class.
class City {
String name; // member variable
String getName() // member method
{
return name;
}
public static void main(String arg[]) {
}
}
- Method overloading
- JavaTM technology allows two methods to have the same name as long as they have different signatures. The signature of a method consists of name of the method, and count and type of arguments of the method. Thus as long as the argument types of two methods are different, they may be over-loaded (have the same name).
- Class constructors
- Constructors are member methods that have same name as the class name. The constructor is invoked using the new operator when a class is created. If a class does not have any constructors then Java language compiler provides an implicit default constructor. The implicit default constructor does not have any arguments and is of the type -
class_name() { }If a class defines one or more constructors, an implicit constructor is not provided. The example below gives a compilation error.
class Test {
int temp;
Test(int x) {
temp = x;
}
public static void main() {
Test t = new Test(); /* This would generate a
compilation error, as there is no constructor
without any arguments. */
}
}
Classes in JavaTM technology - The Object class
- All classes in JavaTM technology are directly or indirectly derived
from the Object class. Some of the subclasses of Object class are -
Boolean, Number, Void, Math, String, StringBuffer etc.

Some of the important methods defined in the Object class are given below. These methods are available to all Java classes.
- boolean equals(Object obj) - The equals method in Object class returns true if two references point to the same object. Some classes like String and Boolean overload this method. The difference between the equals function and the equality operator is covered here.
- String toString() - The function is used to convert objects to String. If a subclass does not override this method, the method returns a textual representation of the object, which has the following format : <name of the class>@<hash code value of the object>".
- The following methods related to threads are also defined in
Object class -
void notify()
void notifyall()
void wait(long timeout) throws InteruptedException
void wait(long timeout, int nanosec) throws InteruptedException
void wait() throws InteruptedException
- Wrapper classes
- Corresponding to all the primitive types Java technology defines wrapper classes. Some examples of these wrapper classes are - Character, Boolean, Integer, Double.
- Important methods in the Math class
- Some of the methods defined in the Math class are used frequently. These are explained below. Besides the functionality, it is important to understand the arguments and return type of these functions.
static double ceil(double(d)) : The method ceil returns the smallest double value equal to a mathematical integer, that is not less than the argument. For example,
ceil(3.4) returns 4.0
ceil(-2.3) returns -2.0
ceil(3.0) returns 3.0
static double floor(double(d)) : The method floor returns the largest double value equal to a mathematical integer, that is not greater than the argument. For example,
floor(3.4) returns 3.0
floor(-2.3) returns -3.0
floor(3.0) returns 3.0
static int round (float f) and static long round(double d) : The method round returns the integer closest to the argument.
round(3.7) returns 4
round(3.2) returns 3
round(3.0) returns 3
round(-3.1) returns -3
- String class
- The String class is used to implement immutable character strings. This means that the character string cannot be changed once it has been created. Some of the important methods are explained below.
int length() - The number of characters in the String class are returned by the length() method.String substring(int startIndex)
String substring(int startIndex, int endIndex)
The method substring extracts a substring from a string. The method extracts a string from the startIndex to the index endIndex - 1. If endIndex is not specified then string till the end of input string is returned. The example below illustrates this
String str = "I am a string";
int len = str.length();
String str2 = str.substring(2,5);
After the above statements str2 contains the string "am ". The string str still has the same value "I am a string". The variable len has value 13.
- StringBuffer class
- The StringBuffer class implements mutable strings. This means that the characters stored in the string and the capacity of the string can be changed.
- Garbage Collection
- Java technology's Garbage collection is complex. In this section I am only giving a brief overview of Garbage Collection. Java technology supports automatic garbage collection. This means that the programmer does not need to free the memory used by objects. Java technology's runtime environment can claim the memory from the objects that are no longer in use. Objects that are not being referred become candidates for garbage collection. It is important to note that these objects are candidates only. Java technology does not guarantee that Garbage collection would happen on these objects. Before actually freeing up the memory, garbage collector invokes the finalize() method of the Object being freed.
The System.gc() method can be invoked by the program to suggest to Java technology that the Garbage Collector be invoked. However there is no guarantee when the garbage collection would be invoked. There is also no guarantee on the order in which objects will be garbage collected.
The example illustrates when a string Object becomes available for Garbage Collection.
public class GCTest {
public static void main(String args[]) {
String a,b;
String c = new String("test");
a = c;
c = null; // The String "test" is not yet
//available for GC as a still points to "test"
b = new String("xyz");
b = c; // String "xyz" is now available for GC.
a = null;
//String "test" is now available for GC.
}
}
Abstract Windowing Toolkit This topic is part of SCJP 1.2 exam but not SCJP 1.4 exam.
- AWT class hierarchy
- The JavaTM Foundation class (JFC) provides two frameworks for building
GUI based applications - Abstract Windowing Toolkit (AWT) and swings.
Sun's JavaTM Programmer Certification exam only covers AWT.
AWT's class hierarchy is explained below.

FIGURE AWTs class hierarchy
- Key Concepts
- Some things to note here are
- Component is an abstract class. All other classes shown above are non-abstract (concrete).
- Component class is superclass of all the non-menu related user
interface classes. It provides support for event handling, drawing of
components etc. Some of the methods of Component class are -
void setForeground(Color c)
void setBackground(Color c) - As the name indicates, these methods are used to set color of a
component. The font of the text rendered can be changed using the
setFont(Font f) method. By default all components except objects of
type Window and its subclasses (Dialog and Frame) are visible. The
visibility of a component can be changed using the setVisible method
defined in the component class. The prototype of this method is
void setVisible(boolean b); - Panel class does not have a title, menu or border. Applet class is used to run programs that run in a web browser.
- Window class represents a top-level window. Both Window and Panel classes do not have title, menus or borders. The Window class is rarely used directly and its subclasses Frame and Dialog are more common.
- The pack method defined in Window class initiates the layout manager of sub-components of the window.
- The Frame class is a subclass of the Window class. It is used to create a GUI application window. Frames have title bars, icons and menus.
AWT Event Classes This topic is part of SCJP 1.2 exam but not SCJP 1.4 exam.
- Events
- When the user interacts with a GUI application, an event is generated.
Examples of user events are clicking a button, selecting an item or
closing a window. Events are represented as Objects in JavaTM technology.
The super class of all event classes is java.util.EventObject. Some of the
important classes and their hierarchy is shown below.
- Some methods related to Events are
- Object getSource()
This method is defined in the Event Object class. It returns the object that originated the event. So if the user has clicked a Push button, the method getSource returns the object corresponding to Push button is generated.int getID()
This method returns the integer value corresponding to the type of event. For example if the user has clicked on the mouse, the method getID returns the integer defined as MouseEvent.MOUSE_CLICKED.- AWT event classes
- The subclasses of ATW Event can be categorized into two groups - Semantic events and low-level events. Semantic events directly correspond to high level user interactions with a GUI component. Clicking of a button is an example of a semantic event. Following event classes are semantic classes.
ActionEvent
AdjustmentEvent
ItemEvent
TextEventMultiple low-level events may get generated for each high level user event. Following event classes are low level event classes.
ComponentEvent
ContainerEvent
FocusEvent
KeyEvent
MouseEvent
PaintEvent
WindowEvent- Event classes for GUI controls
- By GUI component I mean objects like Button, ListBox etc. For each Java GUI component a set of events of above type are generated. It is important to understand which events are generated for each component. This is explained below.
The GUI component that generate ActionEvent are
Button : When the user clicks on a PushButton.
List : When an item in list box is double clicked.
MenuItem : When a MenuItem is selected.
TextField : When the user clicks the Enter key in a text box.AdjustmentEvent is generated when the user adjusts the position of a scrollbar. Scrollbar is the only GUI control that receives the AdjustmentEvent.
ItemEvent is generated when an item is selected or deselected. Following components generate ItemEvents.
CheckBox : When the state of the CheckBox is changed.
CheckBoxMenuItem : When the state of a MenuItem is changed.
Choice : When the state of a ChoiceBox is changed.
List : When an item in list is selected or deselected.TextEvent is generated when the contents of text component are changed. The components that generate TextEvent are TextArea and TextField.
Now I will describe the GUI components corresponding to low level event classes.
FocusEvent : This event is generated when a component gains or looses focus. Focus may be gained by bringing the mouse over a component (or by using the tab key). The component that has the focus receives all user keyboard events. Focus events are generated by objects of Component class and all its subclasses.
KeyEvent and MouseEvent are subclasses of abstract InputEvent class. Both these events are generated by objects of type Component class and its subclasses. The KeyEvent is generated when the user presses or releases a key on the keyboard. The MouseEvent is generated when the user presses the mouse or moves the mouse.
WindowEvent are generated for the Window class and its subclasses. These events are generated if an operation is performed on a window. The operation could be closing of window, opening of window, activating a window etc.
PaintEvent is generated when a component needs to be repainted (for example when an application which is in front is closed and the component needs to be redrawn.) PaintEvents are internally handled by AWT, and cannot (and should not) be handled by you in the application.
ComponentEvent are also generated by objects of type Component class and its subclasses. This event is generated when a component is hidden, shown, moved or resized.
ContainerEvents are generated when a component is added or removed from a container. ComponentEvent and ContainerEvent are handled by AWT and are not normally handled by the user.
- Event Listeners
- These are objects that define methods to handle certain type of events. An event source (for example a PushButton) can generate one or more type of events, and maintain a list of event listeners for each type of event. An event source can register listeners by calling addXListener type of methods. For example a Button may register an object for handling ActionEvent by calling addActionListener. This object would then need to implement the listener interface corresponding to ActionEvent, which is ActionListener. The example below illustrates this -
// A window with just an OK button.
public class exampleWindow extends Frame {
Button OkButton;
OkHandler handler;
public exampleWindow() { //Constructor
.... /* Code to create a window, button
and set a layout Manager. */
/* Now create and add listener */
handler = new OkHandler(this);
OkButton.addActionListener(handler);
}
public static void main (String args []) {
new exampleWindow();
}
}
/* Now define a listener object. It must implement the
interface ActionListener by defining the function
actionPerformed. */
class OkHandler implements ActionListener {
private exampleWindow win;
public OkHandler(exampleWindow window) {
win=window;
}
public void actionPerformed(ActionEvent evt) {
// Process clicking of button here.
}
}
So to set up the processing of events the following tasks must be done.
- For the GUI component (like pushbutton) associate a listener object class with the component by calling a method of type addXListener (See table below for list of methods).
- Define this listener object. It must implement the corresponding interface. The name of interface is of type EventListener. Table below gives list of event listeners.
- The object must define all the methods defined in the interface it is implementing. See table for the list of Event Listener methods defined in each Event Listener interface.
Table Event types and corresponding EventSource & EventListenerEvent Type Event Source Event Listener interface ActionEvent Button, List, MenuItem, TextField ActionListener AdjustmentEvent Scrollbar AdjustmentListener ItemEvent Choice, Checkbox, CheckboxMenuItem, List ItemListener TextEvent TextArea, TextField TextListener ComponentEvent Component ComponentListener ContainerEvent Container ContainerListener FocusEvent Component FocusListener KeyEvent Component KeyListener MouseEvent Component MouseListener, MouseMotionListener WindowEvent Window WindowListener
Table Event Listener Interfaces and corresponding methods which it definesEvent Listener interface Event Listener Methods ActionListener actionPerformed(ActionEvent evt) AdjustmentListener adjustmentValueChanged(AjustmentEvent evt) ItemListener itemStateChanged(ItemEvent evt) TextListener textValueChanged(TextEvent evt) ComponentListener componentHidden(ComponentEvent evt), componentMoved(ComponentEvent evt), componentResized(ComponentEvent evt), componentShown(ComponentEvent evt) ContainerListener componentAdded(ContainerEvent evt), componentRemoved(ContainerEvent evt) FocusListener focusGained(FocusEvent evt), focusLost(FocusEvent evt) KeyListener keyPressed(KeyEvent evt), keyReleased(KeyEvent evt), keyTyped(KeyEvent evt) MouseListener mouseClicked(MouseEvent evt), mouseEntered(MouseEvent evt), mouseExited(MouseEvent evt), mousePressed(MouseEvent evt), mouseReleased(MouseEvent evt) MouseMotionListener mouseDragged(MouseEvent evt), mouseMoved(MouseEvent evt) WindowListener windowActivated(WindowEvent evt), windowClosed(WindowEvent evt), windowClosing(WindowEvent evt), windowDeactivated(WindowEvent evt), windowDeiconified(WindowEvent evt), windowIconified(WindowEvent evt), windowOpened(WindowEvent evt)
- Adapter classes
- Event adapters facilitate implementing listener interfaces. Many event listener interfaces have more than one event listener methods. For such interfaces, Java technology defines adapter classes. These have empty implementation (stubs) of all the event listener methods defined in the interface they implement. A listener can subclass the adapter and override only stub methods for handling events of interest. The table below lists the low level event listener interfaces and their adapters.
Table Event Listener Interfaces and their corresponding adapter classes.Event Listener interface Event Listener Adapter ComponentListener ComponentAdapter ContainerListener ContainerAdapter FocusListener FocusAdapter KeyListener KeyAdapter MouseListener MouseAdapter MouseMotionListener MouseMotionAdapter WindowListener WindowAdapter
- Threads
- A thread is in process in execution within a program. Within a program
each thread defines a separate path of execution.
- Creation of a thread
- A thread can be created in two ways
a) By implementing the Runnable interface. The Runnable interface consists of only one method - the run method. The run method has a prototype of
public void run();
b) By extending the class Thread.
- Execution of a thread
- To execute a thread, the thread is first created and then the start() method is invoked on the thread. Eventually the thread would execute and the run method would be invoked. The example below illustrates the two methods of thread creation. You should note that the run method should not be invoked directly.
public class ThreadExample extends Thread {
public void run() {
System.out.println("Thread started");
}
public static void main(String args[]) {
ThreadExample t = new ThreadExample();
t.start();
}
}
Example - Creation of Thread by extending the
Thread class.
When the run method ends, the thread is supposed to "die". The next example shows the creation of thread by implementing the Runnable interface.
public class ThreadExample2 implements Runnable {
public void run() {
.../* Code which gets executed when
thread gets executed. */
}
public static void main(String args[]) {
ThreadExample2 Tt = new ThreadExample2();
Thread t = new Thread(Tt);
t.start();
}
}
Example - Creating thread by implementing Runnable
- States of thread
- A thread can be in one of the following states - ready, waiting for some action, running, and dead. These states are explained below.
Running State A thread is said to be in running state when it is being executed. This thread has access to CPU.
Ready State A thread in this state is ready for execution, but is not being currently executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state.
Dead State A thread reaches "dead" state when the run method has finished execution. This thread cannot be executed now.
Waiting State In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be in one of the following states - sleeping, suspended, blocked, waiting for monitor. These are explained below.
- Yielding to other processes
- A CPU intensive operation being executed may not allow other threads to be executed for a "large" period of time. To prevent this it can allow other threads to execute by invoking the yield() method. The thread on which yield() is invoked would move from running state to ready state.
- Sleep state of a thread
- A thread being executed can invoke the sleep() method to cease executing, and free up the CPU. This thread would go to the "sleep" state for the specified amount of time, after which it would move to the "ready" state. The sleep method has the following prototypes.
public static void sleep (long millisec)
throws InterruptedException;
public static void sleep (long millisec, int nanosec)
throws InterruptedException;
- Synchronized state
- A code within the synchronized block is "atomic". This means only one thread can execute that block of code for a given object at a time. If a thread has started executing this block of code for an object, no other thread can execute this block of the code (or any other block of synchronized code) for the same object.
public synchronized void synchExample() {
/* A set of synchronized statements. Assume
here that x is a data member of this class. */
if(x == 0)
x = 1;
}
- Basics of Layout Managers
- Java technology uses Layout Managers to define the location and size of
Graphical User Interface components. Java technology does not encourage
programmers to use absolute location and size of components. Java technology
instead places components based on specified Layout Manager. A Layout Manager
implements a layout policy that defines constraints between components in a
container.
- Types of Layout Managers
- Java technology provides the following Layout Managers, each of which implements the LayoutManager interface.
- FlowLayout
- GridLayout
- BorderLayout
- GridBagLayout
- CardLayout
The FlowLayout is the default Layout Manager for Panel, and hence the Applet class. The BorderLayout is the default Layout Manager for Window class and its subclasses (Frame and Dialog).- Setting Layout Managers
- The following method defined in the Container class can be used for setting layout managers.
void setLayout(LayoutManager mgr);
So for example to set FlowLayout as the Layout Manager for a container C, the following can be used -
C.setLayout(new FlowLayout());
The add method defined in the Container class can be used for adding components to a container. The following are the prototypes of the add method -
Component add(Component comp);
Component add(Component comp, int index);
void add(Component comp, Object constraints, int index);
void add(Component comp, Object constraint);
The order in which components are added to a container effects the placement of components. Also a component added to a container can itself be a container that holds other components.- FlowLayout Manager
- FlowLayout places component in rows from left to right. Components towards the end of row are written on next row, if there is not enough space in the current row. The FlowLayout honors the specified size of a component. The size of a component never changes regardless of size of container. The following constructors of FlowLayout are provided by AWT -
FlowLayout();
FlowLayout(int alignment);
FlowLayout(int alignment, int hor_gap, int ver_gap);
Alignment can take values of constants - LEFT, CENTER and RIGHT. The default alignment for the components in a row is center. Default horizontal and vertical gaps are 5 pixels.- GridLayout Manager
- A GridLayout Manager places the components in a rectangular grid. Each component's position is identified by a column and row. All the cells in the grid have same size and width. Each component is stretched to the cell size. So a GridLayout ignores the Component's preferred size.
The GridLayout class provides the following constructors.
GridLayout();
GridLayout(int rows, int columns);
GridLayout(int rows, int columns, int hor_gap, int ver_gap);
This creates a row*col grid layout with the specified horizontal and vertical gaps. In the constructor, either rows or cols can be zero, but not both. The first constructor is equivalent to one row with any number of components. The default gap between components is zero pixels.- BorderLayout Manager
- A BorderLayout Manager divides the window into five regions - North, East, West, South and Center. A component can be explicitly added to one of the regions using the add() method of the Container class. Any space left over by the component in North, East, South and West is occupied by the component in Center. Only the last component added to a region is shown, and not all regions need to be occupied by a component. So a container that uses BorderLayout may have up-to 5 components.
The BorderLayout class defines the following constructors -
BorderLayout();
BorderLayout(int hor_gap, int ver_gap);
As illustrated below, components can be added to the container using add() method defined in the Container class.
Component add(Component comp);
void add(Component comp, Object constraints);
Here constraints can be NORTH, SOUTH, EAST, WEST and CENTER. These constants correspond to strings "North", "South", East", "West", and "Center" respectively. They describe the region where the component should be placed. The default region is CENTER.- GridBagLayout
- GridBagLayout is the most advanced LayoutManager in Java technology. Refer to Sun site for details of GridBag layout.
- Collections
- A Collection allows a group of objects to be treated as a single unit.
Collections define a set of core interfaces. These are -
- Collection
- Set
- List
- SortedSet
- Map
- SortedMap
Collections also provide implementation for these interfaces.
- Core Interfaces
- The Object hierarchy of Core Interfaces defined in Collections is given below.
Figure: Core Interfaces of Collections
- Collection Interface
- The Collection interface is the root of Collection hierarchy, and is used for common functionality across all collections. There is no direct implementation of Collection interface.
- Set Interface
- The Set interface is used to represent a group of unique elements. It extends the Collection interface. The class HashSet implements the Set interface.
- SortedSet Interface
- The SortedSet interface extends the Set interface. It provides extra functionality of keeping the elements sorted. So SortedSet interface is used to represent collections consisting of unique, sorted elements. The class TreeSet is an implementation of interface SortedSet.
- List Interface
- The list interface extends the Collection interface to represent sequence of numbers in a fixed order. Classes ArrayList, Vector and LinkedList are implementation of List interface.
- Map Interface
- The Map Interface is a basic interface that is used to represent mapping of keys to values. Classes HashMap and Hashtable are implementations of Map interface.
- SortedMap Interface
- The SortedMap Interface extends Map interface and maintains their mappings in key order. The class TreeMap implements SortedMap interface.
The table below gives the list of Collection interfaces and the classes that implement them.
Interface Class Implementation Set HashSet SortedSet TreeSet List ArrayList, Vector, LinkedList Map HashMap, Hashtable SortedMap TreeMap
This topic is part of SCJP 1.2 exam but not SCJP 1.4 exam.
- java.io package
- Classes related to input and output are present in the JavaTM language
package java.io . Java technology uses "streams" as a general mechanism of
handling data. Input streams act as a source of data. Output streams act as a
destination of data.
- File class
- The file class is used to store the path and name of a directory or file. The file object can be used to create, rename, or delete the file or directory it represents. The File class has the following constructors -
File(String pathname); // pathname could be file or a directory name
File(String dirPathname, String filename);
File(File directory, String filename);The File class provides the getName() method which returns the name of the file excluding the directory name.
String getName();
- Byte Streams
- The package java.io provides two set of class hierarchies - one for handling reading and writing of bytes, and another for handling reading and writing of characters. The abstract classes InputStream and OutputStream are the root of inheritance hierarchies handling reading and writing of bytes respectively.
Figure : InputStream class hierarchy (partial)
Figure :
OutputStream class hierarchy (partial)

- read and write methods
- InputStream class defines the following methods for reading bytes -
int read() throws IOException
int read(byte b[]) throws IOException
int read(byte b[], int offset, int length) throws IOException
Subclasses of InputStream implement the above mentioned methods.OutputStream class defines the following methods for writing bytes -
void write(int b) throws IOException
void write(byte b[]) throws IOException
void write(byte b[], int offset, int length) throws IOException
Subclasses of OutputStream implement the above mentioned methods.The example below illustrates code to read a character.
//First create an object of type FileInputStream type using the name of the file.
FileInputStream inp = new FileInputStream("filename.ext");
//Create an object of type DataInputStream using inp.
DataInputStream dataInp = new DataInputStream(inp);
int i = dataInp.readInt();
- Reader and Writer classes
- Similar to the InputStream and OutputStream class hierarchies for reading and writing bytes, Java technology provides class hierarchies rooted at Reader and Writer classes for reading and writing characters.
A character encoding is a scheme for internal representation of characters. Java programs use 16 bit Unicode character encoding to represent characters internally. Other platforms may use a different character set (for example ASCII) to represent characters. The reader classes support conversions of Unicode characters to internal character shortage. Every platform has a default character encoding. Besides using default encoding, Reader and Writer classes can also specify which encoding scheme to use.
The Reader class hierarchy is illustrated below.
The Writer
class hierarchy is illustrated below.

The table below gives a brief overview of key Reader classes.
CharArrayReader The class supports reading of characters from a character array. InputStreamReader The class supports reading of characters from a byte input stream. A character encoding may also be specified. FileReader The class supports reading of characters from a file using default character encoding.
The table below gives a brief overview of key Writer classes.
CharArrayWriter The class supports writing of characters from a character array. OutputStreamReader The class supports writing of characters from a byte output stream. A character encoding may also be specified. FileWriter The class supports writing of characters from a file using default character encoding.
The example below illustrates reading of characters using the FileReader class.
//Create a FileReader class from the file name.
FileReader fr = new FileReader("filename.txt");
int i = fr.read(); //Read a character
