Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

Data Types in Java

Any classification of data in Java can be defined as a Data Type. These form an essential component of all computer programming languages. Its function is to inform the compiler or the interpreter of what the programmer is using as the variable or method. Data Types in Java are essential for programmers because they should be able to assign the right Data Types to the correct variables to create a working program. 

As an Object-Oriented Programming Language, Java remains one of the most well-known languages globally. A report by PYPL PopularitY of Programming Language stated Java has a market share of 17.64%. Desktop applications, web and mobile development and many more depend on Java Data Types.   

Java Data Types constitute the type, nature, and set of operations for the value they store. This blog discusses the  Data Types in Java, such as primitive and non-primitive Data Types, with syntax and examples. Read More! 

Table of Contents 

1) Understanding Data Types in Java

2) Data Type categories

    a) Primitive Data Types

    b) Non Primitive Data Types

3) Differences between Primitive Data Types and Reference Data Types

4) Conclusion

Understanding Data Types in Java

Java, renowned for its static and strong typing, meticulously assigns roles to various Data Types within its programming paradigm. In this context, Data Types encompass a broad spectrum, ranging from integers to characters and more. Programmers must adhere to a predefined set of constants and variables, aligning them with specific Data Types. 

The underlying principle is that each variable has an associated Data Type, determining how its values are stored in the computer's memory. This intrinsic association between variables and Data Types ensures a structured and reliable coding practice, promoting consistency and predictability in Java programs. Consequently, Java's stringent typing system enhances code integrity and reduces the likelihood of errors associated with incompatible Data Types or inconsistent variable usage.

Learn how to make desktop application and important concept of GUI programming with Java by signing up for our Java Swing Development Training  now! 

Data Type categories 


Data type

Every individual bit of data is processed and categorised into types, and Java uses different kinds of Data Types. According to the properties these Java Data Types possess, they are mainly categorised into Primitive Data Types and Non-Primitive Data Types. 

Primitive Data Types 

Primitive Data Types in Java are the ones that are already defined by the programming language. In this, the size and type of variable values are already specified and have no additional methods. The Data Types are hardcoded into the compiler to be recognised when the program is executed. Primitive Data Types are classified into eight types, as below: 

1) Boolean Data Type: This Data Type in Java is represented with only one bit of information - either True or False. This Data Type denotes the two truth values of logic and Boolean Algebra. However, the Boolean data type’s size depends on the virtual machine. The values of the type Boolean are not converted to any other Data Type, but there is a possibility that the programmer can easily write the conversion code. 
 

Syntax:
boolean boolean_Var;
Example:
public class Example
{
public static void main(String[] args)
{
boolean isRaining = true;
boolean isSunny = false;
System.out.println("Is it raining? " + isRaining); // Output: Is it raining? true
System.out.println("Is it sunny? " + isSunny); // Output: Is it sunny? false
// Boolean variables can also be used in conditional statements if (isRaining)
{
System.out.println("Bring an umbrella!");
} else
{
System.out.println("Leave the umbrella at home.");
}
}
}


Output: 
Is it raining? true 
Is it sunny? false 
Bring an umbrella! 

In this example, we declare two Boolean variables, isRaining and isSunny, and initialise them with true and false values, respectively. We then use the System.out.println() method to print the values of these variables to the console. We also use an if statement to check whether isRaining is true. If it is, we print the message "Bring an umbrella!" to the console. If it's false, we print "Leave the umbrella at home." instead. 

2) Byte Data Type: In Java, the Byte Data Type represents the smallest data type among all other integer Data Types. Byte Data Type is an 8-bit signed two's complement that stores whole numbers ranging from –128 to 127. It can also be a replacement for the data type int; however, there does not exist any range of size as that of the integer data type. Hence it helps save a large amount of memory. 
 

Syntax:
byte byte_Var;
Example:
public class ByteExample
{
public static void main(String[] args)
{
byte myByte = 123; // declaring a byte variable named myByte and assigning a value of 123 to it
System.out.println("myByte = " + myByte); // printing the value of myByte to the console
byte minByte = Byte.MIN_VALUE; // getting the minimum value of the byte data type
byte maxByte = Byte.MAX_VALUE; // getting the maximum value of the byte data type
System.out.println("minByte = " + minByte); // printing the minimum value of the byte data type to the console
System.out.println("maxByte = " + maxByte); // printing the maximum value of the byte data type to the console
}
}
myByte = 123 


Output: 
myByte = 123 

minByte = -128 

maxByte = 127 

In this example, we declare a byte variable named myByte and assign it a value of 123. We then print the value of myByte to the console using System.out.println(). We also use the Byte.MIN_VALUE and Byte.MAX_VALUE constants to get the minimum and maximum values of the byte data type, respectively. We then print these values to the console as well. 

3) Char Data Type: It is used for storing only a single character in lowercase and uppercase characters. These characters should be enclosed within single quotes like 'A' or 'a'. Alternately, ASCII characters can also be used to display certain characters and also has a provision for multiple languages other than English. Char Data Type takes a memory space of 16 bits or 2Bytes, and the value stored ranges from 0 to 65536.
 

Syntax:
char char_Var;
Example:
public class CharExample
{
public static void main(String[] args)
{
char letter = 'A';
System.out.println("The value of letter is " + letter);
}
}


Output: 

The value of letter is A 

Here, we create a char variable named letter and assign it the value 'A'. The println statement then outputs the letter's value, 'A'. Note that char values are enclosed in single quotes, unlike String values which are enclosed in double quotes. 

4) Int Data Type: The Int Data Type in Java is used for storing integer values that are not of the fraction form or have any decimal places. It has a size of four bytes, and the default value is zero. The value of the integer ranges from –231 to 231. Unless you need to store numbers that exceed the given range, you should always use this data type to store integer values.
 

Syntax:
int int_Var;
Example:
public class IntExample
{
public static void main(String[] args)
{ // declaring and initialising variables of type int
int num1 = 10;
int num2 = 20;
int sum = num1 + num2; // adding two integers and storing the result in sum variable
// printing the values of variables to the console
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
System.out.println("sum = " + sum);
}
}


Output:

num1 = 10

num2 = 20

sum = 30 

In this code, we have declared three variables of type int - num1, num2, and sum. We have initialised num1 to the value 10 and num2 to the value 20. We then add num1 and num2 and store the result in the variable sum. Finally, we print the values of num1, num2, and sum to the console using the System.out.println() method

5) Short Data Type: It is similar to the Int Data Type, that stores values ranging from –32768 to 32767. It is, in fact, greater than a Byte Data Type in terms of size and less than an Int Data Type. The default size of this data type is 2 bytes. 
 

Syntax:
short short_Var;
Example:
public class ShortDataTypeDemo
{
public static void main(String[] args)

{
// Declare a variable of short data type
short num = 32767;
// Print the value of the variable
System.out.println("The value of num is: " + num);
// Increment the value of the variable
num++;
// Print the new value of the variable
System.out.println("The new value of num is: " + num);
}
}


Output:

The value of num is: 32767

The new value of num is: -32768 

In this code, a variable num is declared, which is of short data type. This short data type is a 16-bit signed integer whose range varies from –32768 to 32767. A value, i.e. 32767, is assigned, which is the maximum value stored by the short to the num variable. The value of num is then printed through the println() method of the System.out object.  

Next, the value of num is incremented by one using the ++ operator. The maximum value of a short is 32767, but when the num is increased, it overflows and becomes the minimum value of a short, which is -32768. A new value of num is then printed.

Refer Our Java Interview Questions and Answers to get through the Interviews with ease. 

6) Long Data Type: This Data Type in Java primarily stores bigger numeric data; hence, the range is quite large. It is a 64-bit integer with a range varying from –263 to 263 and has a size equal to eight bytes. It is useful when there is a need to store data that is longer than the integer Data Type. 
 

Syntax:
long long_Var;
Example:
public class LongDemo
{
public static void main(String[] args)
{
// Declare a long variable
long myLong = 123456789012345L;
// Print the value of the long variable
System.out.println("myLong = " + myLong);
// Perform arithmetic operations on the long variable
long sum = myLong + 1000;
long product = myLong * 2;
// Print the results of the arithmetic operations
System.out.println("sum = " + sum);
System.out.println("product = " + product);
}
}


Output: 

myLong = 123456789012345 

sum = 123456789013345 

product = 246913578024690 

In this program, we declare a variable myLong of type long and initialise it with 123456789012345L. Note that we include the L suffix to indicate that this is a long literal. We then perform arithmetic operations on the myLong variable, adding 1000 and multiplying by 2, and store the results in the sum and product variables, respectively. Finally, we print the value of myLong and the results of the arithmetic operations. 

7) Float Data Type: A Float Data Type in Java stores decimal values with a default value of zero and a size of four bytes. It is a single-precision 32-bit IEEE 754 and has an infinite value range. It is, however, recommended to use Float Data Type instead of Double Data Type if a memory constraint exists. Another point to be noted is that currency should never be stored in Float Data Type. 
 

Syntax:
float float_Var;
Example:
public class FloatExample
{
public static void main(String[] args)
{
float pi = 3.14159f; // declare a float variable and assign a value to it
System.out.println("The value of pi is: " + pi); // print the value of pi
float bigNumber = 3.14159e10f; // using scientific notation to represent a large float number
System.out.println("A big number in scientific notation is: " + bigNumber);
float smallNumber = 1.23e-4f; // using scientific notation to represent a small float number
System.out.println("A small number in scientific notation is: " + smallNumber);
}
}


Output: 

The value of pi is: 3.14159 

A big number in scientific notation is: 3.14159E10 

A small number in scientific notation is: 0.000123 

In this program, we declare a float variable called pi and assign it the value of 3.14159. We then print the value of pi using the System.out.println() method. We also demonstrate using scientific notation to represent large and small float numbers. We declare a float variable called bigNumber and assign it the value of 3.14159e10, which represents 3.14159 multiplied by 10 to the power of 10.  

We then print bigNumber to the console. Similarly, we declare a float variable called smallNumber and assign it the value of 1.23e-4, which represents 1.23 multiplied by 10 to the power of -4. We then print smallNumber to the console. 

8) Double Data Type: The Double Data Type is similar to the Float Data Type, but the difference between them lies in the precision of the decimal, where the Double Data Type is twice that of the Float. It is a double-precision 64-bit or eight bytes IEEE 754 floating point type. Double Data Type is used for decimal values but should not be used when precision is required. 
 

Syntax:
double double_Var;
Example:
public class DoubleDataTypeDemo
{
public static void main(String[] args)
{
//declaring double variables
double num1 = 3.14159;
double num2 = 2.71828;
//performing arithmetic operations on double variables
double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;
//displaying the results
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
System.out.println("sum = " + sum);
System.out.println("difference = " + difference);
System.out.println("product = " + product);
System.out.println("quotient = " + quotient);
}
}


Output: 

num1 = 3.14159 

num2 = 2.71828 

sum = 5.8598700000000005 

difference = 0.42331 

product = 8.5397293972 

quotient = 1.1578212829309047 

In this program, we declare two double variables, num1 and num2 and assign them some values. We then perform basic arithmetic operations on these variables and store the results in other double variables sum, difference, product, and quotient. Finally, we display the values of all these variables using the System.out.println() method. Note that the results of some arithmetic operations may contain rounding errors due to the limitations of the double data type. 

The above discussion was all about the different types of Primitive Data Types. Let us now get into the discussion about the different types of Non-Primitive Data Types. 

Want to get an understanding and develop your knowledge on the working of Java EE APIs, then signup for our Introduction To Java EE Training course now! 

Non-Primitive Data Types 

Non-Primitive Data Types, also known as Reference Data Types, denote instances or objects. They do not have the provision for storing the variable's value in the memory directly but store the memory address of the variable. Non-Primitive Data Types are user-defined, unlike Primitive Data Types, which Java defines. Programmers create them and assign a value null to them. All the Non-Primitive Data Types are considered equal in size. Non-Primitive Data Types are generally arrays, class interfaces, or strings. 

1) Arrays: In Java, Arrays are termed as the typed variables referred to by a common name. They can store one or more kinds of specific Data Types. These are stored in an indexed manner beginning with index 0; a particular element in an array is accessed by its index. Arrays can be passed as method parameters and static fields. The variables have data types that can be primitive or non-primitive.  
 

