Variables in Java
- A variable is a name given to the memory location.
- A variable is used to store value.
- We can change the value of the variable when needed.
- Every variable in the java program must be declared before it is used.
- To create every variable(declare) we use datatype.
Datatypes in Java
- The data types are keywords that are used to declare the variables.
- The datatype decides the type of value that can be stored in the variable.
- The datatype decides what is the size of the memory location which is used as variable/ by variable.
- The datatype also decides the range of the values that can be stored in the variable.
- The syntax for creating variables is as follows:
datatype variable_name=value;
The following table shows all 8 primary datatypes available in java:
Datatype | Type of value | Size | Range |
byte | Integer | 1 byte | -128 to 127 |
short | Integer | 2 byte | -32768 to 32767 |
int | Integer | 4 byte | -2147483648 to 2147483648 |
long | Integer | 8 byte | -263 to 263-1 |
float | Real | 4 byte | 32-bit IEEE 754 |
double | Real | 8 byte | 64-bit IEEE 754 |
boolean | Boolean (true/false) | 1 bit | true,false |
char | Character | 2 byte | 0 to 65535 |
The following example creates a variable of int type and stores 100 into it.
int a=100; System.out.println(a);
In java, if you try to store a value beyond the permitted range of datatype then it's a syntax error.
The following declaration gives a syntax error.
byte b=130;
If you try to assign the value of a larger type in a variable of a smaller data type then it is a syntax error because it may lead to a loss in the data:
For example:
short s=123456;
The above statement generates an error because the range of short is -32768 to 32767, and we are trying to assign 123456 into the short variable which results in the loss of the data.
Similarly, if you assign a double value to a float variable it will lead to a syntax error (possible lossy conversion from double to float):
float radius=3.14;
Remember that any real literal by default treated as double, it means 3.14 is a double value.
If you want to make a real literal as float, then you must use the letter f or letter F after the real value, it means that 3.14f or 3.14F is a float value, so writing the above radius declaration will work:
float rad=3.14f;
Consider the below example:
double x=2.12;
int p=x; This will also generate an error because we are trying to assign a double value into the int variable which leads to possible lossy conversion.