What do you mean by a variable?
It is a container to store value which varies according to the user requirement.
x = 20 is a variable
y = 2.5 is also a variable.
These two are variables but of different data types let us look at some of the variables in java now.
There are five types of variables in java they are:
- String: it stores name or sentences in double quotes
- Int: stores integral numbers and non-decimal numbers.
- float: stores decimal floating digits.
- Char: stores single characters in single quotes.
- Boolean: Evaluates a given condition.
Let us try to look at the implementation of all the variables one by one now:
Int or integer as the name suggests that it can store integer values negative or non-negative values.
Range: From -2,147,483,648 to 2,147,483,647 (32-bit signed).
public class Main{
public static void main(String [] args){
int x = 2;
int y = 4;
int z = x + y;
System.out.println(z);
}
}
Float is used to store decimal floating digits, and has a lower precision that is it can store values up to 7-8 digits.
public class Main{
public static void main(String [] args){
float x = 2.3f;
float y = 4.3f;
float z = x + y;
System.out.println(z);
}
}
//Note: if you directly try to declare x = 2.3 without an f you get an error error: incompatible types: possible lossy conversion from double to float
because decimal values are treated as double by default in java.
Double is used to store floating point values, but has a higher precision values up to 15-16 digits.
public class Main{
public static void main(String [] args){
double x = 2.3;
double y = 4.3;
double z = x + y;
System.out.println(z);
}
}
String: it encloses name or sentences in double quotes.
public class Main{
public static void main(String [] args){
String str = "hi this is prequelcoding";
System.out.println(str);
}
}
Char: stores single characters in single quotes.