Programs

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.

Check out our free courses to get an edge over the competition.

Importance of data types in Java

Data types are very significant in Java since it is a strongly typed language. In other words, they are attributes of data that inform the interpreter or compiler how the programmer intends to use the data. It implies that every operation is type-checked by the compiler to ensure type compatibility. So, illegal operations would not be compiled.

Strong type checking avoids errors and improves reliability. All values, expressions, and variables have a type to allow strong type checking. For instance, Java has no concept like a “type-less” variable. Whether you are using primitive or non primitive data types, the type of a value decides what operations are permitted on it. Specifically, an operation permitted on one data type may not be permitted on another.

Explore Our Software Development Free Courses

Check out upGrad’s Java Bootcamp

A data type restricts the values that an expression, a variable or a function might take. It defines how the values of that data type are stored in memory and what operations can be performed on the data. Furthermore, data types include storage categories like floating-point values, integers, characters, strings, etc.

Primitive Data Types

Before understanding what is non primitive data type in java, let’s have an overview of what primitive data types are.

They work as data manipulation’s basic building blocks in Java. They come with a constraint, i.e. they can only store data of the same type and also have a fixed size. They are alternately known as intrinsic data types. Moreover, you can accomplish operations on 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.

Check out upGrad’s Advanced Certification in Blockchain 

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.

This data type is used when a broader range than int is required. Its default value is 0L.

Examples: long x = 300000L, long y = -400000L

long n1 = 987654321098765L;

System.out.println(n1);

The above snippet prints 987654321098765, as expected.

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

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”.

Generally, this data type is used as the default data type for decimal values. It must never be used for accurate values like currency.

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.

In-Demand Software Development Skills

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.

Examples of valid Boolean data types in Java:

  • boolean x=true is valid 
  • boolean y=false is valid 
  • boolean m=5<10 is valid 

 Examples of invalid Boolean data types in Java:

  • boolean x=’true’ is invalid 
  • boolean y=”false” is invalid 
  • boolean s=1 is invalid 
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.

It represents a single 16-bit Unicode character. The minimum and maximum values are ‘\u0000’ (or 0) and ‘\uffff’ (or 65,535 inclusive) respectively.

Example: char letterX = ‘X’

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.

Why do most programmers prefer “Int” and “Double” data types?

Commonly, when an operation is carried out on shorts or bytes, they are internally upcasted to int data type before the real operation happens. Similarly, when you try to add two characters, their ASCII values are added.  Note that Java is strict when it comes to type checking.

It disallows bigger type data to be assigned to the smaller type. Hence, it is recommended to use integer type of even values to store the small values.

When an operation is performed on two float-type values, they are internally upcasted to double. Subsequently, the actual operation begins. But by default, the system considers a fractional value as double.

If you attempt to assign a fraction value to a float variable, you might encounter a compilation error. Hence, it is preferred to use double variables instead of float.

Now let’s get into the details of what is non primitive data type in java.

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.

In the java non primitive data types, the reference variables are created using the classes’ defined constructors. They can access objects. Such variables are declared of a particular type that can’t be changed. Examples can be animals, employees, etc.

Class objects and different types of array variables fall under reference datatype in the category of non primitive data types. The non primitive data types java mentions that the default value of any reference variable is zero. Moreover, the non primitive data types java also mentions that a reference variable can be used to refer to any object of the declared type or any compatible type.

For example,

Bird bid = new Bird(“Pigeon”);

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. 

  • Difference between primitive and non-primitive data types
  • The difference between primitive and non primitive data types in java are as follows:
  • Primitive types are predefined in Java, whereas non-primitive types are not defined by Java but created by the programmer.
  • Non Primitive data types can be used to call methods to carry out certain operations whereas primitive types can’t.
  • Non-primitive data types’ values can be null whereas primitive data types always hold a value.
  • The non primitive data types in java begin with an uppercase letter whereas primitive data type in Java begins with a lowercase letter.
  • The primitive data type’s size depends on the data type whereas all non-primitive data types have the same size.

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.

Enroll in Software Engineering Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development

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 Executive PG Program 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.

What are data types in Java?

The different sizes and values that programmers can store in the variable are defined by data types. Since Java is a heavily typed language, data types are very essential. It indicates that the compiler checks all operations for type compatibility. Illegal operations will be excluded from the compilation. As a result, rigorous type checking aids in the prevention of mistakes and improves dependability. All variables, expressions, and values have a type to enable strict type checking. In addition, the type of a value defines the operations that the programmer may perform on it. An operation that is permitted on one kind may not be allowed on another.

What are the main differences between Java and other platforms?

The Java platform differs from other platforms in a number of ways. To begin with, Java is an entirely software-based platform, whereas other platforms might be either hardware or software-based. Second, Java runs on top of different hardware platforms, whereas other systems can just run the hardware. Java is prevalent and repeatedly used because of its security features. Many Java specialists utilize it for various objectives. We can create a wide range of programs using Java, including online applications, corporate applications, desktop applications, network applications, gaming, Android apps, and many others.

What is the role of a Java programmer?

Java programmers are mainly responsible for creating, developing, and managing Java code before running on any Java-enabled platform. The roles of Java programmers increase with the size of the business. Because most Java programmers work on a variety of projects, their job tasks are seldom defined. However, Java programmers might work on specific applications frequently until the required results are obtained to reduce their responsibilities. It's a popular programming language that works on any system that has the Java Virtual Machine installed. Because it is a general-purpose programming language, it is akin to Python or JavaScript.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

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

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks