Java Variables and Data Types With EXAMPLE
Java Variables and Data Types With EXAMPLE
What is a Variable?
A variable can be thought of as a container which holds value for you, during the life of a Java
program. Every variable is assigned a data type which designates the type and quantity of value
it can hold.
Variable Declaration
Variable Initialization
Variable Declaration
Variable Initialization
Types of variables
Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.
float pi;
double d;
char a;
Variable Initialization:
pi =3.14f;
do =20.22d;
a=’v’;
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;
Types of variables
Local Variables
Instance Variables
Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword .They are defined Outside a method
declaration. 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.
class Guru99 {
int data = 99; //instance variable
void method() {
Data types classify the different values to be stored in the variable. In java, there are two types
of data types:
There are 8 primitive types: byte, short, int, long, char, float, double, and boolean Integer data
types
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
float (4 bytes)
double (8 bytes)
char (2 bytes)
Logical
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes