JAVA Programming Guide - Quick Reference.pdf
(
104 KB
)
Pobierz
172034261 UNPDF
Java Programming Guide - Quick Reference
Java Programming Guide - Quick Reference
Syntax for a standalone application in Java:
Java Comments:
class <classname>
{
Delimiters Use
// Used for commenting a single line
public static void main(String args[])
{
statements;
————————;
————————;
}
}
/* ————— */ Used for commenting a block of code
/** —————*/ Used for commenting a block of code.
Used by the Javadoc tool for
generating Java documentation.
Primitive datatypes in Java:
Steps to run the above application:
1. Type the program in the DOS editor or notepad. Save the
file with a .java extension.
2. The file name should be the same as the class, which has the
main method.
3. To compile the program, using javac compiler, type the
following on the command line:
Syntax:
javac <filename.java>
Example:
javac abc.java
4. After compilation, run the program using the Java
interpreter.
Syntax:
java <filaname>
(without the .java
extension)
Example:
java abc
5. The program output will be displayed on the command line.
DataType Size Default Min Value
Max Value
byte
(Signed
-128
integer) 8 bits 0
+127
short
(Signed
-32,768
integer) 16 bits 0
+32,767
int
(Signed
-2,147,483,648
integer) 32 bits 0
+2,147,483,647
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
Java reserved words:
abstract default if package this
boolean do implements private throw
Break double import protected throws
Byte else instanceof public transient
case extends int return null
try Const for new switch
continue while goto
float 32 bits 0.0 1.4E-45
(IEEE 754
3.4028235E38
floating-point)
synchronized super
double 64 bits 0.0 4.9E-324
(IEEE 754 1.7976931348623157E308
floating-point)
Catch final
interface short
void
char finally long
static
volatile
class float
native
char 16 bits \u0000 \u0000
(Unicode
character)
Java naming conventions:
\uFFFF
boolean 1 bit false
Variable Names: Can start with a letter, ‘$’ (dollar symbol),
or ‘_’ (underscore); cannot start with a number; cannot be a
reserved word.
Method Names: Verbs or verb phrases with first letter in
lowercase, and the first letter of subsequent words
capitalized; cannot be reserved words.
Example:
setColor()
Variable Declaration:
<datatype> <variable name>
Example:
int num1;
Variable Initialization:
<datatype> <variable name> = value
Example:
double num2 = 3.1419;
Class And Interface Names: Descriptive names
that begin with a capital letter, by convention; cannot be a
reserved word.
Escape sequences:
Literal
Represents
Constant Names: They are in capitals.
Example:
Font.BOLD, Font.ITALIC
\n
New line
\t
Horizontal tab
\b
Backspace
\r
Carriage return
© 1999, Pinnacle Software Solutions Inc.
2
© 1999, Pinnacle Software Solutions Inc.
4
Java Programming Guide - Quick Reference
Java Programming Guide - Quick Reference
\f
Form feed
5. Switch statement
Syntax:
switch(variable)
{
case(value1):
statements;
break;
case(value2):
statements;
break;
default:
statements;
break;
}
\\
Backslash
\”
Double quote
\ddd
Octal character
\xdd
Hexadecimal character
\udddd
Unicode character
Arrays: An array which can be of any datatype, is created in
two steps – array declaration and memory allocation.
Array declaration
<datatype> [] <arr ```````````ayname>;
Examples
int[] myarray1;
double[] myarray2;
Memory Allocation
The
new
keyword allocates memory for an array.
Syntax
<arrayname> = new <array type> [<number of
elements>];
Examples
myarray1 = new int[10];
Myarray2 = new double[15];
Class Declaration: A class must be declared using the
keyword
class
followed by the class name.
Syntax
class <classname>
{
———— Body of the class
A typical class declaration is as follows:
<modifier> class <classname> extends
<superclass name> implements <interface name>
{
—————Member variable declarations;
—————Method declarations and definitions
}
Multi-dimensional arrays:
Syntax:
<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
Flow Control:
Member variable declarations:
1. If……..else statements
Syntax:
if(condition)
{
statements;
}
else
{
statements;
}
<access specifier> <static/final/transient/
volatile> <datatype> <variable name>
Example
public final int num1;
Method declarations:
<access specifier> <static/final> <return type>
<method name> <arguments list>
{
Method body;
}
Example
public static void main(String args[])
{
}
2. For loop
Syntax:
for(initialization; condition; increment)
{
statements;
}
Interface declaration: Create an interface. Save the file
with a.java extension, and with the same name as the
interface. Interface methods do not have any implementation
and are abstract by default.
3. While loop
Syntax:
while(condition)
{
statements;
}
Syntax
interface <interface name>
{
void abc();
void xyz();
}
4. Do….While loop
Syntax:
do
{
statements;
}
while(condition);
Using an interface: A class implements an interface with the
implements
keyword.
© 1999, Pinnacle Software Solutions Inc.
6
© 1999, Pinnacle Software Solutions Inc.
8
Java Programming Guide - Quick Reference
Java Programming Guide - Quick Reference
Syntax
class <classname> extends <superclass name>
implements <interface name>
{
class body;
—————————;
}
final
Class
Cannot be subclassed.
Method
Cannot be overridden.
Variable
Value cannot be changed
(Constant)
Creating A Package:
native
Method
Implemented in a language
other than Java like C,C++,
assembly etc. Methods do not
have bodies.
1. Identify the hierarchy in which the
.class
files have to
be organized.
2. Create a directory corresponding to every package, with
names similar to the packages.
3. Include the package statement as the first statement in
the program.
4. Declare the various classes.
5. Save the file with a .java extension.
6. Compile the program which will create a .class file in
the same directory.
7. Execute the .class file.
static
Method
Class method. It cannot refer to
nonstatic variables and methods
of the class. Static methods are
implicitly final and invoked
through the class name.
Variable Class variable. It has only one
copy regardless of how many
instances are created. Accessed
only through the class name.
Packages and Access Protection:
Accessed
Public Protected Package Private
From the
same class ?
synchronized
Method
A class which has a synchronized
method automatically acts as a
lock. Only one synchronized
method can run for each class.
Yes
Yes
Yes
Yes
From a non
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
List of exceptions in Java(part of java.lang package):
From a non
subclass
outside the
package?
Essential exception classes include -
Yes
No
No
No
Exception Description
From a
subclass
in the same
package?
ArithmeticException
Caused by exceptional
conditions like divide by
zero
Yes
Yes
Yes
No
ArrayIndexOfBounds
Thrown when an array is
Exception
From a
subclass
outside the
package ?
accessed beyond its bounds
Yes
Yes No No
ArrayStoreException
Thrown when an incompatible
type is stored in an array
ClassCastException
Thrown when there is an invalid
cast
Attribute modifiers in Java:
IllegalArgument
Thrown when an inappropriate
Exception
argument is passed to a method
Modifier Acts on Description
abstract Class Contains abstract
methods.Cannot
be instantiated.
IllegalMonitorState
Illegal monitor operations such as
Exception
waiting on an unlocked thread
Interface All interfaces are implicitly
abstract. The modifier is
optional.
IllegalThreadState
Thrown when a requested
Exception
operation is incompatible with
the current thread state.
Method
Method without a body.
Signature is followed by a
semicolon. The class must also
be abstract.
IndexOutOfBounds
Thrown to indicate that an index
Exception
is out of range.
NegativeArraySize
Thrown when an array is created
Exception
with negative size.
© 1999, Pinnacle Software Solutions Inc.
10
© 1999, Pinnacle Software Solutions Inc.
12
Java Programming Guide - Quick Reference
Java Programming Guide - Quick Reference
NullPointerException
Invalid use of a null reference.
setPriority()
Changes the priority of the thread
NumberFormatException
Invalid conversion of a string to a
number.
currentThread()
Returns a reference to the
currently executing 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
interface.
try
{
//code to be tried for errors
}
catch(ExceptionType1 obj1)
{
//Exception handler for ExceptionType1
}
catch(ExceptionType2 obj2)
{
//Exception handler for ExceptionType2
}
finally{
//code to be executed before try block ends.
This executes whether or not an //
exception occurs in the try block.
}
IllegalAccess
Thrown when a method does not
Exception
have access to a class.
Instantiation
Thrown when an attempt is made
Exception
to instantiate an abstract class or
an interface.
InterruptedException
Thrown when a second thread
interrupts a waiting, sleeping, or
paused thread.
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
either (i) extend the Thread class or (ii) implement the Runnable
interface. In both cases, the
run()
method defines operations
I/O class name
Description
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
performed by the thread.
Methods of the Thread class:
input. Supports
mark()
and
reset()
methods.
BufferedOutputStream Provides the ability to write bytes
to the underlying output stream
without making a call to the
underlying system.
Methods
Description
run()
Must be overridden by
Runnable
object; contains code
that the thread should perform
BufferedReader
Reads text from a character
input stream
start()
Causes the
run
method to
execute and start the thread
BufferedWriter
Writes text to character
output stream
sleep()
Causes the currently executing
thread to wait for a specified time
before allowing other threads to
execute
DataInputStream
Allows an application to read
primitive datatypes from an
underlying input stream
DataOutputStream
Allows an application to write
primitive datatypes to an output
stream
interrupt()
Interrupts the current thread
File
Represents disk files and
directories
Yield()
Yields the CPU to other runnable
threads
FileInputStream
Reads bytes from a file in a file
system
getName()
Returns the current thread’s name
FileOutputStream
Writes bytes to a file
ObjectInputStream
Reads bytes i.e. deserializes
objects using the
readObject()
method
getPriority()
Returns the thread’s priority as an
integer
ObjectOutputStream
Writes bytes i.e. serializes
objects using the
writeObject()
method
isAlive()
Tests if the thread is alive; returns
a Boolean value
PrintStream
Provides the ability to print
different data values in an
efficient manner
join()
Waits for specified number of
milliseconds for a thread to die
RandomAccessFile
Supports reading and writing to
a random access file
setName()
Changes the name of the thread
© 1999, Pinnacle Software Solutions Inc.
14
© 1999, Pinnacle Software Solutions Inc.
16
Java Programming Guide - Quick Reference
Java Programming Guide - Quick Reference
StringReader
Character stream that reads
from a string
getName()
Returns the name of the file and directory
denoted by the path name
isDirectory()
Tests whether the file represented by the
pathname is a directory
lastModified()
Returns the time when the file was last
modified
l
length()
Returns the length of the file represented by
the pathname
listFiles()
Returns an array of files in the directory
represented by the pathname
setReadOnly()
Marks the file or directory so that only
read operations can be performed
renameTo()
Renames the file represented by the
pathname
delete()
Deletes the file or directory represented by
the pathname
canRead()
Checks whether the application can read
from the specified file
canWrite()
Checks whether an application can write to
a specified file
StringWriter
Character stream that writes to
a
StringBuffer
that is later
converted to a String
The java.io.InputStream class: The
InputStream
class is
at the top of the input stream hierarchy. This is an abstract class
which cannot be instantiated. Hence, subclasses like the
DataInputStream
class are used for input purposes.
Methods of the InputStream class:
Method Description
available()
Returns the number of bytes that can be
read
close()
Closes the input stream and releases
associated system resources
mark()
Marks the current position in the input
stream
Creating applets:
mark
Supported()
Returns true if mark() and reset() methods
are supported by the input stream
1. Write the source code and save it with a .java
extension
2. Compile the program
3. Create an HTML file and embed the
.class
file with the
<applet>
tag into it.
4. To execute the applet, open the HTML file in the browser
or use the appletviewer utility, whch is part of the Java
Development Kit.
read()
Abstract method which reads the next byte
of data from the input stream
read(byte b[])
Reads bytes from the input stream and
stores them in the buffer array
© 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
input stream
The <applet> tag:
Code, width
, and
height
are
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
its value.
Syntax:
<applet code = “abc.class” height=300
width=300>
<param name=parameterName1 value= value1 >
<param name=parameterName2 value= value2 >
</applet>
The java.io.OutputStream class: The
OutputStream
class
which is at the top of the output stream hierarchy, is also an
abstract class, which cannot be instantiated. Hence, subclasses
like
DataOutputStream
and
PrintStream
are used for
output purposes.
Methods of the OutputStream class:
Method
Description
Using the Appletviewer: Appletviewer.exe is an
application found in the BIN folder as part of the JDK. Once an
HTML file containing the class file is created (eg.
abc.html)
,
type in the command line:
Appletviewer abc.html
close()
Closes the output stream, and releases
associated system resources
write(int b)
Writes a byte to the output stream
java.applet.Applet class:
write(byte b[])
Writes bytes from the byte array to the
output stream
Methods of the java.applet.Applet class:
flush()
Flushes the ouput stream, and writes
buffered output bytes
Method
Description
init()
Invoked by the browser or the
applet viewer to inform that the
applet has been loaded
java.io.File class: The
File
class abstracts information
about files and directories.
start()
Invoked by the browser or the
applet viewer to inform that
applet execution has started
Methods of the File class:
stop()
Invoked by the browser or the
applet viewer to inform that
applet execution has stopped
Method
Description
exists()
Checks whether a specified file exists
© 1999, Pinnacle Software Solutions Inc.
18
© 1999, Pinnacle Software Solutions Inc.
20
Plik z chomika:
musli_com
Inne pliki z tego folderu:
Big Java Late Objects [Horstmann 2012-02-01].pdf
(167477 KB)
Data Structures_ Abstraction and Design using Java (2nd ed.) [Koffman & Wolfgang 2010-01-26].pdf
(190252 KB)
Big Java Early Objects (5th ed.) [Horstmann 2013-01-04].pdf
(145099 KB)
Data Abstraction and Problem Solving with Java_ Walls and Mirrors (3rd ed.) [Prichard & Carrano 2010-10-30] (photocopier quality).pdf
(110506 KB)
A Little Java, a Few Patterns [Felleisen & Friedman 1997-12-19].pdf
(14847 KB)
Inne foldery tego chomika:
3D Design - Programming
ActionScript
Actionscript - Flash - Flex - Air
Ada
ADO
Zgłoś jeśli
naruszono regulamin