Skip to main content
Lesson 3 - Data Types in Java
Lesson MenuPreviousNext
  
Declaring and Initializing Variables in Java page 5 of 11

  1. A variable must be declared before it can be initialized with a value. The general syntax of variable declarations is:

    data_type  variableName;

    for example

    int number;
    char ch;
  2. Variables can be declared near the top of the method or in the midst of writing code. Variables can also be declared and initialized in one line. The following example program illustrates these aspects of variable declaration and initialization.

    Program 3-1

    public class DeclareVar
    {
      public static void main(String[] args)
      {
        // first is declared and initialized
        // second is just initialized
        int first = 5, second; 
        double x;
        char ch;
        boolean done;
    
        second = 7;
        x = 2.5;
        ch = 'T';
        done = false;
    
        int sum = first + second;
      }
    }
    
    1. Multiple variables can be declared on one line.
    2. Initialization is accomplished with an equal (=) sign
    3. Initialization can occur at declaration time or later in the program. The variable sum was declared and used in the same line.

  3. Where the variables are declared is a matter of programming style. Your instructor will probably have some preferences regarding this matter.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.