Data Types
In Java, data types are used to define the type of data a variable can hold. Data types determine the size and format of data that can be stored in a variable, as well as the operations that can be performed on that data. Java has two categories of data types: primitive data types and reference data types. In this documentation, we will explore both categories in detail.
Primitive Data Types
Primitive data types are the fundamental data types provided by Java, and they are divided into four categories: integral, floating-point, character, and boolean. Let's take a closer look at each of these types.
Integral Data Types
byte
Size: 8 bits (1 byte)
Range: -128 to 127
Example:
byte age = 30;
short
Size: 16 bits (2 bytes)
Range: -32,768 to 32,767
Example:
short distance = 1000;
int
Size: 32 bits (4 bytes)
Range: -2^31 to 2^31-1
Example:
int population = 1000000;
long
Size: 64 bits (8 bytes)
Range: -2^63 to 2^63-1
Example:
long bigNumber = 1000000000L; // Note the 'L' suffix to indicate a long literal
Floating-Point Data Types
float
Size: 32 bits (4 bytes)
Example:
float temperature = 98.6f; // Note the 'f' suffix to indicate a float literal
double
Size: 64 bits (8 bytes)
Example:
double pi = 3.14159265359;
Character Data Type
char
Size: 16 bits (2 bytes)
Represents a single Unicode character.
Example:
char grade = 'A';
Boolean Data Type
boolean
Size: JVM-dependent (commonly 1 bit)
Represents true or false.
Example:
boolean isJavaFun = true;
Reference (Non-Primitive) Data Types
Reference data types are used to refer to objects. These data types do not store the actual data but store references to the memory location where the data is stored. Common reference data types include:
String
Used to store a sequence of characters.
Example:
String greeting = "Hello, World!";
Arrays
Used to store multiple values of the same data type.
Example:
int[] numbers = {1, 2, 3, 4, 5};
Classes
User-defined data types that can have attributes and methods.
Example:
class Person { String name; int age; }
Interfaces
Defines a contract for implementing classes.
Example:
interface Drawable { void draw(); }
Enums
A special data type for a predefined set of constants.
Example:
enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
Understanding Java data types is essential for writing effective and efficient Java programs. You should choose the appropriate data type for your variables based on the nature of the data you intend to store. Keep in mind the size and range of the data types to prevent overflow or loss of precision.
Last updated
Was this helpful?