Data Types in JavaLearn about Data Types in Java In Java variables must be declared before they are used in a program (that is Java is statically typed). This means the following code will result in compilation error in Java.
public static void main(String[] args) {
age=20; //COMPILATION ERROR
System.out.println(age);
}
So we need to know the basic data types to declare variables. byte, short, int, long are used to represent numbers without floating point. float, double to represent floating point numbers. boolean to represent true or false condition(s). char to represent characters. Corrected version of the above program:
public static void main(String[] args) {
short age=20;
System.out.println(age);
}
How to choose between byte, short, int and long? Depending on how big the values that are going to be assigned to your variable, you have to choose the data type. A person's age practically will not exceed 200 years. Hence we declared "short age=20". We could also declare int age=20 BUT declaring it as int consumes more memory as more bytes are allocated for storage. Please click this link for the maximum and minimum values a data type can hold. Example showing declaration of all possible primitive data types:
public static void main(String[] args) {
byte kidsAge = 2;
short age = 20;
int ageOfEarth = 87878723;
long ageOfUniverse = 28723293982L;
float approximateAverageAge = 30.45f;
double politiciansEarnings = 9922242423239.999d;
boolean isItRaining = true;
char firstLetterOfMyName = 'K';
}
|