Understanding Java Data Types

In Java, data types define the type of data that a variable can hold. Java supports two categories of data types: Primitive Data Types and Reference Data Types.

Primitive Data Types

Integral Types:

  • byte: 8 bits, range: -128 to 127
  • short: 16 bits, range: -32,768 to 32,767
  • int: 32 bits, range: -231 to 231-1
  • long: 64 bits, range: -263 to 263-1
Floating-Point Types:
  • float: 32 bits, range: approximately ±3.4e38 (6-7 significant decimal digits)
  • double: 64 bits, range: approximately ±1.7e308 (15 significant decimal digits)
Character Type:
  • char: 16 bits, represents a single Unicode character
Boolean Type:
  • boolean: Represents true or false

Examples:

Here are examples of declaring variables with different primitive data types:


// Integral Types
byte myByte = 100;
short myShort = 2000;
int myInt = 50000;
long myLong = 123456789L;

// Floating-Point Types
float myFloat = 3.14f;
double myDouble = 2.71828;

// Character Type
char myChar = 'A';

// Boolean Type
boolean isJavaFun = true;

Note:

Understanding data types is crucial for effective programming. Choosing the right data type ensures optimal memory usage and avoids unexpected behavior in your Java programs.