Syntax:
int array_name = new int [10];
Example:
public class ArrayExample
{
public static void main(String[] args)
{
// create an array of integers
int[] numbers = {5, 2, 8, 10, 1};
// print the array
System.out.println("Original array: ");
for (int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
// sort the array
Arrays.sort(numbers);
// print the sorted array
System.out.println("nSorted array: ");
for (int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
// find the sum of the array
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
System.out.println("nSum of array: " + sum);
// find the average of the array
double average = (double) sum / numbers.length;
System.out.println("Average of array: " + average);
// create a 2D array of strings
String[][] names = {{"John", "Mary", "Tom"}, {"Bob", "Sue", "Kate"}};
// print the 2D array
System.out.println("n2D array: ");
for (int i = 0; i < names.length; i++)
{
for (int j = 0; j < names[i].length; j++)
{
System.out.print(names[i][j] + " ");
}
System.out.println();
}
}
}


Output: 

Original array:  

5 2 8 10 1  

Sorted array:  

1 2 5 8 10  

Sum of array: 26 

Average of array: 5.2 

2D array:  

John Mary Tom  

Bob Sue Kate 

This program creates an Array of Integers, sorts the Array, finds the sum and average of the Array, creates a 2D Array of strings, and prints both Arrays. 

2) Class: It is a user-defined Data Type in Java from which objects are created. A common class describes a set of properties or methods for all objects of the same type. It consists of fields and methods used to represent an object's behaviour. A class gets created by the creation of the respective objects. 
 

Syntax:
class class_Name
{
// class body
}
Example:
public class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public void sayHello()
{
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
public class Main
{
public static void main(String[] args)
{
Person person = new Person("John", 30);
person.sayHello();
person.setName("Jane");
person.setAge(25);
person.sayHello();
}
}


Output: 

Hello, my name is John and I am 30 years old. 

Hello, my name is Jane and I am 25 years old. 

In this program, we define a Person class with two private instance variables, name and age, and three methods:  

1) A constructor that initialises the name and age variables when a new Person object is created.  

2) getName() and getAge() methods allow other classes to access the name and age variables.  

3) setName() and setAge() methods allow other classes to modify the name and age variables.  

We also define a sayHello() method that prints a message with the name and age of the Person object. In the Main class, we create a new Person object named person with the name "John" and age 30 and call the sayHello() method to print a message. We then modify the name and age variables of the person object using the setName() and setAge() methods and call sayHello() again to print a new message with the updated information. 

Learn how to make desktop application and important concept of GUI programming with Java by signing up for our Java Swing Development Training course now! 

3) String: A String Data Type in Java stores an array or sequence of characters and is enclosed in double quotes. Although it is a Non-Primitive Data Type, it is already defined in Java. The primary difference between a character and a string is that a character is a collection of separate char-type entities in Java. On the other hand, a string can hold a sequence of characters in a single variable. 
 

Syntax:
string_type string_variable = “strings_sequence”
Example:
public class StringDemo
{
public static void main(String[] args)
{
// Declare and initialize a string variable
String message = "Hello, world!";
// Print the string to the console
System.out.println(message);
// Get the length of the string
int length = message.length();
System.out.println("The length of the string is: " + length);
// Get the index of the first occurrence of a character in the string
int index = message.indexOf('o');
System.out.println("The index of the first 'o' character is: " + index);
// Get a substring of the string
String substring = message.substring(7);
System.out.println("The substring of the string is: " + substring);
// Concatenate two strings
String str1 = "Hello";
String str2 = "world";
String str3 = str1 + " " + str2;
System.out.println(str3);
}
}


Output: 

Hello, world

The length of the string is: 13 

The index of the first 'o' character is: 4 

The substring of the string is: world! 

Hello world 

This program declares a string variable, prints the string to the console, gets the length of the string, gets the index of the first occurrence of a character in the string, gets a substring of the string, and concatenates two strings.

4) Interface: An Interface, like a class, has methods and variables, but methods in the interface are abstract by default (only the method signature exists, but no body). If a class implements an interface and does not offer method bodies for all the functions specified in the interface, then the class should be declared abstract. The role of the interface is to specify what a class should do and not how it has to be done. 
 

Syntax:
public interface Interface_Name
{
// Any final, static fields here
// Any abstract method declaration here
}
Example:
// Define the interface
interface Animal
{
public void eat();
public void sleep();
}
// Implement the interface in a class
class Cat implements Animal
{
public void eat()
{
System.out.println("The cat is eating.");
}
public void sleep()
{
System.out.println("The cat is sleeping.");
}
}
// Main program to test the implementation
public class Main
{
public static void main(String[] args)
{
// Create a new cat object
Cat myCat = new Cat();
// Call the eat() and sleep() methods on the cat object
myCat.eat();
myCat.sleep();
}
}


Output: 

The cat is eating. 

The cat is sleeping. 

In this program, we first define an interface called Animal which contains two methods: eat() and sleep(). Then we implement this interface in a class called Cat. The Cat class overrides the eat() and sleep() methods to provide their implementation.  

