Course Content‎ > ‎Session 2‎ > ‎

Declaration of Variables

Syntax for Declaring Variables in Java

The syntax for declaring a variable in a Java program is:

    Datatype Variablename;

This is a declaration statement, which tells the compiler to set aside memory for a variable Variablename, which is of type Datatype. We declare variables like this:

    String name;  
    int age;  
    char alphabet; 

In the above statements, there are three variables, which are declared to be of data types String, int and char

Data type is the most fundamental concept of any programming language. Data type of a variable determines how much memory should be set aside for that variable.  Data type of a variable will determine, how the compiler will interpret the contents of that memory location, that is represented by that variable name. In Java, a variable has to be declared, before it can be used in the program. 

Key Points Regarding the Variable Declaration

  • Variable declaration tells the compiler, what the variable name is.
  • It specifies what type of data the variable will hold.
  • The place where the variable is declared, decides the scope of the variable.
  • A variable must be declared, before it is used in the program.
  • A variable can be used to store a value of any data type i.e. the name of variable has nothing to do with the data type of   the variable.
  • You cannot declare the same variable name for two different data types. For example, 
         int Section;
         char Section;

The above variable declaration is invalid because the variable name Section is already defined as of type int. So the variable name Section of type char is an invalid declaration.
  • You can also declare multiple variables of the same type in the same line. The syntax will be:
         DataType variable1, variable2, variable3...........;

     For example:

         int  Score1, Score2, Total;

In Java you can put the declarations anywhere in your code, but you can declare a variable only once in any block in a method. A variable has to be declared before it can be used in a program. Java is a strongly typed language. This means that when a variable is declared, you must specify its data type. There are eight fundamental or primitive data types in Java. These data types are built-in or intrinsic in Java and they are not derived from any other types. Let's look at these data types in the next part of this session.
Comments