Data types in Java

In Java, data types are divided into two categories: primitive data types and reference data types. Understanding these is crucial for effective programming in Java.

Primitive Data Types

Primitive data types are predefined by the language and named by a reserved keyword. They represent simple values and include:

Data TypeSizeRangeUse
byte8 bits-128 to 127Saving memory in large arrays
short16 bits-32,768 to 32,767Saving memory in large arrays
int32 bits-2^31 to 2^31-1Default choice for integer values
long64 bits-2^63 to 2^63-1Wider range than int
float32 bits±3.40282347E+38F (6-7 digits)Single-precision floating point calculations
double64 bits±1.79769313486231570E+308 (15 digits)Double-precision floating point calculations
boolean1 bit*true or falseFlags for true/false conditions
char16 bits‘\u0000’ to ‘\uffff’ (0 to 65,535)Storing characters

*Note: The exact size of a boolean is not precisely defined but is typically a single bit.

Reference Data Types

Reference data types are created using defined constructors of the classes. They are used to store references (addresses) of objects and can be used to call methods to perform certain operations. They include:

Data TypeDescriptionUse
ClassBlueprint for objects with data fields (attributes) and methodsCreating objects, defining methods and variables
InterfaceAbstract type specifying behavior that classes must implementAchieving abstraction and multiple inheritance
ArrayContainer holding a fixed number of values of a single typeStoring multiple values in a single variable
StringSpecial class for sequences of characters (immutable)Handling and manipulating textual data