Data Types in Java
In our day to day lives we deal with a lot of data. All this data can be categorized into different types. Take the example of a list containing the result of all the students in your class.
Let’s see what all different types of data are present in this list. The name of the student is a set of alphabets. Our school has a policy to award marks in subjects only in whole numbers, in case the total marks in the subject are a fraction like 84.5, it will be rounded off to 85. So, the marks in each subject and the total marks obtained are whole numbers or integers. Percentage is a fraction as it can be 94.5 or 84.0 or 75.25, etc. Data in the Promoted column tells us if the student is promoted to the next class or not. It can contain Y to indicate yes the student is promoted or N to indicate No the student is not promoted. Another way to look at it is that Promoted column represents one of the two states the student can be in, either he is promoted, or he is not promoted.
Putting on my programmers’ hat, I will refactor the Promoted column a little bit and instead of writing Y or yes if the student is promoted, I will write true. I will write false if the student is not promoted. Now it will look something like this:
Our sample student result sheet contains four types of data:
- Set of characters — Name of the students
- Whole numbers — Marks in each subject & total marks
- Fractional numbers — Percentage
- True/False — Promoted
Java language formally defines a category for each such type of data and these data categories are called Data Types.
Java provides two types of data types:
- Primitive Data Types
- Reference or Composite Data Types
The reference types are Class type, Interface type and Array type. We will first look at Primitive Data Types. I will talk about Reference types in detail when we will start discussing arrays.
Primitive Data Types
In Java, the primitive data types are broadly grouped into four groups:
This group represents the whole numbers like the marks in each subject & total marks columns of our student result sheet example. The data types in this group are byte, short, int and long.
This group represents the fractional numbers like the percentage column of our student result sheet example. The data types in this group are float & double.
This group represent the characters like the name of students in our student result sheet example. There is only one data type present in this group char.
This group represents the true/false kind of data like the promoted column in our student result sheet example. This group too has only one data type boolean which can either have the value true or false.
This gives us 8 primitive data types — byte, short, int, long, float, double, char and boolean. Out of these 8 primitive data types, the first 7 data types are collectively termed as Numeric Types as they deal with numerical values.
Next, we will look into each of these data types in detail.