If you cannot find what you are looking for. Please visit our sitemap

Java Variable Declaration Scope Lifetime and Type Conversion

                           Java Variable Declaration

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. All variables have a scope, which defines their visibility and lifrtime.

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, or the name of a class or interface. The identifier is the name of the variable. You can initialize the variable by specifying an equal sign and a value.

int a, b, c; //declare three int a , b and c.
int d = 4, e, f = 5; //declared three ints, initializing d and f.
byte g = 7;  //declares g and initialize.
double h = 8.465 //declarers a double a.
char i = 'i' //the variable i has the value of 'i'.

Dynamic Initialization:

In Java variables can be initialized dynamically.

Scope and Lifetime of Variables.

Variable are created when their scope is entered, and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope Therefore, 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.

Type Conversion and Casting:

If two variables are compatible, then java will perform the conversion automatically.

Java's Automatic Conversions:

When two type of data is assigned to another type of variable, and automatic type conversion will take place  if the following two conditions are met:
  • The two types are compatible.
  • The destination type is larger than the source type.

Casting Incompatible Types:

To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form:

(target-type) value.

Here, target-type specifies the desired type to convert the specified value to.
A different type of conversion will occur when a floating-point value is assigned to an integer type, the fractional part is lost. This is called truncation.

Automatic Type Promotion in Expression:

Automatic conversion is also used in expressions when the value exceed the range of their operand.
In this bytes and shorts are elevated to int then to long.

Written By: Asad Hussain