Variables
Variables
S.REVATHI AP/CSE
1
Variables
The variable is the basic unit of storage in a Java program.
2
Declaring a Variable
In Java, all variables must be declared before they can be used.
value] ...] ;
3
Example
int a, b, c;
int d = 3, e, f = 5;
byte z = 22;
double pi = 3.14159;
char x = ‘X’
4
Dynamic Initialization
Java allows variables to be initialized dynamically, using any
expression valid at the time the variable is declared.
CODING DEMO
5
The Scope and Lifetime of Variables
Java allows variables to be declared within any block.
A block defines a scope.
A scope determines what objects are visible to other parts of your
program.
Declare a variable within a scope, can localizing that variable
and protecting it from unauthorized access and/or
modification.
Scopes can be nested
CODING DEMO
6
Variables 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.
CODING DEMO
7
Type Conversion and Casting
To assign a value of one type to a variable of another type.
If the two types are compatible, then Java will perform the
conversion automatically.
8
1.Java’s Automatic Conversions
The following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type
(target-type) value 10
CODING DEMO
11