Java – Variables

Java – Variables 2017-08-09T09:18:53+00:00

Java Variables:

The variable is the basic unit of storage in a Java program. A variable is defined by
the combination of  a type, an identifier and an optional initializer.
type is a data type or the name of a class or interface (class and interface will discussed further).for identify the type of variable identifier is a variable name.and optional initializermeans users directly initialize the value to the variable if they want.

Declare Variable

Now how we can declare a variable in java?

Syntax for declaring a variable is…

type identifier1=val , identifier2;

Ex.

int a=100, b;  //initialize a and declare b.

byte z = 22;   // initialize z.

double pi = 3.14159;   // declares an approximation of pi.

char x = ‘x’;   // the variable x has the value ‘x’.

Dynamic Initialization

Java allows variables to be initialized dynamically. Take a look following example.

Output :

Normal initaialization : area is = 200
Dynamic initaialization : area is = 200

The Scope and Lifetime of Variables

Every variable have scope and life time throughout the program. Here we study when the new scope will be create for how long time (Life time).

A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope.

We use so many variables in our program and declared these variables at the at the start of the main( ) method.

Most other computer languages define two general categories of scopes: global and local. However, these traditional scopes do not fit well with Java’s strict, object oriented model.

Take a look below example.

 


Here we initialize variable x in main block but the varible y is initialized in if block so scope of variable y is limited to if block.
So we will get error on line no. 14 because we are trying to access variable y which is out side of its scope.
NOTE: we will study about scope and lifetime in further chapter.

Prev Next