Java-Variables

Variables

A variable is an identifier that denotes a storage location in which a value is stored. A variable may take different values during the execution of a program. Since Java is case-sensitive, uppercase letters and lowercase letters are distinct in Java. Thus the variable name sum is not the same as the variable name Sum.

DataType

Every variable has a data type. The variety of data types available allow the programmer to select the type appropriate to the needs of the application. The four basic data types are integer, float or real, character and boolean. A variable’s data type specifies the size and type of value that can be assigned to that variable. Every variable is the name of a storage location. Since the storage size depends on the data type of a variable.

Integer

An integer is always a whole number. It can be either positive or negative. This data type is further subdivided into four types, namely byte, short, int and long on the basis of their sizes. The minimum and maximum possible values for each one of these four data types are furnished in the following table :

Type Size Minimum Possible Value Maximum Possible Value
byte 1 byte -128 127
short 2 byte -23,768 -23,767
int 4 byte -2,147,483,648 -2,147,483,647
long 8 byte -9,223,372,036,854,775,808 -9,223,372,036,854,775,807

Variable Declaration

The Java compiler fixes the size of a storage location and the type of value to be stored in it on the basis of the information it receives from a Variable declaration statement. For example :

This statement informs the Java compiler that the variable mark is of int type and the storage location that stores the value of mark should be of size 4 bytes.

Variable Initialization

You assign to a previously declared variable by using the variable name on the left , an equal sign (=), and then some java expression that has an appropriate value on the right. For example :

You can both declare and initialize a variable on the same line. For example :

Program

Program Source

class Javaapp {

    public static void main(String[] args) {
        
        byte  by = 50;
        
        short sh = 100;
        
        int   in = 200;
        
        long  lo = 400;

        System.out.println("byte  by = "+by);
        System.out.println("short sh = "+sh);
        System.out.println("int   in = "+in);
        System.out.println("long  lo = "+lo);
    }
}

Leave a Comment