Data types in Java are fundamental to the language. They define the kind of values that variables can hold and how those values behave. In this tutorial, we'll explore Java's data types, from simple primitive types to more complex reference types, ensuring that learners of all levels can grasp this crucial concept.
Definition: Primitive data types represent single values and have predefined behaviors in Java.
Examples:
There are eight primitive data types in Java:
Data Type | Size | Description |
---|---|---|
byte | 1 byte | Stores whole numbers from -128 to 127 |
short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
boolean | 1 bit | Stores true or false values |
char | 2 bytes | Stores a single character/letter or ASCII values |
In Java, numbers come in two flavors: integers (whole numbers) and floating-point (decimal numbers). Let's break them down, keeping it concise and easy to understand.
Integer Types
Range: -128 to 127. Memory-efficient for small numbers.
byte age = 25;
Range: -32768 to 32767. Useful for a wider range of numbers.
short distance = 5000;
Range: -2147483648 to 2147483647. Commonly used for whole numbers.
int population = 100000;
Range: -9223372036854775808 to 9223372036854775807. For very large values; end with 'L'.
long bigNumber = 15000000000L;
You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should end the value with an "f" for floats and "d" for doubles:
float price = 5.75f; double pi = 3.1415;
Use float when memory is a concern, but remember it has lower precision. For most calculations, it's safer to use double, which provides higher precision (about 15 digits).
boolean: Stores either true or false.
boolean flag1=true; boolean flag2=false;
char: Stores a single character, enclosed in single quotes, e.g., 'A'. Example: char myGrade = 'A';
Alternatively, if you are familiar with ASCII values, you can use those to display certain characters .
Example : char myVar1 = 65 // output := A
Non-primitive data types are called reference types. Reference data types don't store the data itself but store references (memory addresses) to objects.
Examples: String: Stores sequences of characters. User-defined classes: Custom data types created by the programmer.