Skip to main content

Section A.6 Statements

Subsection A.6.1 Declarations

There are two kinds of declaration statements: field declarations, which include a class's instance variables, and local variable declarations.

  • Put one statement per line, possibly followed by an end-of-line comment if the declaration needs explanation.

  • Initialize local variables when they are declared. Instance variables are given default initializations by Java.

  • Place variable declarations at the beginning of code blocks in which they are used rather than interspersing them throughout the code block.

The following class definition illustrates these points:

public class Example {
   private int size = 0;     // Window length and width
   private int area = 0;     // Window's current area

   public void myMethod() {
      int mouseX = 0;        // Beginning of method block
      if (condition) {
          int mouseY = 0;    // Beginning of if block
      } // if
   } // myMethod()
} // Example
You have attempted of activities on this page.