L5 Datatypes Variable
L5 Datatypes Variable
1. Variable Declaration
2. Variable Initialization
Variable Declaration:
To declare a variable, you must specify the data type & give
the variable a unique name.
int a,b,c;
float pi;
double d;
char a;
Variable Initialization:
To initialize a variable, you must assign it a valid value.
pi =3.14f;
do =20.22d;
a=’v’;
You can combine variable declaration and initialization.
Example :
float pi=3.14f;
double do=20.22d;
char a=’v’;
Types of variables
In Java, there are three types of variables:
1. Local Variables
2. Instance Variables
3. Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the body
of a method.
2) Instance Variables
o Instance variables are defined without the STATIC
keyword.
o They are defined Outside a method declaration.
o They are Object specific and are known as instance
variables.
3) Static Variables
Static variables are initialized only once, at the start of the
program execution. These variables should be initialized first,
before the initialization of any instance variables.
There are 8 primitive types: byte, short, int, long, char, float,
double, and boolean
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
float (4 bytes)
double (8 bytes)
Textual Data Type
char (2 bytes)
Logical
class Demo {
public static void main(String args[]) {
byte x;
int a = 270;
double b = 128.128;
System.out.println("int converted to byte");
x = (byte) a;
System.out.println("a and x " + a + " " + x);
System.out.println("double converted to int");
a = (int) b;
System.out.println("b and a " + b + " " + a);
System.out.println("\ndouble converted to byte");
x = (byte)b;
System.out.println("b and x " + b + " " + x);
}
}
Step 2) Save, Compile & Run the code.
Output: