Vous êtes sur la page 1sur 14

Chapter 15 -- Java Syntax Reference Page 1 of 14

Chapter 15
Java Syntax Reference

CONTENTS
l Modifiers

This section serves as a reference for the Java language itself. All keywords and operators in the
language are listed in alphabetical order, each followed by a complete explanation of the term, its
syntax, and an example of how it might be used in actual code. Further, for ease of identification, the
terms are set in bold in the code samples.

abstract

An abstract class or method is one that is not complete. Interfaces are automatically abstract.

Syntax:

abstract class className {


abstract returnType methodName(optionalParameters);

Example:

abstract class Grapher

abstract void displayImage(Image im);

break

This is used to exit a loop.

Syntax:

break;

Example:

while (true) {
if ( connection.isClosed() )
break;
else
// code goes here

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 2 of 14

catch

The catch statement is used to handle any exceptions thrown by code within a try block.

Syntax:

try {
statement(s)
}
catch(Exception list) {
statement(s)
}

Example:

InputStream in;
int val;
...
try {
val = in.read() / in.read();
}
catch(ArithmeticException e) {
System.out.println("Invalid data. val set to 0.");
val = 0;
}

catch(Exception e) {
System.out.println("Exception encountered, but not handled.");
}

class

This is used in a class declaration to denote that the following code defines a class.

Syntax:

modifiers class className extends SuperClassName


implements InterfaceNames

Example:

class MyClass

public class GraphAnimator extends Applet

public class Calculator implements Runnable, Cloneable

continue

This returns the program to the top of a loop.

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 3 of 14

Syntax:

continue;

Example:

Enumeration enum;
Object value;
...
while ( enum.hasMoreElements() ) {
value = enum.nextElement();
if ( value.equals("Invalid") )
continue;
else
System.out.println( value);
}

do…while

This is used to perform operations while a condition is met. The loop body will be executed at least
once.

Syntax:

do

statement(s)
while (booleanVariable);
do

statement(s)
while (booleanExpression);

Example:

do {

val = in.readByte();
System.out.println(val);
} while (val != '\n');
boolean valid = true;

do {
val = in.readByte();
if (val == '\n')
valid = false;
else
System.out.println(val);
} while (valid);

else

This is used in conjunction with the if statement to perform operations only when the requirements of
the if statement are not met.

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 4 of 14

Syntax:

if (booleanVariable)
statement(s)
else
statement(s)
if (booleanExpression)
statement(s)
else
statement(s)

Example:

if (stillRunning) {
System.out.println("Still Running");
advanceCounter();
}

else {
System.out.println("We're all done.");

closeConnection();
}

if (size >= 5)
System.out.println("Too big");

else
System.out.println("Just Right");

extends

This is used to make the current class or interface a subclass of another class or interface.

Syntax:

modifiers class className extends superClassName

interface interfaceName extends superInterfaceName

Example:

public class Clock extends Applet

public interface carefulObserver extends Observer

final

The final modifier makes a class or method final, meaning that it cannot be changed in a subclass.
Interfaces cannot be final.

Syntax:

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 5 of 14

final class className

final returnType methodName(optionalParameters)

Example:

final class LogoAnimator

final Color getCurrentColor()

finally

The finally statement is used in error handling to ensure the execution of a section of code. Regardless
of whether an exception is thrown within a try statement, the code in the finally block will be executed.

Syntax:

try {
statement(s)
}
finally {

cleanUpStatement(s)
}
try {
statement(s)
}
catch (Exception) {
exceptionHanldingStatement(s)
}
finally {

cleanUpStatement(s)
}

Example:

public static void testMath(int numerator, int divisor) throws


ArithmeticException {
try {

if (divisor == 0)
throw new ArithmeticException("Division by Zero.");
}
finally {
System.out.println("The fraction was " + numerator + "/" +
divisor);
}

}
try {
percent_over = quantity / number_ordered * 100; // could cause
division by 0
}

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 6 of 14

catch (ArithmeticException e) {
percent_over = 0;
}
finally { // regardless of the success of the try, we still need to
print the info
System.out.println("Quantity = " + quantity);
System.out.println("Ordered = " + ordered);
System.out.println("Percent Over = " + percent_over);
}

for

This is used to execute a block of code a specific number of times.

Syntax:

for (counterInitialization ; counterCheck ;


counterChange)
statement(s)

Example:

String name;
...

for (pos = 0; pos < name.length(); I++)


System.out.println(name.charAt(i));

if

This is used to perform operations only if a certain condition is met.

Syntax:

if (booleanVariable)
statement(s)

if (booleanExpression)
statement(s)

Example:

if (ValidNumbersOnly)
checkInput(Answer);
if (area >= 2*PI) {
System.out.println("The size of the loop is still too big.");
reduceSize(area);
}

implements

This is used to force a class to implement the methods defined in an interface.

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 7 of 14

Syntax:

modifiers class className implements interfaceName

Example:

public class Clock implements Runnable, Cloneable

import

This is used to include other libraries.

Syntax:

import packageName;

import className;

import interfaceName;

Example:

import java.io.*;

import java.applet.Applet;

import java.applet.AppletContext;

instanceof

The instanceof operator returns true if the object to the left of the expression is an instance of the
class to the right of the expression.

Syntax:

object instanceof ClassName

Example:

void testType(Object instance) {


if (instance instanceof String) {
System.out.println("This is a string.")
System.out.println("It is " +
((String)i).length() ); // casts the Object to a
String first

Modifiers
Access modifiers are used to control the accessibility and behavior of classes, interfaces, methods, and
fields.

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 8 of 14

Modifier Effect on Classes Effect on Methods Effect on Fields


none (friendly) Visible to subclasses Can be called by Accessible only to
and classes within the methods belonging to classes within the
same package. classes within the same same package.
package.
Public Visible to subclasses Can be called by Accessible to
and other classes methods in subclasses subclasses and all
regardless of their and all classes classes regardless of
package. Regardless of their their package.
package.
Private Classes cannot be Can only be called by Accessible only to
private. methods within the methods within the
current class. current class.
Static Not applicable to Method is shared by all Field is shared by all
classes. instances of the current instances of the
class. current class.
Abstract Some methods are not Contains no body and Not applicable to
defined. These methods must be overridden in fields.
must be implemented in subclasses.
subclasses.
final The class cannot be The method cannot be Variable's value
used as a Superclass. overridden inany cannot be changed.
subclasses.
Native Not applicable to This method's Not applicable to
classes. implementation will be fields.
defined by code written
in another language.
Synchronized Not applicable to This method will seize Not applicable to
classes. control of the class fields.
while running. If
another method has
already seized control,
it will wait until the
first has completed.

native

A native method will be defined by code written in another language.

Syntax:

native returnType methodName(optionlParameters)

Example:

native long sumSeries();

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 9 of 14

new

The new operator allocates memory for an object, such as a String, a Socket, an array, or an instance of
any other class.

Syntax:

dataType arrayName[] = new dataType[ number ];


dataType fieldName = new dataType( constructor parameters)

Example:

int sizes[] = new int[9];


String name = new String("Hello");

package

This is used to place the current class within the specified package.

Syntax:

package packageName;

Example:

package java.lang;
package mytools;

public

public makes the class, method, or field accessible to all classes.

Syntax:

public class className;


public interface interfaceName;
public returnType methodName(optionalParameters)
public dataType fieldName;

Example:

public class GraphicsExample;


public interface Graph;
public boolean checkStatus(int x, int y)
public int size;

private

The private modifier makes the method or field accessible only to methods in the current class.

Syntax:

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 10 of 14

public returnType methodName(optionalParameters)


public dataType fieldName;

Example:

public int changeStatus(int index);


public int count;

return

The return statement is used to return a value from a method. The data type returned must correspond
to the data type specified in the method declaration.

Syntax:

return value;

Example:

float calculateArea(float circumference) {


float radius, area;
radius = circumference / (2 * PI);
area = radius * radius * PI;
return(area);
}

static

The static modifier makes a method or field static. Regardless of the number of instances that are
created of a given class, only one copy of a static method or field will be created.

Syntax:

static returnType methodName(optionalParameters)


static dataType fieldName;

Example:

static void haltChanges(optionalParameters)


static Color backgroundColor;

A static block is a set of code that is executed immediately after object creation. It can only handle
static methods and static fields.

Syntax:

static
statement(s)

Example:

static {

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 11 of 14

type = prepare();
size = 25;
}

super

This is used to refer to the superclass of this class.

Syntax:

super

super.methodName()
super.fieldName

Example:

class FloorManager extends Manager {


FloorManager() {
type = floor;
super(); // calls the Manager constructor
}
void organize() {
size = name.getSize();
super.organize(size); // calls the organize method in the
Manager method
.... }
}

switch

The switch statement is a conditional statement with many options.

Syntax:

switch (variableName) {
case (valueExpression1) : statement(s)
case (valueExpression2) : statement(s)
default : statement(s)
}

Example:

char ans;
...
switch (ans) {
case 'Y' : startOver();
break;
case 'n' ;
case 'N' : cleanUp();
default : System.out.println("Invalid response.");
}

synchronized

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 12 of 14

Every object has a "lock" that can be seized by an operation. Any synchronized operation seizes this
lock, preventing other synchronized processes from beginning until it has finished.

Syntax:

Synchronized Method:
synchronized returnType methodName(optionalParameters)
synchronized (objectName)
statement(s)

Example:

synchronized void changeValues(int size, int shape, String name)


synchronized (runningThread) {
runningThread.name = newName;
}

this

this is used to refer to the current class.

Syntax:

this
this.methodName()
this.fieldName

Example:

ticker = new Thread(this);

throw

The throw statement is used to throw an exception within the body of a method. The exception must be
a subclass of one of the exceptions declared with the throws statement in the method declaration.

Syntax:

throw exceptionObject

Example:

float calculateArea(float radius) throws


IllegalArgumentException {
if (radius < 0)
throw(new IllegalArgumentException("Radius less than 0.");
else
return(radius*radius*PI);
}

throws

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 13 of 14

The throws keyword specifies the types of exceptions that can be thrown from a method.

Syntax:

modifiers returnType methodName(optionalParameters) throws ExceptionNames

Example:

String getName(InputStream in) throws IOException

try

The try statement is used to enclose code that can throw an exception. It should be used with the catch
() statement and may be used with the finally statement.

Syntax:

try
statement(s)
catch(Exception list)
statement(s)
finally
statement(s)

Example:

InputStream in;
int val;
...
try
val = in.read() / in.read();
catch(ArithmeticException e) {
System.out.println("Invalid data. val set to 0.");
val = 0;
}
catch(Exception e)
System.out.println("Exception encountered, but not handled.");
finally {
in.close();
System.out.println("Stream closed.");

while

This is used to perform a loop operation while a certain condition is met.

Syntax:

while (booleanVariable)
statement(s)

while (booleanExpression)

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004
Chapter 15 -- Java Syntax Reference Page 14 of 14

statement(s)

Example:

FileInputStream din;
byte info;

while (info = din.read() != -1) // End of File


System.out.println(info);
while (stillValidData) {
info = din.read();
stillValidData = checkData(info); // returns false if data is not
valid
}

http://docs.rinet.ru/ProPauk/ch15.htm 12/4/2004

Vous aimerez peut-être aussi