Data Types in Java: Primitive & Non-Primitive Data Types

Introduction

In any programming language, a data type is an ascribe of data that lets the computer or compiler know how the programmers want to assign the data. A data type adds a restriction to the variables or a function while assigning values.

These data types define the behavior of data like the way values of that type can be stored and operations that can be done on data. Let’s have a look at all the data types provided by java.

Primitive Data Types

A primitive data type cannot be further split into a simpler data type. Java provides 8 primitive data types, let’s explore them!

Byte

A byte is an Integer type that stores whole numbers ranging from -128 to 127, this clears the memory constraint problems if you are dealing with small numbers since it requires only 1 byte of memory. A byte variable can be declared using the “byte” keyword. Assigning a value higher than 127 to a byte throws an “incompatible types” error.

byte n1 = 98;

System.out.println(n1);

The above snippet prints 98 as expected.

Short

A short is an Integer type that stores whole numbers ranging from -32768 to 32767, it consumes 2 bytes of memory from the disk. A short variable can be declared by using the “short” keyword. Assigning a value greater than 32767 to a short variable throws an “incompatible types” error.

short n1 = 9876;

System.out.println(n1);

The above snippet prints 9876 as the output.

Int

An int is an integer type that stores whole numbers ranging from -2147483648 to 2147483647, it consumes 4 bytes of memory in the disk. Generally, programmers prefer more to use an int to declare a variable that stores numeric values. Java compiler throws an “incompatible types” error if tried to assign a value greater than the range.

int n1 = 987654;

System.out.println(n1);

The above snippet prints 987654 as the output.

Long

Now, this is something interesting data type which consumes 8 bytes of memory in the disk. It is an integer type that stores whole numbers ranging from -9223372036854775808 to 9223372036854775807, phew that takes a considerable amount of time to read that range.

This is used when the int data type overflows for the operations we perform. Remember that we need to end the value with an ‘L’ while assigning.

long n1 = 987654321098765L;

System.out.println(n1);

The above snippet prints 987654321098765, as expected.

Float

Float is a floating-point data type, meaning that it can store the values including their decimal precision. Let us assume that you’ve developed a code for noting all your expenditures, but you are quite strict and want to keep track of each penny you spent. In that case, int will not do the job because int can store only whole numbers.

We need a floating-point data type for this task. A float can store the fractional numbers ranging from 3.4e-038 to 3.4e+038, it can store up to 7 digits decimal precision. Remember that you should end the value with an ‘f’.

float n = 98.76f;

System.out.println(n);

The above snippet prints 98.76 as the output.

Read: JavaBeans Properties & Benefits: How Should You Utilize?

Double

Double is similar to float, but as the name says it is twice the float in the case of decimal precision. It can have a 15 digit decimal precision and can store fractional numbers ranging from 1.7e-308 to 1.7e+308. Remember that you have to end the value with a “d”.

Let’s walk through a code to understand the difference between float and double.

public class Test{

    public static void main(String args[]) 

    { 

      float a1=1.f/70;

      float b1=0;

      double a2=1.d/70;

      double b2=0;

      float f1=1f;

      double f2=1d;

      for(int i=0;i<490;i++){

        b1=b1+a1;

        b2=b2+a2;

        if(i>1 && i<=50){

          f1=f1*i;

          f2=f2*i;

        }

      }

      System.out.println(b1);  //line1

      System.out.println(b2);  //line2

      System.out.println(f1);  //line3

      System.out.println(f2);  //line4

    } 

}

On hand calculation of the expression “(1/70)*490” gives us 7 as an answer, but executing it in java using float and double gives a different answer. In the above snippet, a float variable and a double variable is initialized with 1/70, and adding this value to another variable 490 times should give us 7 as the answer.

On running the above snippet line 1 prints 6.9999795 which has a 7 digit decimal precision, whereas line 2 prints 6.999999999999978 which has a 15 digit decimal precision. So if float doesn’t provide you an accurate decimal precision then you can opt for double. Also, a float is more likely to hit infinity since the range of float is less when compared to double.

