Variables
A variable stores a value of a particular type. A variable has a name, a type, and a value associated with it. In Java, variables can only
store values of primitive data types and references to objects. Variables that store references to objects are called reference variables.
Declaring Variables:-
Variable declarations are used to specify the type and the name of variables. This implicitly determines their memory allocation and the values that can be stored in them. We show some examples of declaring variables that can store primitive values:
char a, b, c; // a, b and c are character variables.
double area; // area is a floating-point variable.
boolean flag; // flag is a boolean variable.
The first declaration above is equivalent to the following three declarations:
char a;
char b;
char c;
A declaration can also include initialization code to specify an appropriate initial value for the variable:
int i = 10, // i is an int variable with initial value 10.
j = 101; // j is an int variable with initial value 101.
long big = 2147483648L; // big is a long variable with specified initial value.
Lifetime of Variables
Lifetime of a variable, that is, the time a variable is accessible during execution, is determined by the context in which it is declared. We distinguish between lifetime of variables in three contexts:
Instance variables:-— members of a class and created for each object of the class. In other words, every object of the class will
have its own copies of these variables, which are local to the object. The values of these variables at any given time
constitute the state of the object. Instance variables exist as long as the object they belong to exists.
Static variables:- also members of a class, but not created for any object of the class and, therefore, belong only to the class. They are created when the class is loaded at runtime, and exist as long as the class exists.
Local variables:- (also called method variables)— declared in methods and in blocks and created for each execution
of the method or block. After the execution of the method or block completes, local (non-final) variables are no longer accessible.
Initial Values for Variables
If no initialization is provided for a static variable either in the declaration it is
initialized with the default value of its type when the class is loaded.
Similarly, if no initialization is provided for an instance variable either in the declaration or in an block, it is initialized with the default value of its type when the class is instantiated.
The fields of reference types are always initialized with the null reference value, if no initialization is provided.
Example:-
How static and instance members are initialised in a class:-
public class Light {
// Static variable
static int counter; // Default value 0 when class is loaded.
// Instance variables
int noOfWatts = 100; // Explicitly set to 100.
boolean indicator; // Implicitly set to default value false.
String location; // Implicitly set to default value null.
public static void main(String[] args) {
Light bulb = new Light();
System.out.println("Static variable counter: " + Light.counter);
System.out.println("Instance variable noOfWatts: " + bulb.noOfWatts);
System.out.println("Instance variable indicator: " + bulb.indicator);
System.out.println("Instance variable location: " + bulb.location);
return;
}
}
Output from the program:-
Static variable counter: 0
Instance variable noOfWatts: 100
Instance variable indicator: false
Instance variable location: null
Initializing Local Variables of Primitive Data Types
Example:-
public class TooSmartClass {
public static void main(String[] args) {
int weight = 10,Range; // Local variable
if (weight < 10)
Range= 1000;
if (weight > 50)
Range = 5000;
if (weight >= 10)
Range = weight*10; // Always executed.
System.out.println("The price is: " + thePrice); // (1)
}
}
Explaination:-
In Example, the compiler complains that the local variable Range used in the println statement at (1) may not be initialized. However,
it can be seen that at runtime the local variable Range will get the value 100 in the last if-statement, before it is used in the println
statement. The compiler does not perform a rigorous analysis of the program in this regard. It only compiles the body of a conditional
statement if it treat the condition to be true. The program will compile correctly if the variable is initialized in the declaration, or if
an unconditional assignment is made to the variable. Replacing the declaration of the local variables in Example with the following
declaration solves the problem:
int weight = 10, Range = 0; // Both local variables initialized.
Initializing Local Reference Variables
public class VerySmartClass {
.
public static void main(String[] args) {
String importantMessage; // Local reference variable
System.out.println("The message length is: " + importantMessage.length());
}
}
Explaination:-In Example, the compiler complains that the local variable importantMessage used in the println statement may not be initialized. If the
variable importantMessage is set to the value null, the program will compile. However, at runtime, a NullPointerException will be thrown
since the variable importantMessage will not denote any object. The golden rule is to ensure that a reference variable, whether local or
not, is assigned a reference to an object before it is used, that is, ensure that it does not have the value null. The program compiles and
runs if we replace the declaration with the following declaration, which creates a String value and assigns its reference to the local
reference variable importantMessage:
String importantMessage = "Initialize before use!";
Conversions
Unary Cast Operator: (type):-
Java, being a strongly typed language, checks for type compatibility (i.e., checks if a type can substitute for another type in a given context)
at compile time. However, some checks are only possible at runtime (for example, which type of object a reference actually denotes during
execution). In cases where an operator would have incompatible operands (for example, assigning a double to an int), Java demands that
a cast be used to explicitly indicate the type conversion. The cast construct has the following syntax:
(<type>) <expression>
The is applied to the value of the <expression>.At runtime, a cast results in a new value of <type> which best represents the
value of the <expression> in the old type. We use the term casting to mean applying the cast operator for explicit type conversion.Casting can be applied to primitive values as well as references. Casting between primitive data types and reference types is not
permitted. Boolean values cannot be cast to other data values, and vice versa. The reference valuel null can be cast to any reference
type.
.
Narrowing and Widening Conversions
For the primitive data types, the value of a narrower data type can be converted to a value of a broader data type without loss of
information. This is called a widening primitive conversion. Widening conversions to the next broader type for primitive data types are given
in Figure below. The conversions shown are transitive. For example, an int can be directly converted to a double without first
having to convert it to a long and a float.
Figure 3.1. Widening Numeric Conversions