Java Statements

Home Up Search Java 2 API C++ Resources

Since the Java expression language is not very rich, Java programs express computations as sequences of statements rather than as compound expressions. The most common form of Java statement is an assignment statement

type var = expr ;

where type is a Java type name, var is a Java variable name, and expr is an expression of type compatible with the type of var. The assignment statement

int x = 5;

asserts that ``the variable x has value 5''.


Finger Exercise 1.3.4.1: In the DrJava Interactions pane, try evaluating the following statements and expressions:

int x = 5;
x*x
double d = .000001;
double dd = d*d;
dd
dd*dd
1. + dd
1. + dd*dd

Did you get the answers that you expected?

Java variable names and type names must be identifiers. An identifier is any sequence of ``alphanumeric characters'' (letters, digits, and _) beginning with a letter or _--except for the following keywords, which are reserved and may not be used as variable names or type names:

abstract    default     if          private     throw
boolean     do          implements  protected   throws
break       double      import      public      transient
byte        else        instanceof  return      try
case        extends     int         short       void
catch       final       interface   static      volatile
char        finally     long        super       while
class       float       native      switch
const       for         new         synchronized
continue    goto        package     this

Java is case-sensitive; the variable X is distinct from the variable x. There are three kinds of variables in Java: fields, method parameters, and local variables.   See the section on declaring variables.

Java includes all of the basic statement forms found in the C programming language expressed in essentially the same syntax.  Although Java accepts most C syntax, many common C constructions are considered bad style in Java.

 

(Written by Corky Cartwright.   Modified by Stephen Wong)