Java is statically typed and also a strongly typed language because each type of data, such as integer, character, hexadecimal, packed decimal etc. is predefined as part of the programming language, and all constants or variables defined for a given program must be declared with the specific data types.
Data types in Java are of different sizes and values that can be stored in a variable that is made as per convenience and circumstances to handle different scenarios or data requirements.
Why Data Types Matter in Java?
Data types matter in Java because of the following reasons, which are listed below:
- Memory Efficiency: Choosing the right type (byte vs int) saves memory.
- Performance: Proper types reduce runtime errors.
- Code Clarity: Explicit typing makes code more readable.
Java Data Type Categories
Java has two categories in which data types are segregated
1. Primitive Data Type: These are the basic building blocks that store simple values directly in memory. Examples of primitive data types are
- boolean
- char
- byte
- short
- int
- long
- float
- double
Note: The Boolean with uppercase B is a wrapper class for the primitive boolean type.
2. Non-Primitive Data Types (Object Types): These are reference types that store memory addresses of objects. Examples of Non-primitive data types are
- String
- Array
- Class
- Interface
- Object
The below diagram demonstrates different types of primitive and non-primitive data types in Java.
Primitive Data Types in Java
Primitive data store only single values and have no additional capabilities. There are 8 primitive data types. They are depicted below in tabular format below as follows:
Type | Description | Default | Size | Example Literals | Range of values |
---|
boolean | true or false | false | JVM-dependent (typically 1 byte) | true, false | true, false |
---|
byte | 8-bit signed integer | 0 | 1 byte | (none) | -128 to 127 |
---|
char | Unicode character(16 bit) | \u0000 | 2 bytes | 'a', '\u0041', '\101', '\\', '\', '\n', 'β' | 0 to 65,535 (unsigned) |
---|
short | 16-bit signed integer | 0 | 2 bytes | (none) | -32,768 to 32,767 |
---|
int | 32-bit signed integer | 0 | 4 bytes | -2,0,1 | -2,147,483,648 to 2,147,483,647 |
---|
long | 64-bit signed integer | 0L | 8 bytes | -2L,0L,1L | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
---|
float | 32-bit IEEE 754 floating-point | 0.0f | 4 bytes | 3.14f, -1.23e-10f | ~6-7 significant decimal digits |
---|
double | 64-bit IEEE 754 floating-point | 0.0d | 8 bytes | 3.1415d, 1.23e100d | ~15-16 significant decimal digits |
---|
1. boolean Data Type
The boolean data type represents a logical value that can be either true or false. Conceptually, it represents a single bit of information, but the actual size used by the virtual machine is implementation-dependent and typically at least one byte (eight bits) in practice. Values of the boolean type are not implicitly or explicitly converted to any other type using casts. However, programmers can write conversion code if needed.
Syntax:
boolean booleanVar;
Size : Virtual machine dependent (typically 1 byte, 8 bits)
Example: This example, demonstrating how to use boolean data type to display true/false values.
Java
// Demonstrating boolean data type
public class Geeks {
public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;
System.out.println("Is Java fun? " + b1);
System.out.println("Is fish tasty? " + b2);
}
}
OutputIs Java fun? true
Is fish tasty? false
2. byte Data Type
The byte data type is an 8-bit signed two's complement integer. The byte data type is useful for saving memory in large arrays.
Syntax:
byte byteVar;
Size : 1 byte (8 bits)
Example: This example, demonstrating how to use byte data type to display small integer values.
Java
// Demonstrating byte data type
public class Geeks {
public static void main(String[] args) {
byte a = 25;
byte t = -10;
System.out.println("Age: " + a);
System.out.println("Temperature: " + t);
}
}
OutputAge: 25
Temperature: -10
3. short Data Type
The short data type is a 16-bit signed two's complement integer. Similar to byte, a short is used when memory savings matter, especially in large arrays where space is constrained.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use short data type to store moderately small integer value.
Java
// Demonstrating short data types
public class Geeks {
public static void main(String[] args) {
short num = 1000;
short t = -200;
System.out.println("Number of Students: " + num);
System.out.println("Temperature: " + t);
}
}
OutputNumber of Students: 1000
Temperature: -200
4. int Data Type
It is a 32-bit signed two's complement integer.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer, which has a value in the range [0, 2 32 -1]. Use the Integer class to use the int data type as an unsigned integer.
Example: This example demonstrates how to use int data type to display larger integer values.
Java
// Demonstrating int data types
public class Geeks {
public static void main(String[] args) {
int p = 2000000;
int d = 150000000;
System.out.println("Population: " + p);
System.out.println("Distance: " + d);
}
}
OutputPopulation: 2000000
Distance: 150000000
5. long Data Type
The long data type is a 64-bit signed two's complement integer. It is used when an int is not large enough to hold a value, offering a much broader range.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2 64 -1. The Long class also contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic operations for unsigned long.
Example: This example demonstrates how to use long data type to store large integer value.
Java
// Demonstrating long data type
public class Geeks {
public static void main(String[] args) {
long w = 7800000000L;
long l = 9460730472580800L;
System.out.println("World Population: " + w);
System.out.println("Light Year Distance: " + l);
}
}
OutputWorld Population: 7800000000
Light Year Distance: 9460730472580800
6. float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you need to save memory in large arrays of floating-point numbers. The size of the float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
Example: This example demonstrates how to use float data type to store decimal value.
Java
// Demonstrating float data type
public class Geeks {
public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;
System.out.println("Value of Pi: " + pi);
System.out.println("Gravity: " + gravity);
}
}
OutputValue of Pi: 3.14
Gravity: 9.81
7. double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is generally the default choice. The size of the double data type is 8 bytes or 64 bits.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits)
Note: Both float and double data types were designed especially for scientific calculations, where approximation errors are acceptable. If accuracy is the most prior concern then, it is recommended not to use these data types and use BigDecimal class instead.
It is recommended to go through rounding off errors in java.
Example: This example demonstrates how to use double data type to store precise decimal value.
Java
// Demonstrating double data type
public class Geeks {
public static void main(String[] args) {
double pi = 3.141592653589793;
double an = 6.02214076e23;
System.out.println("Value of Pi: " + pi);
System.out.println("Avogadro's Number: " + an);
}
}
OutputValue of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23
8. char Data Type
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use char data type to store individual characters.
Java
// Demonstrating char data type
public class Geeks{
public static void main(String[] args) {
char g = 'A';
char s = '$';
System.out.println("Grade: " + g);
System.out.println("Symbol: " + s);
}
}
Why is the Size of char 2 bytes in Java?
Unlike languages such as C or C++ that use the ASCII character set, Java uses the Unicode character set to support internationalization. Unicode requires more than 8 bits to represent a wide range of characters from different languages, including Latin, Greek, Cyrillic, Chinese, Arabic, and more. As a result, Java uses 2 bytes to store a char, ensuring it can represent any Unicode character.
Example: Here we are demonstrating how to use various primitive data types.
Java
// Java Program to Demonstrate Char Primitive Data Type
class Geeks
{
public static void main(String args[])
{
// Creating and initializing custom character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i = 89;
// use byte and short
// if memory is a constraint
byte b = 4;
// this will give error as number is
// larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is
// larger than short range
// short s1 = 87878787878;
// by default fraction value
// is double in java
double d = 4.355453532;
// for float use 'f' as suffix as standard
float f = 4.7333434f;
// need to hold big range of numbers then we need
// this data type
long l = 12121;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
}
}
Outputchar: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Non-Primitive (Reference) Data Types
The Non-Primitive (Reference) Data Types will contain a memory address of variable values because the reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character array and a string in Java is, that the string is designed to hold a sequence of characters in a single variable whereas, a character array is a collection of separate char-type entities. Unlike C/C++, Java strings are not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example: This example demonstrates how to use string variables to store and display text values.
Java
// Demonstrating String data type
public class Geeks {
public static void main(String[] args) {
String n = "Geek1";
String m = "Hello, World!";
System.out.println("Name: " + n);
System.out.println("Message: " + m);
}
}
OutputName: Geek1
Message: Hello, World!
Note: String cannot be modified after creation. Use StringBuilder for heavy string manipulation
2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:
- Modifiers : A class can be public or has default access. Refer to access specifiers for classes or interfaces in Java
- Class name: The name should begin with an initial letter (capitalized by convention).
- Superclass(if any): The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
- Body: The class body is surrounded by braces, { }.
Example: This example demonstrates how to create a class with a constructor and method, and how to create an object to call the method.
Java
// Demonstrating how to create a class
class Car {
String model;
int year;
Car(String model, int year) {
this.model = model;
this.year = year;
}
void display() {
System.out.println(model + " " + year);
}
}
public class Geeks {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
myCar.display();
}
}
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of :
- State: It is represented by the attributes of an object. It also reflects the properties of an object.
- Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
- Identity: It gives a unique name to an object and enables one object to interact with other objects.
Example: This example demonstrates how to create the object of a class.
Java
// Define the Car class
class Car {
String model;
int year;
// Constructor to initialize the Car object
Car(String model, int year) {
this.model = model;
this.year = year;
}
}
// Main class to demonstrate object creation
public class Geeks {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Honda", 2021);
// Access and print the object's properties
System.out.println("Car Model: " + myCar.model);
System.out.println("Car Year: " + myCar.year);
}
}
OutputCar Model: Honda
Car Year: 2021
4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).
- Interfaces specify what a class must do and not how. It is the blueprint of the class.
- An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement.
- If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract.
- A Java library example is Comparator Interface. If a class implements this interface, then it can be used to sort a collection.
Example: This example demonstrates how to implement an interface.
Java
// Demonstrating the working of interface
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Woof");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
}
}
5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. The following are some important points about Java arrays.
- In Java, all arrays are dynamically allocated. (discussed below)
- Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using size.
- A Java array variable can also be declared like other variables with [] after the data type.
- The variables in the array are ordered and each has an index beginning with 0.
- Java array can also be used as a static field, a local variable, or a method parameter.
- The size of an array must be specified by an int value and not long or short.
- The direct superclass of an array type is Object.
- Every array type implements the interfaces Cloneable and java.io.Serializable.
Example: This example demonstrates how to create and access elements of an array.
Java
// Demonstrating how to create an array
public class Geeks {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
String[] arr = {"Geek1", "Geek2", "Geek3"};
System.out.println("First Number: " + num[0]);
System.out.println("Second Fruit: " + arr[1]);
}
}
OutputFirst Number: 1
Second Fruit: Geek2
Primitive vs Non-Primitive Data Types
The table below demonstrates the difference between Primitive and Non-Primitive Data types
Aspect | Primitive | Non-Primitive |
---|
Memory | Stored on the stack | Stored on the heap |
---|
Speed | Primitive data types are faster | Non-primitive data types are slower |
---|
Example | int x = 5; | String s = "Geeks"; |
---|
Understanding Java’s data types is fundamental to efficient programming. Each data type has specific use cases and constraints, making it essential to choose the right type for the task at hand. This ensures optimal memory usage and program performance while leveraging Java’s strong typing system to catch errors early in the development process.
Check Out: Quiz on Data Type in Java
Similar Reads
Basics of Java
Learn Java - A Beginners Guide for 2024If you are new to the world of coding and want to start your coding journey with Java, then this learn Java a beginners guide gives you a complete overview of how to start Java programming. Java is among the most popular and widely used programming languages and platforms. A platform is an environme
10 min read
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Similarities and Difference between Java and C++Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as competitive programming. C++ is a widely popular language among coders for its efficiency, high speed, and dynamic
6 min read
Setting up Environment Variables For Java - Complete Guide to Set JAVA_HOMEIn the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win
6 min read
Java SyntaxJava is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand. Java Syntax refers to a set of rules that define how Java programs are w
6 min read
Java Hello World ProgramJava is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat
6 min read
Differences Between JDK, JRE and JVMUnderstanding the difference between JDK, JRE, and JVM plays a very important role in understanding how Java works and how each component contributes to the development and execution of Java applications. The main difference between JDK, JRE, and JVM is:JDK: Java Development Kit is a software develo
3 min read
How JVM Works - JVM ArchitectureJVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE (Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one
7 min read
Java IdentifiersAn identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name.Example:public class Test{ public static void main(String[] args) { int a = 2
2 min read
Variables & DataTypes in Java
Java VariablesIn Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated.Key Components of Variables in Java:A variable in Java has three components, which are listed below:Data Type: Defines the kind
9 min read
Scope of Variables in JavaThe scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about
7 min read
Java Data TypesJava is statically typed and also a strongly typed language because each type of data, such as integer, character, hexadecimal, packed decimal etc. is predefined as part of the programming language, and all constants or variables defined for a given program must be declared with the specific data ty
14 min read
Operators in Java
Java OperatorsJava operators are special symbols that perform operations on variables or values. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different
15 min read
Java Arithmetic Operators with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
6 min read
Java Assignment Operators with ExamplesOperators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
7 min read
Java Unary Operator with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they p
8 min read
Java Relational Operators with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
10 min read
Java Logical Operators with ExamplesLogical operators are used to perform logical "AND", "OR", and "NOT" operations, i.e., the functions similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consider
8 min read
Java Ternary OperatorOperators constitute the basic building block of any programming language. Java provides many types of operators that can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provi
5 min read
Bitwise Operators in JavaIn Java, Operators are special symbols that perform specific operations on one or more than one operands. They build the foundation for any type of calculation or logic in programming.There are so many operators in Java, among all, bitwise operators are used to perform operations at the bit level. T
6 min read
Packages in Java
Flow Control in Java
Loops in Java
Jump Statements in Java
Arrays in Java
Arrays in JavaArrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Java Multi-Dimensional ArraysMultidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T
10 min read
Jagged Array in JavaIn Java, a Jagged array is an array that holds other arrays. When we work with a jagged array, one thing to keep in mind is that the inner array can be of different lengths. It is like a 2D array, but each row can have a different number of elements.Example:arr [][]= { {10,20}, {30,40,50,60},{70,80,
6 min read
Strings in Java
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowi
9 min read
String Class in JavaA string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
7 min read
StringBuffer Class in JavaThe StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters.Features of StringBuffer ClassThe key features of StringBuffer c
11 min read
Java StringBuilder ClassIn Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations.Declaration:StringBuilder sb = new
7 min read
OOPS in Java
Java OOP(Object Oriented Programming) ConceptsJava Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Classes and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
11 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
8 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de
7 min read
Wrapper Classes in JavaA Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
6 min read
Need of Wrapper Classes in JavaFirstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These metho
3 min read