For example, if you store factorial of a considerably big number then that variable hits infinity. From the above snippet, we can see that there are two variables used to store the factorial of 50 and at the time we print the result, line 3 prints infinity, and line 4 prints 3.0414093201713376E64, so if float doesn’t meet your numerical range then you can opt for double.

Both float and double can be used as scientific numbers with an ‘e’, where ‘e’ denoted the power of 10. For example, 3e2f is equivalent to 300.0 in float data type, and 3e4d is equivalent to 30000.0 in double data type.

Boolean

A boolean data type can take only two values true and false, It is declared by using the boolean keyword in java. This data type is generally used as a flag variable for keeping track of changes we do in a code. For example, setting the flag to true if a number is divisible by 2 else false.

boolean flag = true;

boolean b1 = false;

System.out.println(flag);    //prints true

System.out.println(b1);  //prints false

Char

A char data type is used to store a single character, this data type can be declared using the char keyword. Remember that we have to enclose the character in single quotes while assigning, it can store both lower case and upper case characters in a char data type.

Storing more than one character in a char data type throws an error. Also, there’s a fun fact regarding char data type which is, typecasting a char into an integer store the ASCII value of that character, and vice versa is also true.

char c1=a;

char c2=66;

System.out.println(c1);     //line1

System.out.println(c2);     //line2

System.out.println((int)c1);//line3

In the above snippet line 1, prints ‘a’ as output which is as expected. Line 2 prints ‘B’ as output since 66 refers to B in the ASCII table. Line 3 prints 97 as output since it the ASCII value of ‘a’.

But what if we want to store more than one character? We’ll come to them in the coming paragraphs.

Also Read: 17 Interesting Java Project Ideas & Topics For Beginners

Non-Primitive Data Types

Non-Primitive data types in java are also called reference types because they refer to objects. Non-primitive data types are created by the programmer and they are not predefined. Since non-primitives are referred to as objects they can be assigned with null, which is not a case in primitive type.

Unlike primitive data types, a non-primitive data type must start with an upper case letter. All the non-primitive data types are of equal size and consume equal memory on disk which is different in the case of primitive data types.

String

A string is a special data type in java, where it contradicts the fact that non-primitive types are defined by programmers. The string data type is a non-primitive data type but it is predefined in java, some people also call it a special ninth primitive data type.

This solves the case where a char cannot store multiple characters, a string data type is used to store the sequence of characters. Remember that you need to enclose the sequence of text in double-quotes.

String s1 = Hey There;

System.out.println(s1);

The above snippet will print “Hey There” as expected.

Arrays, Classes, Interfaces, etc are few other non-primitive data types in java. 

How to calculate the range of data types?

After watching the ranges of primitive data types you may get a doubt that do we need to remember this?. Well, the answer would be NO. But we need to remember the size of each data type and then we can calculate the range of that data type.

For example, a byte data type consumes 1 byte of memory on disk. At the compiler level, all the data is stored in the form of bits and one byte has 8 bits. Now one among the 8 bits is used to specify the sign of the number and the remaining 7 bits can store the actual number, so the maximum number we can store using 7 bits is 128.

So, -128 is the lower limit of byte data type and +127 is the upper limit because zero is the first number on the number line after negative numbers.

Similarly in floating-point types, the data is split into 3 parts signed bit, mantissa, and exponent. Mantissa part is used to store the decimal precision, a float has 23 mantissa bits plus one hidden bit and a double has 52 mantissa bits plus one hidden bit.

For float, log(2^24)/log(10) which is approximately equal to 7, so 7 digits decimal precision.

For double, log(2^53)/log(10) which is approximately equal to 15, so 15 digits decimal precision.

Conclusion

We have seen various data types in java, understood primitive and non-primitive data types, the difference between primitive and non-primitive. Walked through sample code snippets to have a basic knowledge of the declaration of data types.

Understood how to calculate the range of various data types of integer data types, how to calculate the decimal precision of floating-point data types.

Now that you are aware of various data types in java, start exploring them!

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
Learn More

Leave a comment

Your email address will not be published. Required fields are marked *

×