ng message)
  • Error( )

    IllegalAccessError Extends IncompatibleClassChangeError

    IncompatibleClassChangeError Extends LinkageError

    InstantiationError Extends IncompatibleClassChangeError

    InternalError Extends VirtualMachineError

    LinkageError Extends Error

    NoClassDefFoundError Extends LinkageError

    NoSuchFieldError Extends IncompatibleClassChangeError

    NoSuchMethodError Extends IncompatibleClassChangeError

    OutOfMemoryError Extends VirtualMachineError

    StackOverflowError Extends VirtualMachineError

    ThreadDeath Extends Error

    Constructors
    ThreadDeath( )

    UnknownError Extends VirtualMachineError

    UnsatisfiedLinkError Extends LinkageError

    VerifyError Extends LinkageError

    VirtualMachineError Extends Error




    Chapter 15 -- Java Syntax Reference

    Chapter 15

    Java Syntax Reference


    CONTENTS


    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
         }

    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.

    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.

    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:
    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
        }
    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.

    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.

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

    native

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

    Syntax:
    native returnType methodName(optionlParameters)
    Example:

    native long sumSeries();

    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:
    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 {
              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

    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

    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 shou