Core Java

Java Variables

Variables

The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. These elements are examined next.

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:


type identifier [ = value][, identifier [= value] …] ;

  • The type is one of Java’s atomic types (Data Types), or the name of a class or interface. (We will discussed about Class and interface types later ).
  • The identifier is the name of the variable.
  • You can initialize the variable by specifying an equal sign and a value. Keep in mind that the initialization expression must result in a value of the same (or compatible) type as that specified for the variable.
  • To declare more than one variable of the specified type, use a comma separated list.

Example


int a, b, c; // declares three ints, a, b, and c.

int d = 3, e, f = 5; // declares three more ints, initializing // d and f.

byte z = 22; // initializes z.

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

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

boolean d = false;   // boolean value initialized with value false;

The identifiers that you choose have nothing intrinsic in their names that indicates their

type.

Dynamic Initialization

Although the preceding examples have used only constants as initializers, Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. Example Program for Dynamic variable Initialization:

class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
  • Here, three local variables—a, b, and c—are declared. The first two, a and b, are initialized by constants.
  • c is initialized dynamically to the length of the hypotenuse.
  • The program uses another of Java’s built-in methods, sqrt( ), which is a member of the Math class, to compute the square root of its argument.
  • The key point here is that the initialization expression may use any element valid at the time of the initialization, including calls to methods, other variables, or literals.

The Scope and Lifetime of Variables

So far, all of the variables used have been declared at the start of the main( ) method. However, Java allows variables to be declared within any block. A block defines a scope. Thus, each time you start a new block, you are creating a new scope. A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects.

There are three kinds of variables in Java based on scope & lifetime

Local Variable : Local variables are declared in methods, constructors, or blocks.

Global Variable/Instance Variable : Instance variables are declared in a class, but outside a method, constructor or any block.

Instance variable are also variable of object commonly known as field or property. They are referred as object variable. Each object has its own copy of each variable and thus, it doesn’t effect the instance variable if one object changes the value of the variable.

class Student
{
 String name;
 int age;
}

Here name and age are instance variable of Student class.

Class/Static Variables : Class variables also known as static variables are declared with the static keyword in a class. Static variables are also used in declaring constant along with final keyword. we will see about static variable in detail in upcoming chapters

class Student
{
 String name;
 int age;
 static int collegeCode =1101;
}

Here collegeCode is a static variable. Each object of Student class will share collegeCode property.

Scope of the varialbe with example Program

// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

Within a block, variables can be declared at any point, but are valid only after they are declared. If you define a variable at the start of a method, it is available to all of the code within that method.

  • Variables are created when their scope is entered, and destroyed when their scope is left.
  • Variable will not hold its value once it has gone out of scope.
  • Variables declared within a method will not hold their values between calls to that method. Also, a variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
  • If a variable declaration includes an initializer, then that variable will be reinitialized each
  • time the block in which it is declared is entered.
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}

Output

y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

Duplicate Variable  Error

Although blocks can be nested, you cannot declare a variable to have the same name as one in an outer scope. For example, the following program is illegal:

// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}
Published on Java Code Geeks with permission by Annamalai Thangaraj, partner at our JCG program. See the original article here: Java Variables

Opinions expressed by Java Code Geeks contributors are their own.

Annamalai Thangaraj

Annamalai is a Software Engineer with 2+ years experience in Java, Spring, Struts, Hibernate, IDM/IAM, and Enterprise Web Application Development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button