Finally, we create a new Cat object in the main program and call the eat() and sleep() methods. Since the Cat class implements the Animal interface, we can treat the Cat object as an Animal object and call its methods accordingly. This demonstrates how interfaces can be used to define a set of methods that a class must implement while allowing for different implementations of those methods by different classes. 

5) Enum: Similar to a Class, an Enum also has attributes and methods. Yet, in contrast to classes, the constants in Enum are public, static, and final (i.e., it is unchangeable). It can neither be used to create objects nor can extend other classes. However, Enum can implement interfaces. 
 

Syntax:
enum Level
{
EASY,
MEDIUM,
HARD
}
Example:
public class EnumExample
{
enum Colour
{
RED, GREEN, BLUE
}
public static void main(String[] args)
{
Colour c1 = Color.RED;
Colour c2 = Color.GREEN;
Colour c3 = Color.BLUE;
System.out.println(c1); // Output: RED
System.out.println(c2); // Output: GREEN
System.out.println(c3); // Output: BLUE
}
}


In the above code, firstly, we define an Enum called Colour that contains three possible names of colours: RED, GREEN, and BLUE. In the main method, we create three variables of type Colour and assign them to different values. We then print out the value of these variables using System.out.println().
 

Java Training
 

Differences between Primitive Data Types and Reference Data Types

 

Characteristic

Primitive Data Types

Reference Data Types

Storage

Stores the actual values directly.

Stores references or memory addresses.

Examples

int, float, char, boolean, etc.

Objects, arrays, classes, etc.

Predefined vs. user-defined

Predefined vs. user-defined

Can be user-defined or part of the class library.

Memory consumption

Consumes less memory due to simplicity.

May consume more memory due to references and additional information.

Speed

Operations are faster.

Operations may be relatively slower due to indirection.

Usage

Ideal for basic data storage.

Suitable for creating complex structures and supporting OOP principles.

Flexibility

Limited in terms of complexity.

More versatile, enabling complex data structures.

Examples in code int x = 5; String str = new String("Hello");

 

Primitive Data Types comprise basic types such as int, float, char, and boolean. They directly store the actual values and are characterised by simplicity and efficiency. Primitive types are predefined by the language and operate faster, consuming less memory due to their straightforward nature.

Reference Data Types include objects, arrays, and classes. Instead of storing the actual data, they store references or memory addresses pointing to the data. This allows for the creation of complex structures and facilitates dynamic memory allocation. Reference types are more versatile, enabling the implementation of sophisticated data structures and supporting object-oriented programming principles.

One crucial difference lies in how primitive types are predefined by the language, while reference types can be user-defined or part of Java's extensive class library. The former is ideal for basic data storage, while the latter enables the creation of intricate data structures and supports object-oriented programming concepts.

Conclusion 

After reading this blog, you will know the different Data Types in Java. Before proceeding with the advanced concepts, you need to know about these Data Types. A better understanding of Data Types will help you develop a simple program or any software or application. 

Sign up for our Web Development Using Java Training to learn how to develop a web application using Java programming. 

Frequently Asked Questions

Can I change the data type of a variable in Java? faq-arrow

In Java, once a variable is declared with a specific Data Type, its type cannot be changed during runtime. However, type casting allows temporary conversion of the variable to another type for particular operations or situations, providing flexibility in handling different Data Types.

Why use Data Types in Java? faq-arrow

Data Types in Java are essential for defining the type and size of values a variable can hold. They ensure consistency in variable usage, optimise memory allocation, and enhance code reliability. Utilising Data Types facilitates precise data manipulation and contributes to the overall efficiency and integrity of Java programs.

Why is class used as Data Type in Java? faq-arrow

In Java, a class is used as a Data Type because it allows for the creation of user-defined types, encapsulating data and behavior into a single entity. This enhances code organisation, reusability, and promotes the principles of object-oriented programming, facilitating the creation of complex and structured applications.

What are the other resources and offers provided by The Knowledge Academy? faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.

Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.

What are related courses and blogs provided by The Knowledge Academy? faq-arrow

The Knowledge Academy offers various Java Courses, including Java Programming, Hibernate Training and Introduction to Java EE Course. These courses cater to different skill levels, providing comprehensive insights into Latest Java Technologies Trends.

Our Programming and DevOps blogs cover a range of topics related to Java Programming, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Java Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
 

What is Knowledge Pass, and how does it work? faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SPRING SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.