JAVA Programming Guide - Quick Reference
JAVA Programming Guide - Quick Reference
1. Type the program in the DOS editor or notepad. Save the DataType Size Default Min Value
file with a .java extension. Max Value
2. The file name should be the same as the class, which has the byte
main method. (Signed -128
3. To compile the program, using javac compiler, type the integer) 8 bits 0 +127
following on the command line:
Syntax: javac <filename.java> short
Example: javac abc.java (Signed -32,768
4. After compilation, run the program using the Java integer) 16 bits 0 +32,767
interpreter.
Syntax: java <filaname> (without the .java int
extension) (Signed -2,147,483,648
Example: java abc integer) 32 bits 0 +2,147,483,647
5. The program output will be displayed on the command line.
long -9, 223, 372,036,854,
(Signed 775,808,
Integer) +9,223,372,036,
64 bits 0 854, 775, 807
© 1999, Pinnacle Software Solutions Inc. 1 © 1999, Pinnacle Software Solutions Inc. 3
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
© 1999, Pinnacle Software Solutions Inc. 2 © 1999, Pinnacle Software Solutions Inc. 4
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
5. Switch statement
\f Form feed Syntax:
\\ Backslash switch(variable)
\” Double quote {
\ddd Octal character case(value1):
\xdd Hexadecimal character statements;
\udddd Unicode character break;
case(value2):
statements;
Arrays: An array which can be of any datatype, is created in break;
two steps – array declaration and memory allocation. default:
statements;
Array declaration break;
<datatype> [] <arr ```````````ayname>; }
Examples int[] myarray1;
double[] myarray2; Class Declaration: A class must be declared using the
Memory Allocation keyword class followed by the class name.
The new keyword allocates memory for an array. Syntax
Syntax class <classname>
<arrayname> = new <array type> [<number of {
elements>]; ———— Body of the class
Examples
myarray1 = new int[10]; A typical class declaration is as follows:
Myarray2 = new double[15]; <modifier> class <classname> extends
<superclass name> implements <interface name>
Multi-dimensional arrays: {
—————Member variable declarations;
Syntax: —————Method declarations and definitions
<datatype> <arrayname> [] [] = new <datatype> }
[number of rows][number of columns];
Example:
int mdarray[][] = new int[4][5];
© 1999, Pinnacle Software Solutions Inc. 5 © 1999, Pinnacle Software Solutions Inc. 7
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
Syntax
class <classname> extends <superclass name>
implements <interface name> final Class Cannot be subclassed.
{
class body; Method Cannot be overridden.
—————————;
} Variable Value cannot be changed
(Constant)
Creating A Package:
native Method Implemented in a language
1. Identify the hierarchy in which the .class files have to other than Java like C,C++,
be organized. assembly etc. Methods do not
2. Create a directory corresponding to every package, with have bodies.
names similar to the packages.
3. Include the package statement as the first statement in static Method Class method. It cannot refer to
the program. nonstatic variables and methods
4. Declare the various classes. of the class. Static methods are
5. Save the file with a .java extension. implicitly final and invoked
6. Compile the program which will create a .class file in through the class name.
the same directory.
7. Execute the .class file. Variable Class variable. It has only one
copy regardless of how many
Packages and Access Protection: instances are created. Accessed
only through the class name.
Accessed Public Protected Package Private
From the synchronized Method A class which has a synchronized
same class ? Yes Yes Yes Yes method automatically acts as a
lock. Only one synchronized
From a non method can run for each class.
subclass in
the same
package ? Yes Yes Yes No
© 1999, Pinnacle Software Solutions Inc. 9 © 1999, Pinnacle Software Solutions Inc. 11
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
NullPointerException Invalid use of a null reference. setPriority() Changes the priority of the thread
SecurityException Thrown when security is violated. activeCount() Returns the number of active
threads in a thread group
ClassNotFound Thrown when a class is not found.
Exception
Exception Handling Syntax:
CloneNotSupported Attempt to clone an object that
Exception does not implement the Cloneable try
interface. {
//code to be tried for errors
IllegalAccess Thrown when a method does not }
Exception have access to a class. catch(ExceptionType1 obj1)
{
Instantiation Thrown when an attempt is made //Exception handler for ExceptionType1
Exception to instantiate an abstract class or }
an interface. catch(ExceptionType2 obj2)
{
InterruptedException Thrown when a second thread //Exception handler for ExceptionType2
interrupts a waiting, sleeping, or }
paused thread. finally{
//code to be executed before try block ends.
This executes whether or not an //
exception occurs in the try block.
}
The java.lang.Thread class I/O classes in Java (part of the java.io package):
The Thread class creates individual threads. To create a thread I/O class name Description
either (i) extend the Thread class or (ii) implement the Runnable
interface. In both cases, the run() method defines operations BufferedInputStream Provides the ability to buffer the
© 1999, Pinnacle Software Solutions Inc. 13 © 1999, Pinnacle Software Solutions Inc. 15
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
StringReader Character stream that reads getName() Returns the name of the file and directory
from a string denoted by the path name
isDirectory() Tests whether the file represented by the
StringWriter Character stream that writes to pathname is a directory
a StringBuffer that is later lastModified() Returns the time when the file was last
converted to a String modified
l length() Returns the length of the file represented by
the pathname
The java.io.InputStream class: The InputStream class is listFiles() Returns an array of files in the directory
at the top of the input stream hierarchy. This is an abstract class represented by the pathname
which cannot be instantiated. Hence, subclasses like the setReadOnly() Marks the file or directory so that only
DataInputStream class are used for input purposes. read operations can be performed
renameTo() Renames the file represented by the
Methods of the InputStream class: pathname
delete() Deletes the file or directory represented by
Method Description the pathname
available() Returns the number of bytes that can be canRead() Checks whether the application can read
read from the specified file
canWrite() Checks whether an application can write to
close() Closes the input stream and releases a specified file
associated system resources
© 1999, Pinnacle Software Solutions Inc. 17 © 1999, Pinnacle Software Solutions Inc. 19
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
skip() Skips a specified number of bytes from the The <applet> tag: Code, width, and height are
input stream mandatory attributes of the <applet> tag. Optional attributes
include codebase, alt,name, align, vspace, and
hspace. The code attribute takes the name of the class file as
The java.io.OutputStream class: The OutputStream class its value.
which is at the top of the output stream hierarchy, is also an Syntax:
abstract class, which cannot be instantiated. Hence, subclasses <applet code = “abc.class” height=300
like DataOutputStream and PrintStream are used for width=300>
output purposes. <param name=parameterName1 value= value1 >
<param name=parameterName2 value= value2 >
Methods of the OutputStream class: </applet>
destroy() Invoked by the browser or the setBackground() Sets the background color of the
appletviewer to inform that the component
applet has been reclaimed by the setForeground() Sets the foreground color of the
Garbage Collector component
getAppletContext() Determines the applet context or SetSize() Resizes the component
the environment in which it runs setLocation() Moves the component to a new
getImage() Returns an Image object that can location
be drawn on the applet window setBounds() Moves the component to specified
location and resizes it to the
getDocumentBase() Returns the URL of the HTML page specified size
that loads the applet addFocusListener() Registers a FocusListener
object to receive focus events
getCodeBase() Returns the URL of the applet’s from the component
class file addMouseListener() Registers a MouseListener
getParameter() Returns the value of a named object to receive mouse events
applet parameter as a string from the component
showStatus() Displays the argument string on addKeyListener() Registers a KeyListener object
the applet’s status to receive key events from the
component
getGraphics() Returns the graphics context of
java.awt.Graphics class: The Graphics class is an this component
abstract class that contains all the essential drawing methods update(Graphics g) Updates the component. Calls the
like drawLine(), drawOval(), drawRect() and so on. A paint() method to redraw the
Graphics reference is passed as an argument to the paint() component.
method that belongs to the java.awt.Component class.
Methods of the Graphics class: AWT Components: Many AWT classes like Button,
Checkbox, Label, TextField etc. are subclasses of the
Method Description java.awt.Component class. Containers like Frame and
drawLine() Draws a line between (x1,y1) and Panel are also subclasses of components, but can additionally
(x2,y2) passed as parameters hold other components.
drawRect()/fillRect() Draws a rectangle of specified
width and height at a specified
© 1999, Pinnacle Software Solutions Inc. 21 © 1999, Pinnacle Software Solutions Inc. 23
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
Label:
location
Constructors
drawOval()/fillOval() Draws a circle or an ellipse that · Label() - Creates an empty label
fills within a rectangle of specified · Label(String s) - Creates a label with left
coordinates justified text string
drawString() Draws the text given as a · Label (String s, int alignment) - Creates
specified string a label with the specified text and specified aligment.
drawImage() Draws the specified image onto Possible values for alignment could be Label.RIGHT,
the screen Label.LEFT, or Label.CENTER
drawPolygon()
/fillPolygon() Draws a closed polygon defined Methods of the Label class:
by arrays of x and y coordinates
Method Description
setColor() Sets the specified color of the
graphics context getAlignment() Returns an integer representing
the current alignment of the Label.
setFont() Sets the specified font of the 0 for left, 1 for center, and 2 for
graphics context right alignment.
setAlignment() Sets the alignment of the Label to
the specified one
java.awt.Component class: The Component class is an getText() Returns the label’s text as a
abstract class that is a superclass of all AWT components. A string
component has a graphical representation that a user can setText() Sets the label’s text with the
interact with. For instance, Button, Checkbox, specified string
TextField, and TextArea.
paint(Graphics g) Paints the component. The Button() - Creates a button without a label
Graphics context g is used for Button(String s) - Creates a button with the specified
painting. label
© 1999, Pinnacle Software Solutions Inc. 22 © 1999, Pinnacle Software Solutions Inc. 24
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
· Checkbox() - Creates a checkbox without any label getSelectedIndex() Returns the index number of the
· Checkbox(String s) - Creates a checkbox with a currently selected item
specified label
· Checkbox(String s, boolean state) - Creates getSelectedItem() Returns the currently selected item
a checkbox with a specified label, and sets the specified as a string
state
· Checkbox(String s, boolean state, insert() Inserts a specified item at a specified
CheckboxGroup cbg) - Creates a checkbox with a index position
specified label and specified state, belonging to a
specified checkbox group remove() Removes an item from the choice
menu at the specified index
© 1999, Pinnacle Software Solutions Inc. 25 © 1999, Pinnacle Software Solutions Inc. 27
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
setEchoChar() Sets the echo character for a text Methods of the List class:
field
getText() Returns the text contained in the Method Description
text field
setText() Sets the text for a text field add() Adds an item to the end of the
scrolling list
· TextArea() - Creates a new text area deselect() Deselects the item at the specified
· TextArea(int rows, int cols) - Creates a new index position
empty text area with specified rows and columns
· TextArea(String s) – Creates a new text area with the getItem() Returns the item at the specified
specified string index position
· TextArea(String s, int rows, int cols) - Creates
a new text area with the specified string and specified rows getItemCount() Returns the number of items in the
and columns. list
· TextArea(String s, int rows, int cols, int
scrollbars) - Creates a text area with the specified text, getSelectedIndex() Returns the index position of the
and rows, columns, and scrollbar visibility as specified. selected item
Methods of the TextArea class: getSelectedItem() Returns the selected item on the
scrolling list
Method Description
isMultipleMode() Determines if the scrolling
getText() Returns the text contained in the list allows multiple selection
text area as a string
remove() Removes a list item from a
setText() Sets the specified text in the text specified position
area
setMultipleMode() Sets a flag to enable or disable
getRows() Returns the number of rows in the multiple selection
© 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc.
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
Scrollbar:
Constructors
text area
getColumns() Returns the number of columns in · Scrollbar() - Creates a new vertical scroll bar
the text area · Scrollbar(int orientation) - Creates a new scroll
bar with a particular orientation, which is specified as
selectAll() Selects all the text in the text area Scrollbar.HORIZONTAL or Scrollbar.VERTICAL
· Scrollbar(int orientation, int value,
setEditable() A True value passed as an int visible, int minimum, int maximum)- Creates
argument enables editing of the a new scroll bar with the specified orientation, initial value,
text area, while False disables thumb size, minimum and maximum values
editing. It is True by default.
Methods of the Scrollbar class:
© 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc.
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
· Frame() - Creates a new frame without any title textValueChanged() Invoked whenever a Text
· Frame(String s) - Creates a new frame with the Event object is generated (text
specified title value changes)
Menus:
AdjustmentListener interface: Implemented by a class that
· Can be added only to a frame handles adjustment events. The method
· A MenuBar instance is first created as: adjustmentValueChanged(), overridden by the
MenuBar mb = new MenuBar(); implementing class is invoked everytime an AdjustmentEvent
· The MenuBar instance is added to a frame using the object occurs (when a scrollbar is adjusted).
setMenuBar() method of the Frame class as follows:
setMenuBar(mb); Interface method Description
· Individual menus are created (instances of the Menu class) adjustmentValueChanged() Invoked whenever an
and added to the menu bar with the add() method AdjustmentEvent object is
generated (when a scrollbar
Dialog: Direct subclass of java.awt.Window, which accepts thumb is adjusted)
user input.
ItemListener interface: Implemented to handle state change
events. The method itemStateChanged()must be overridden
by the implementing class.
© 1999, Pinnacle Software Solutions Inc. 33 © 1999, Pinnacle Software Solutions Inc. 35
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
© 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc. 36
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
keyTyped() Invoked whenever a key is typed windowDeactivated() Invoked when the window is no
longer the active window i.e. the
window can no longer receive
keyboard events
MouseListener interface: Implemented by a class handling
mouse events. It comprises of five methods invoked when a windowIconified() Invoked when a normal window is
MouseEvent object is generated. Its corresponding adapter minimized
class is the MouseAdapter class.
windowDeiconified() Invoked when a minimized
Method Description window is changed to normal
state
mouseClicked() Invoked when mouse is clicked
on a component
java.sql.Driver interface: Implemented by every driver
mouseEntered() Invoked when mouse enters a class.
component
Methods of the Driver interface:
mouseExited() Invoked when mouse exits a
component Method Description
mousePressed() Invoked when mouse button is acceptsURL() Returns a Boolean value indicating
pressed on a component whether the driver can open a
connection to the specified URL
mouseReleased() Invoked when mouse button is
released on a component connect() Tries to make a database connection
to the specified URL
MouseMotionListener interface: Implemented by a class getMajorVersion() Returns the driver’s major version
for receiving mouse-motion events. Consists of two methods – number
mouseDragged() and mouseMoved(), which is invoked
when a MouseEvent object is generated. getMinorVersion() Returns the driver’s minor version
MouseMotionAdapter is its corresponding adapter class. number
© 1999, Pinnacle Software Solutions Inc. 37 © 1999, Pinnacle Software Solutions Inc. 39
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
mouseMoved() Invoked when mouse is moved over Methods of the Connection interface:
a component
Method Description
WindowListener interface: Implemented by a class to
receive window events. It consists of seven different methods to Close() Immediately releases the database
handle the different kinds of window events, which are invoked and JDBC resources
when a WindowEvent object is generated. Its corresponding
adapter class is the WindowAdapter class. commit() Makes all changes since the last
commit/rollback permanent, and
Method Description releases the database locks held by
the connection
windowOpened() Invoked when the window is
made visible for the first time createStatement() Creates and returns a Statement
object. It is used for sending SQL
windowClosing() Invoked when the user attempts statements to be executed on the
to close the window from the database
Windows system menu
getMetaData() Returns a DatabaseMetaData
windowClosed() Invoked when the window has object that represents metadata
been closed as a result of calling about the database
the dispose() method
isReadOnly() Checks whether the connection is a
windowActivated() Invoked when the window is read-only connection
made active i.e. the window can
receive keyboard events prepareCall() Creates and returns a
Callable Statement object,
© 1999, Pinnacle Software Solutions Inc. 39 © 1999, Pinnacle Software Solutions Inc. 4
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
Method Description
Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference
© 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc.