Java Variables and Data Types with example
What is mean by Variable?
A variable is a container that holds values that are used in java program.Every variables must be used to declare a data type. That data type hold the quantity of values.
Using variables in java program you have to follow two steps:
1) Variable Declaration
2) Variable Initialization
Variable Declaration
If you are Declaring a variable in program, you need to specify the data type and that variable unique name.
For example:
Int a,b,c;
Float pi;
Double e;
Variable Initialization:
To initialize a variable, You need to assign a valid value to it.
For example:
Pi = 3.142;
I = 1;
A=’v’;
Do = 20.35;
We can combine together declaration and initialization.
Int a=100;
Example:
Int a=10,b=20,c=30;
Float pi=3.0142;
Double do = 30.256;
Char a=’v’;
Types of variables
In java, we have 3 types of variables
They are :
1. Local Variables
2. Instance Variables
3. Static Variables
1) Local Variables
Local variables are declared inside the body of a method.
2) Instance Variables
Instance variables are Object specific and are defined without a keyword I.e STATIC Keyword. They are defined outside of the body method declaration.
3) Static Variables
Static variables are initialized at the beginning of the program execution and only once.
These variables are must be initialized first, before the initialization of any other instance variables.
Example: Types of Variables in Java program
Class data {
Int data = 100; //instance variables
Static int a = 1; //static variables
Void method() {
Int b = 87; //local variable
}
}
Data types in JAVA
Data types divided into two types it classify the different values to be stored in the variable.
They are:
1. Primitive Data Types
2. Non-primitive Data Types
Primitive Data Types
Primitive data types are called as predefined variables and variable within the java language. Primitive values do not share state with other primitive values.
In primitive data type there are 8 types:
1. Byte
2. Short
3. Int
4. Long
5. Char
6. Float
7. Double
8. Boolean
These all are Integer data types.
Byte (1 bits)
Short (2 byte)
Int (4 byte)
Long (8 byte)
Floating Data Type
Java Variable Type Conversion & Type Casting
A variable one type can receive the value of another type. Here there 2 cases
Case 1) Variable of smaller capacity is be assigned to another variable of bigger capacity
Double d;
Int I = 10;
d = I;
This process is Automatic, and non -explicit is known as conversion
Case 2) Variable of larger capacity is be assigned to another variable of smaller capacity
Double d = 10;
Int I;
I = (int) d
In such case,you have to explicitly specify the type cast operator.This process is known as Type Casting.