Java Syntax Reference
Java Syntax Reference
Handout 336895255.doc
1/17
Handout 336895255.doc
Operators
Assignment
Example:
Arithmetic
+
/
*
%
Addition
Subtraction
Division, ignoring remainder
Multiplication
Modulo, remainder of dividing x by y
Example
x++
y-x += 5
y -= 5
2/17
Handout 336895255.doc
/=
x *= 2
y /= 2
Boolean
!=
>
<
>=
<=
==
not equal to
greater than
less than
greater than or equal to
less than or equal to
equal to
Note that when testing equality of objects, use the equals method. E.g.
object1.equals(object2). This will test whether the objects are equal in
terms of their attributes, whereas using == will only test whether the two
variables are actually references to the same object.
Logical
Operator
&&
||
!
&
Description
Example
logical AND
A && B
logical OR
A || B
logical NOT (logical negation)
!A
boolean logical AND
true & true
(both operands must be booleans)
^
boolean logical exclusive OR
false ^ false
(both operands must be booleans)
|
boolean logical inclusive OR
true | false
(both operands must be booleans)
Note that similarly to the assignment operators, there are short forms available for
working with the logical operators. E.g. x |= y perform a logical OR of x and y
and then assigns this new value to x.
Shift
Operator
>>
<<
>>>
Use
Operation
shift bits of op1 right by distance op2
shift bits of op1 left by distance op2
shift bits of op1 right by distance op2 (unsigned)
3/17
Handout 336895255.doc
<variable
if( <condition>
name 1> )
= {
(<new type>)<variable
ifif(
(shoppingCart.isEmpty())
name
<condition>
2>; if
float
<variable>
myString
if(
) {&&
(x
myFloat;
<condition>
instanceof
y)
instanceof
{
) {
String
<classname>
<statementsToDoIfConditionTrue> {
<statementsToDoIfConditionTrue>
int
/* code
myInt;
<statementsToDoIfConditionTrue>
if true */
} else {
} else
/*
codeif(
is shopping
<otherCondition>
myFloat
}
}
cart
= (int)myInt;
empty
) {
<statementsToDoIfConditionFalse>}
<statementsToDoIfOtherConditionTrue>
}
else
} else {
{
<statementsToDoIfNoneAreTrue>
/*
} code if shopping cart is not empty
}
Casts
Example:
Casting does not change an object, just the type used to reference it.
Casting from one primitive type to another may cause some loss of precision.
When casting an object, if the cast is not legal then a ClassCastException
is thrown.
Instanceof
The instanceof operator checks whether one object is an instance of another,
Example:
Flow Of Control
If Statement
If-Else:
If-Else-If:
Examples:
4/17
Handout 336895255.doc
for (<counter
switch
<selector>
initialization>;
{
switch (shoppingCart.size())
//count
<loop
from one
continuation
to ten
condition>; <counter
increment>)
case <value
{ 1> :
{
for
(int i=1; i<10; i++) {
/* Java<statement
statements1>;
*/
case 1:
System.out.println(i);
}
break;
} {
case <value 2> :
showMessage(You have one item in your shopping cart);
<statement 2>;
break;
break;
}
case <value n> :
case 2:
<statement n>;
{
break;
showMessage(You have two items in your shopping cart);
default :
break;
<statement n+1>
}
break;
default:
}
{
showMessage(You have no items in your shopping cart);
}
}
Switch Statement
Example:
The break statement causes the program to proceed with the first statement after
the switch structure. The break statement is used because otherwise the
cases of the switch statement would otherwise run together. If break is not
used anywhere in a switch structure, then each time a match occurs in the
structure, the statements for all the remaining cases will be executed (or until a
break is encountered).
The <selector> for a select statement must be an integer, char, or an
enumerated type.
If the <selector> does not match any of the values, then the default statement
is executed.
For Loop
Example:
5/17
Handout 336895255.doc
satisfied, then the statements in the loop body are executed. Finally the
counter is incremented. The loop begins again by checking the <loop
continuation condition>. This process continues until the control
variable no longer satisfies the <loop continuation condition>.
The program then continues by performing the first statement after the loop.
A break statement inside a for loop causes the loop to end
A continue statement inside a for loop skips the remaining statements in
the body of that structure, and proceeds with the next iteration of the loop
While Loop
Example:
Variables
Primitive Data Types
There are eight primitive data types in Java
Type
Boolean
Description
A Boolean value (true or false)
Size
1 bit. true or
false
Byte
Short
Int
Long
Float
Double
Byte-length integer
Short integer
Integer
Long Integer
Single precision floating point
number
Double precision floating point
1 byte
2 bytes
4 bytes
8 bytes
4 bytes
8 bytes
6/17
Handout 336895255.doc
<modifiers> <data
<datatype>
type>[]
<variable
<array name>
name>;=<modifiers>
<expression>;
new
{<comma
<data
separated
type>[<array
<data type>[]
list of
size>];
<array name>;
values>};
<array name> = new <data type>[<array size>];
Char
number
A single character
2 bytes.
Unicode
character
As well as primitive types, Java has the notion of reference types. Arrays,
classes and interfaces are all reference types. I.e. they refer to an object in
memory rather than a primitive value. A reference type is equivalent to a pointer
in C, but the objects are referenced by name rather than memory location.
Declaring a Variable
or, to initialize the variable when its declared:
Declaring an Array
or, to allocate the size of the array when its declared:
or, to initialize the array when its declared:
Examples:
7/17
Handout 336895255.doc
final
private
//
<visibility
creates
<datatype>
int[]
amodifier>
five
myArray;
myArray
<constant
element
=//
static
new
declares
array
name>
int[20];
final
of
= <constant
the arrayand
integers
<datatype>
value>;
<constant
initializes
name> = com.mydomain.package1
myArray
//
<constant
the elements
= value>;
new int[20];
to 1, 2,
//3,
allocates
4, 5
the array to hold 20 ints
com.mydomain.package2
private int[] myArray = {1, 2, 3, 4, 5};
Declaring Constants
A class constant:
A constant variable inside an object or method:
Use class constants for global variables that must be shared by all instances of a
class.
Use constant variables inside an object to ensure that the variable is only ever
assigned a single value.
Packages
Naming
A package is a group of Java classes. All classes within a package must have a unique
name. The standard convention is to name packages using a reverse domain name
format. For example if I own the domain name mydomain.com then I would give my
packages names like
8/17
Handout 336895255.doc
This convention has arisen to avoid naming clashes in code created by different
companies.
Of course if you dont own a domain name then youre free to name your packages as
appropriate. Using the application name as a prefix is a good option. As a rule you should
always place your code in a package.
Note: when your code is compiled in Java classes, the Java compiler will organise the
classes into directories according to the package names. E.g. all classes in the
com.mydomain.package1 package will be compiled into the
com/mydomain/package1/ directory.
Defining a Package
The package statement must appear before any other Java statements in the file, or be
omitted entirely. If the package statement is omitted, then a file is assumed to be in the
default package, to which all package-less classes belong.
All files in the same package must use the same <package name>.
Importing a Package
Classes in a package must be referenced by their fully qualified class name (e.g.
com.mydomain.package1.MyClass) unless that package is imported.
9/17
Handout 336895255.doc
<modifiers>
public
classinterface
myClass extends
{<interface
<modifiers>
public
superClass
interface
class
name>
interface
class
MotorVehicle
extends
implements
myInterface
<class
<interface
<superinterface
name>
extends
myInterface
{ extends
name>
Vehicle
{
list>
<superclass
{ {
name> {
} Class
/*
instance
constants
variables
and*/
abstract
/*
}
Abstract
MY_CONSTANT
methods
methods
declared
= 10;
and class
here */
constants declared here */
} int
/* constructors */
}
} void myMethod();
/* methods */
}
}
Defining an Interface
Example:
Extending a Class
Example:
<class name> will inherit all non-private methods and instance variables
defined in <superclass name>. Thus the methods and instance variables
defined for <class name> need be only those things needed to specialize the
class.
A class that implements interfaces can also inherit from a superclass. The
superclass must be extended before the interfaces are implemented:
Extending an Interface
10/17
Handout 336895255.doc
public class
<modifiers>
interface
class
<return
myClass
myInterface
<class
types>
type>
implements
name>
<method
<method
extends
implements
myInterface
name>(<parameter
name>()
superInterface
<interface
{{
list>)
{list>{{
private void myMethod() {
/* statements
Class constants
Instance
variables
*/
anddeclared
abstractand
methods
methods
declared
defined
here
here
*/*/ /* statements */
}
}
Example:
Implementing an Interface
Example:
Methods
Defining a Method
Example:
11/17
Handout 336895255.doc
<parameter
public
voidtype1>
class
drawCircle(int
myClass
<parameter
{
radius,
name1>,
Color
<modifiers>
<variable
colour)
name>
{
<class
=Shape
new
name>(<parameter
<class
circle;
name>();
list>) {
<parameter
/*
/*
statements
Instance
type2>
*/ <parameter
variables
declared
name2>,
*/ /* statements to circle
initialize
= new
the
Shape();
object */
<parameter typeN> <parameter nameN> }
}
public myClass() { // the Constructor
/* statements to initialize objects of myClass */
}
}
Example:
A method can be overloaded. This means that multiple methods with the same
name but different parameter lists can be declared within the same class. The
JVM will determine the correct method to run by examining the parameters
passed used in the method call. Methods cannot be overloaded to have different
return types.
Constructors
Example:
Objects
Creating (Instantiating) an Object
Example:
Modifiers
There are various modifiers that can be applied when declaring classes, interfaces,
methods and variables. These are reviewed in the following sections. In some cases
modifiers have subtly different meaning depending on the type of structure (e.g. class or
method) to which theyre being applied.
L. Dodds, October 2002
12/17
Handout 336895255.doc
Visibility Modifiers
Visibility modifiers control the encapsulation of a class, its attributes and behaviours
Public
Protected
Private
None
13/17
Handout 336895255.doc
public<other
abstract
final
interface
class
<other
public
Circle
modifiers>
modifiers>
class
<interface
{ Shape
<data
<return
class
<return
class
name>
{
type>
<class
type>
<class
{type>
<constant
abstract
name>
<method
name>
<method
{ public
{ name>();
name>
name>(<parameter
=
void
<constant
animate();
final
final
list>)
value>;
int
void
constantNum
{myMethod()
= {
1;
/* Instance
Interface
Java
statements
variables
definition
*/ declared
here */and methods defined */
here */
here.
*/ /* Java statements */
}
}
Example:
14/17
Handout 336895255.doc
publicclass
final
static
<modifiers>
<other
void
myClass
<return
myMethod()
modifiers>
{ throws
type>
<return
<data
<method
Exception
type>
type>
name>(<parameter
<variable
<method
{
name>(<parameter
name>;
list>) throws
staticlist>)
<list
voidmyNumber;
int
myMethod()
{
{
of Java
/*
Instance
Throwables>
statements
variables
{
here
*/
declared
*/
and methods defined here *//* Java statements */
/* Java statements */
}
}
}
The final modifier can be used with variables to create constants. A value must
be assigned to the variable at declaration, and then cannot be changed. See also
Declaring Constants
A final method cannot be redefined in a subclass.
A final class cannot be subclassed.
Exceptions
Declaring a method to throw an Exception
Example:
Every method that throws exceptions should declare what exceptions it throws
in the method declaration. A method that calls another method must handle the
exceptions thrown by that method.
<list of Throwables> is a space-separated list of the class Throwable
and its subclasses.
15/17
Handout 336895255.doc
try { e;
throw
new//
<Throwable>;
where e is an
if instance
try
/*
//
/**
(problemEncountered)
This
{
is also
aof
comment.
the
a comment.
Throwable
Useful
Useful
class
for commenting
for
or one
commenting
ofaits
block
a single
of code*/
line
subclasses
/*
Statements which may{throw
readFile();
*
Thisan
isexception
a comment*/
which will appear in the
}
throw
}
* auto-generated
new Exception();
documentation produced by Javadoc.
catch(<Throwable> <exception
}* If handler
catch
(Exception
it
appears
1>)before
e)
{ {
a class, method or constant
/* Statements to do if an
/*exeption
*
declaration
Statements
of type
to doThrowable
if problem
1 is
encountered
thrown */reading file */
}
log(Problem reading file);
*/
finally {
}
/* Statements to do regardless
finally of
{ whether or not an exception is thrown.
*/
closeTheFile();
}
}
Throwing an Exception
or
Example:
The basic structure is: try to do something, catch exceptions that signal
problems, finally do some clean-up.
It is legal to have multiple catch blocks, each of which handle a specific type of
exception.
Its possible to omit the catch block and just have a tryfinally structure. This is
recommended where some clean-up is essential and must be done even if the
JVM encounters problems.
Miscellaneous
Comments
Keywords
A summary of the Java keywords. Note that const and goto are reserved but are not
actually implemented.
L. Dodds, October 2002
16/17
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
final
finally
float
for
goto
Handout 336895255.doc
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
Legal Names
17/17