While working with programming languages, you will often come across something called โdata typesโ. These are like labels that tell the computer what kind of data the computer memory will be holding. In this article, we will talk about understanding Java Data Typesย and their categories.
Data types in Java programming language form the basics of the language. They are like the building blocks of a program. They are essential to understand concepts like data handling and memory allocation.
Are you ready to get started? Well then, let us dive in!
Summary Of The Article:
Data types refer to the kind of value a variable has. They let us know how to interpret the values stored in variables.
In Java, the data types can be differentiated into two categories – primitive data types and non-primitive data types.
The data types in the Java language can vary in size and the values that they storeโfor instance, numerical, characters, etc.
What Are The Data Types in Java? Why we use data types in Java?
Data types in programming tell us what kind of value we are dealing with. For example, whether we are operating on numbers or text. Is it a collection of letters in the alphabet or a combination of different types? The computer gets to know about it with the help of data types.
So, does every Java variable use a data type? The answer is yes. It is compulsory for all variable values to have a data type in the Java programming language.
A variableโs type is needed for its declaration to let the compiler know how to process the data it is storing. We all know Java is a statically typed language, meaning Java Data Type of variable should be defined in advance.ย This way, the computer gets to know how much space to allocate.
So, how are data types classified in Java? Let us see!
Two Main Types Of Data Types In Java:
In Java, Data types are mainly classified into two types:
Now, let us understand what are primitive and non-primitive data types below. Read below to know!
Primitive Data Types:
These are a basic data types that stores the actual value. Primitive Data types are allocated Stack memory. They do not share their state with other primitive values and help us to represent simple values..
Non-Primitive (Reference) Data Types:
Reference data type stores references to objects meaning the pointย to addresses of actual data rather than storing them directly. E.g. โ objects, arrays, enums, etc. In this discussion, we will explore primitive Java Data Types and non-primitive data types in Java.
ย If you face any difficulties learning about the below data types then worry not, you can take Java homework assistance from CodingZap experts and clear your confusion.
Primitive Data Types Supported In Java
The primitive data types are like the basic or foundational data types in Java programming. Let us discuss the eight primitive data types used in Java.
A primitive data type is declared using a reserved keyword. Weโll also see some of their details like size, uses, and default values. Let’s get started!
1. Byte
ย The first primitive data type is Byte. The `byte` is a primitive data type used to represent small signed integer values using 8 bits (1 byte).
Size: A `byte` occupies 8 bits in memory.
Range: A byte range It can hold value from -128 (minimum value) to 127 (maximum value)
Use: Byte is typically used when memory saving is more important. Often used in cases like read/write binary files, networking, and other low-level operations.
Default Value: 0
Example Code for Byte data type:
public class ByteExample {
public static void main(String[] args) {
byte temperature = -10;
System.out.println(temperature);
}
}
In this example, the `temperature` variable is declared as a byte and assigned the value -10. Since -10
falls within the range of a byte, this code is valid and demonstrates the use of the` byte` data type. The output can be seen in the image below.
2. Short data type
The short data type is a primitive data type that is a 16-bit signed two’s complement integer. Its details are given below.
Size: A `short` takes up 16 bits (2 bytes) in memory.
Range: minimum value of -32,768 to maximum value of 32,767
Use : Due to its larger size compared to `byte` , it is used to store the value that exceeds -128 to -127
range but still within limited range of numbers.
Default Value: 0
Example Java Code short data type:
public class ShortExample {
public static void main(String[] args) {
short studentsCount = 20000;
System.out.println("student count: " + studentsCount);
}
}
Output:
In this example, `studentsCount` variable is declared as `short` as it will hold value 20000 as it falls
within its range.
3. intย data type
The int type in Java is a 32-bit signed two’s complement integer. It further has two types: signed integer and unsigned integer types. `int` data type is used to store an integer number (integral values without a decimal point.)
Size: int data type takes up 32 bits (4 bytes) in memory.
Range: -2^31 to 2^31 + 1
Use: It is most used data type in programming due to its extended range and suitable for mathematical calculations.
Default Value: 0
Example Java Code int data type:
public class IntExample {
public static void main(String[] args) {
int bankBalance = 8000000;
System.out.println("Balance in Bank: " + bankBalance);
}
}
Output:
In this code, an integer variable `bankBalance` is declared and assigned the value 8000000 (8 million)
since 8 million falls between approximate range of 2.1 billion. Therefore, `int` is suitable data type to
hold such values.
4. long dataย type
This data type is a 64-bit signed two’s complement integer. It is used to store very large numbers. Find its details below!
Size: long data type takes up 64 bits (8 bytes) in memory.
Range: -2^63 to 2^63 + 1
Use: long is used when dealing with larger numbers. Remember long occupies more memory and it is
slower than int, short and byte in terms of processing.
Default Value: 0L (L is suffix)
Example Java Code long data type:
public class LongExample {
public static void main(String[] args) {
long worldPopulation = 7800000000L;
System.out.println("World Population: " + worldPopulation);
}
}
Output:
In this code, `worldPopulation` is declared as long and assigned the value `7800000000L`. The use of
`L` at the end of 7800000000 indicates itโs a long literal.
**Starting from Java Se 8 or later version, long has unsigned 64 bit range where minimum is 0 and
the maximum is 2^64-1.
5. float data type
The `float` data type is a 32-bit single-precision IEEE 754 floating point data type. As the name suggests, it is used to store
floating-point numbers. However, it has limitations on precision. The float data type internally rounds
off values, making it unsuitable for scenarios where precision is crucial. There’s a difference between double and float datatypes in Java.
Size: float data type takes up 64 bits (8 bytes) in memory.
Range: range of approximately ยฑ1.4e-45 to ยฑ3.4e+38.
Use: Use the float data type when you need to store floating point numbers and are willing to trade off some precision for memory efficiency. And are willing to trade off some precision for memory efficiency.
Default Value: 0.0f (f is suffix)
Example Java Code float data type:
public class FloatExample {
public static void main(String[] args) {
float distance = 150.25f;
float time = -42.3e3f; // Scientific Notation -42.3 * 10 ^3
System.out.println("Distance: " + distance);
System.out.println("Time: " + time);
}
}
Output:
Distance: 150.25
Time: -42300.0
In the above code and output, the `distance` variable declared demonstrates the use of float with the suffix
f, `time` variable demonstrate the scientific way of declaring float value.
6. double data type
The `double` data type is a 64-bit double-precision data type. `double` can stored much larger decimal
value and provides more accuracy as compared to double.
By Default, If Suffix `L` is not present then floating-point literals are considered as `double`.
Size: 64 bit
Range: ยฑ4.9e-324 to ยฑ1.8e+308.
Use: Helpful in financial calculations when we need to store decimal values with higher precision.
However, minimal rounding errors will still be there. So, in case you need precise values, the double data type shouldnโt be used.
Example Java Code double data type:
public class DoubleExample {
public static void main(String[] args) {
double gravity = 27.5;
double pi = 3.141592653589793;
System.out.println("Gravity: " + gravity);
System.out.println("Pi: " + pi);
}
}
Output:
In the code, we can observe two `double` variable each having different precisions which demonstrate
the use and range of `double` data type
7. char data type
The `char` data type is used to represent a single character. It occupies 16 bits of space in memory.
It represent this characters using Unicode encoding which allows itto handle single characters, letters,
symbols, punctuation, escape sequences etc.
Use: Helpful in processing strings, handling text input and performing character based operations.
Default Value: ‘\u0000’ (0)
Example Java Code char data type:
public class CharExample {
public static void main(String[] args) {
char letter = 'A';
char digit = '5';
char percent = '%';
char e = '\u0065';
System.out.println("Letter: " + letter);
System.out.println("Digit: " + digit);
System.out.println("Symbol: " + percent);
System.out.println("Small E: " + e);
}
}
Output:
The output displays the characters for ‘A’, ‘5’, and ‘%’ as expected, and it shows the lowercase letter
‘e’ for the e variable, which was assigned the Unicode code point \u0065.
8. boolean data type
The `boolean` data type has only two values `true` and `false`.
Default value: false
Use: It is mainly used in conditional statements and expressions to determine whether certain
conditions are met or not. Often used with ( >= , <= , ! , == , || , && ) operators.
Example Java Code boolean data type:
public class BooleanExample {
public static void main(String[] args) {
boolean isRaining = true;
boolean hasUmbrella = false;
boolean office = (isRaining && !hasUmbrella) ;
System.out.println("Should Go to Office ? : " + office);
// Consider true = Yes and False = No
}
}
Output:
In this example, the code uses boolean variables to represent whether it’s raining and whether the
person has an umbrella. The program then uses logical operators to check the conditions and prints
whether a person should go to the office.
Non-Primitive Data Types Supported In Java
The non-primitive data types (reference types) in Java are used to refer to the objects. In this article, we will discuss what are the 5 non primitive data types in Java. Let us move forward without any other discussion!
1. Arrays
An array data type stores the elements of the same data type. For instance, marks obtained by a student in different subjects can be stored together in an array.
A byte can be used in large arrays to save memory especially where memory savings are required.It is a user-defined data type that needs to be declared using an array name and a primitive type.
They can be used as a method parameter or local variable. The memory address of the first element ( array[0]) is stored, the following elements are stored in continuous addresses.
To know how to implement an array and its methods in Java, you can check out our article – Java Array Methods.
2. Strings
A string is an array of characters. Although the string class is non-primitive, it is predefined in Java like other primitive types and is also one of the most basic data types in the language.
String literals are declared using double quotes and the string objects are immutable. In Java, strings are not terminated with the null character unlike in C or C++. Below is a coding example for using strings.
Example Java Code string data type:
public class StringExample {
public static void main(String[] args) {
String st = "Welcome to Codingzap!";
System.out.println(st);
}
}
Output:
So here, we have a series of characters enclosed in the double quotes. Such series form character strings. We have given the name ‘st’ to the string variable.
3. Class
A class is like a container for objects. It is a blueprint to create objects. They can have different variables and methods having various data types in them. A class contains methods and behaviour of an object.
To declare a class in Java, you simply have to use the ‘class’ keyword followed by the class name you want. Let us see an example class below.
Example Java Code Class:
public class ClassExample {
int num1;
int num2;
public void addition(){
System.out.println("The sum of two numbers is: "+ (num1+num2));
}
public static void main(String[] args) {
ClassExample obj = new ClassExample();
obj.num1 = 2;
obj.num2 = 3;
obj.addition();
}
}
Output:
In the above code, we have a class ‘ClassExample’ that is performing addition on two integer class variable values (num1 and num2.) We have an object ‘obj’ of the class ClassExample that has num1 and num2 as the attributes.
4. Interface
Just like we say that a class is a blueprint of an object, interfaces are a blueprint for creating a class. The difference between a class and an interface is that an interface consists of abstract methods. The following example will help you to understand it.
Example Java Code Interface:
interface printable {
void print();
}
public class InterfaceExample implements printable {
public void print(){
System.out.println("Welcome to Codingzap!");
}
public static void main(String[] args) {
InterfaceExample obj = new InterfaceExample();
obj.print();
}
}
Output:
Alright! So, here we will need to save this program in a file named ‘InterfaceExample.java’ . We have created an interface printable having the method print().
Java is an object-oriented programming language and it makes use of classes and objects throughout the code you write. These can be successfully created by keeping in mind the correct Java data types for storing variable values.
Conclusion:
In Summary, Primitive Data types storeย the actual value and are more memory efficient. In Contrast,
Reference Data types store the reference or we can say it points to the address of actual data.
Understanding which data type to use in software applications is crucial as it helps to avoid errors and saves memory. If youโre interested to know about data types in JavaScript, you can check out our article.
Takeaways:
Java data types are used to store and save memory for variable values. Whether you are using numeric values or characters, there is a data type for all!
We have found the answer to the question of how many numeric data types are supported in Java. There are six in total – four for integer data types and two for floating-point types and support arithmetic operations on them.
There are eight primitive data types in Java that are at a fundamental level.
Understanding data types will help you in efficient data manipulation and saving memory.