Skip to main content

Java Primitive Data Types - Complete Cheatsheet

A comprehensive guide to Java's primitive data types with practical code snippets and their operations.

📋 Quick Navigation​


🔹 int (32-bit Integer)​

Declaration & Initialization​

int num = 42;                      // Basic declaration
int hex = 0x1A; // Hexadecimal: 26
int binary = 0b1010; // Binary: 10
int octal = 017; // Octal: 15
int negative = -100; // Negative number
int[] array = {1, 2, 3, 4, 5}; // Array declaration

Range & Limits​

int maxValue = 2147483647;         // Maximum value (2^31 - 1)
int minValue = -2147483648; // Minimum value (-2^31)
int overflow = Integer.MAX_VALUE + 1; // Results in: -2147483648 (overflow)

Common Operations​

int a = 10, b = 3;
int sum = a + b; // 13
int difference = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 1 (modulo)

Bitwise Operations​

int x = 12, y = 10;                // 12 = 1100, 10 = 1010
int and = x & y; // 8 (1000)
int or = x | y; // 14 (1110)
int xor = x ^ y; // 6 (0110)
int not = ~x; // -13 (bitwise complement)
int leftShift = x << 2; // 48 (multiply by 4)
int rightShift = x >> 2; // 3 (divide by 4)
int unsignedRight = x >>> 2; // 3 (unsigned right shift)

🔹 long (64-bit Integer)​

Declaration & Initialization​

long bigNum = 123456789L;          // L suffix required for literals
long hex = 0x1FFFFFFFFL; // Hexadecimal long
long binary = 0b101010101L; // Binary long
long fromInt = 42; // Automatic widening from int
long maxLong = 9223372036854775807L; // Maximum value

Range & Operations​

long a = 1000000000L;              // 1 billion
long b = 2000000000L; // 2 billion
long sum = a + b; // 3000000000L
long product = a * b; // 2000000000000000000L

// Overflow example
long overflow = Long.MAX_VALUE + 1; // Results in: -9223372036854775808L

Time & Large Numbers​

long currentTime = System.currentTimeMillis(); // Current timestamp
long nanoTime = System.nanoTime(); // High precision time
long fileSize = 1024L * 1024L * 1024L; // 1 GB in bytes

🔹 char (16-bit Character)​

Declaration & Initialization​

char letter = 'A';                 // Single character
char digit = '9'; // Digit character
char unicode = '\u0041'; // Unicode: 'A'
char escape = '\n'; // Escape sequence: newline
char fromInt = 65; // ASCII value: 'A'
char[] charArray = {'H', 'e', 'l', 'l', 'o'};

Unicode & Escape Sequences​

char tab = '\t';                   // Tab character
char backslash = '\\'; // Backslash
char quote = '\''; // Single quote
char euro = '€'; // Euro symbol
char emoji = '😀'; // Emoji (if supported)

Character Operations​

char ch = 'A';
int asciiValue = (int) ch; // 65
char nextChar = (char) (ch + 1); // 'B'
boolean isDigit = ch >= '0' && ch <= '9'; // false
boolean isUppercase = ch >= 'A' && ch <= 'Z'; // true
boolean isLowercase = ch >= 'a' && ch <= 'z'; // false

Range​

char minChar = '\u0000';           // Minimum: null character (0)
char maxChar = '\uFFFF'; // Maximum: 65535

🔹 boolean (true or false)​

Declaration & Initialization​

boolean isTrue = true;             // True value
boolean isFalse = false; // False value
boolean result = (5 > 3); // true (from comparison)
boolean[] flags = {true, false, true};

Logical Operations​

boolean a = true, b = false;
boolean and = a && b; // false (logical AND)
boolean or = a || b; // true (logical OR)
boolean not = !a; // false (logical NOT)
boolean xor = a ^ b; // true (logical XOR)

Short-Circuit Evaluation​

boolean result1 = false && (5/0 > 0);  // false, no division by zero
boolean result2 = true || (5/0 > 0); // true, no division by zero

Conditional Usage​

boolean canVote = age >= 18;
boolean isEligible = hasLicense && canVote && !isBanned;

if (isEligible) {
System.out.println("Eligible to vote");
}

🔹 double (64-bit Floating Point)​

Declaration & Initialization​

double pi = 3.14159;               // Decimal number
double scientific = 1.23e-4; // Scientific notation: 0.000123
double negative = -45.67; // Negative double
double fromInt = 42; // Automatic conversion from int
double infinity = 1.0 / 0.0; // Positive infinity
double nan = 0.0 / 0.0; // Not a Number (NaN)

Precision & Range​

double maxValue = 1.7976931348623157E308;     // Maximum value
double minValue = 4.9E-324; // Minimum positive value
double precision = 0.1 + 0.2; // 0.30000000000000004 (precision issue)

Mathematical Operations​

double a = 10.5, b = 3.2;
double sum = a + b; // 13.7
double product = a * b; // 33.6
double power = Math.pow(a, 2); // 110.25
double sqrt = Math.sqrt(25.0); // 5.0
double sin = Math.sin(Math.PI / 2); // 1.0

Special Values​

double positiveInf = Double.POSITIVE_INFINITY;
double negativeInf = Double.NEGATIVE_INFINITY;
double notANumber = Double.NaN;

boolean isInfinite = Double.isInfinite(1.0/0.0); // true
boolean isNaN = Double.isNaN(0.0/0.0); // true
boolean isFinite = Double.isFinite(3.14); // true

🔹 float (32-bit Floating Point)​

Declaration & Initialization​

float num = 3.14f;                 // f suffix required
float scientific = 1.23e-4f; // Scientific notation
float fromDouble = (float) 3.14159; // Explicit casting required
float negative = -45.67f; // Negative float
float[] floatArray = {1.1f, 2.2f, 3.3f};

Range & Precision​

float maxValue = 3.4028235E38f;    // Maximum value
float minValue = 1.4E-45f; // Minimum positive value
float precision = 0.1f + 0.2f; // 0.3 (better than double for this case)

Operations​

float a = 10.5f, b = 3.2f;
float sum = a + b; // 13.7f
float product = a * b; // 33.6f
float division = a / b; // 3.28125f

Comparison with double​

float f = 3.14f;
double d = 3.14;
boolean equal = (f == d); // true (automatic promotion)
boolean precise = (f == 3.14f); // true

🔹 byte (8-bit Integer)​

Declaration & Initialization​

byte small = 127;                  // Maximum value
byte negative = -128; // Minimum value
byte fromInt = (byte) 200; // Explicit casting (overflow: -56)
byte[] byteArray = {1, 2, 3, 4, 5};

Range & Operations​

byte min = -128;                   // Minimum value (-2^7)
byte max = 127; // Maximum value (2^7 - 1)
byte a = 10, b = 20;
int sum = a + b; // Promoted to int: 30
byte result = (byte) (a + b); // Explicit cast back to byte: 30

Common Use Cases​

// File I/O
byte[] fileData = new byte[1024];
// Network communication
byte[] packet = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello"
// Bit manipulation
byte flags = 0b10101010; // Binary representation

🔹 short (16-bit Integer)​

Declaration & Initialization​

short medium = 32767;              // Maximum value
short negative = -32768; // Minimum value
short fromInt = (short) 50000; // Explicit casting (overflow: -15536)
short[] shortArray = {100, 200, 300};

Range & Operations​

short min = -32768;                // Minimum value (-2^15)
short max = 32767; // Maximum value (2^15 - 1)
short a = 1000, b = 2000;
int sum = a + b; // Promoted to int: 3000
short result = (short) (a + b); // Explicit cast: 3000

Practical Usage​

// Audio samples (16-bit audio)
short[] audioData = new short[44100]; // 1 second at 44.1kHz
// Memory-efficient arrays
short[] coordinates = {100, 200, 150, 300};

🔹 Type Casting & Conversions​

Widening (Implicit) Conversions​

byte b = 10;
short s = b; // byte → short
int i = s; // short → int
long l = i; // int → long
float f = l; // long → float
double d = f; // float → double

// Direct chain
double result = 42; // int → double (automatic)

Narrowing (Explicit) Conversions​

double d = 123.45;
float f = (float) d; // 123.45f
long l = (long) f; // 123L
int i = (int) l; // 123
short s = (short) i; // 123
byte b = (byte) s; // 123

Overflow Examples​

int bigInt = 130;
byte smallByte = (byte) bigInt; // -126 (overflow)

long bigLong = 3000000000L;
int overflowInt = (int) bigLong; // -1294967296 (overflow)

String Conversions​

// Primitive to String
int num = 42;
String str1 = String.valueOf(num); // "42"
String str2 = num + ""; // "42" (concatenation)

// String to Primitive
String numStr = "123";
int parsed = Integer.parseInt(numStr); // 123
double parseDouble = Double.parseDouble("3.14"); // 3.14
boolean parseBool = Boolean.parseBoolean("true"); // true

🔹 Operations & Operators​

Arithmetic Operators​

int a = 10, b = 3;
int addition = a + b; // 13
int subtraction = a - b; // 7
int multiplication = a * b; // 30
int division = a / b; // 3 (integer division)
int modulo = a % b; // 1 (remainder)

Unary Operators​

int x = 5;
int positive = +x; // 5 (unary plus)
int negative = -x; // -5 (unary minus)
int preIncrement = ++x; // 6 (x becomes 6, returns 6)
int postIncrement = x++; // 6 (returns 6, x becomes 7)
int preDecrement = --x; // 6 (x becomes 6, returns 6)
int postDecrement = x--; // 6 (returns 6, x becomes 5)

Comparison Operators​

int a = 5, b = 10;
boolean equal = (a == b); // false
boolean notEqual = (a != b); // true
boolean less = (a < b); // true
boolean greater = (a > b); // false
boolean lessOrEqual = (a <= b); // true
boolean greaterOrEqual = (a >= b); // false

Assignment Operators​

int x = 10;
x += 5; // x = 15 (x = x + 5)
x -= 3; // x = 12 (x = x - 3)
x *= 2; // x = 24 (x = x * 2)
x /= 4; // x = 6 (x = x / 4)
x %= 4; // x = 2 (x = x % 4)

Bitwise Operators​

int a = 12, b = 10;                // 12 = 1100, 10 = 1010
int bitwiseAnd = a & b; // 8 (1000)
int bitwiseOr = a | b; // 14 (1110)
int bitwiseXor = a ^ b; // 6 (0110)
int bitwiseNot = ~a; // -13 (complement)
int leftShift = a << 2; // 48 (multiply by 2^2)
int rightShift = a >> 2; // 3 (divide by 2^2)
int unsignedRightShift = a >>> 2; // 3 (unsigned right shift)

🚀 Quick Reference Summary​

TypeSizeRangeDefaultSuffixExample
byte8-bit-128 to 1270nonebyte b = 100;
short16-bit-32,768 to 32,7670noneshort s = 1000;
int32-bit-2.1B to 2.1B0noneint i = 42;
long64-bit-9.2E18 to 9.2E180LLlong l = 123L;
float32-bit±3.4E38 (7 digits)0.0fffloat f = 3.14f;
double64-bit±1.8E308 (15 digits)0.0dddouble d = 3.14;
char16-bit0 to 65,535'\u0000'nonechar c = 'A';
boolean1-bittrue or falsefalsenoneboolean b = true;

🎯 Best Practices​

1. Choose Appropriate Types​

// Good - appropriate size
byte age = 25; // Age fits in byte range
int population = 1000000; // Population needs int
long worldPopulation = 7800000000L; // World population needs long

// Avoid - wasteful
long age = 25L; // Overkill for age
double simpleCounter = 1.0; // int would be better

2. Handle Overflow Carefully​

// Dangerous - can overflow
int result = Integer.MAX_VALUE + 1; // Overflows to negative

// Safe - check before operation
if (a <= Integer.MAX_VALUE - b) {
int result = a + b;
} else {
// Handle overflow case
long result = (long) a + b;
}

3. Floating Point Precision​

// Problematic - precision issues
double result = 0.1 + 0.2; // 0.30000000000000004

// Better - use BigDecimal for exact decimal arithmetic
BigDecimal bd1 = new BigDecimal("0.1");
BigDecimal bd2 = new BigDecimal("0.2");
BigDecimal result = bd1.add(bd2); // Exactly 0.3

// For comparisons
double a = 0.1 + 0.2;
double b = 0.3;
boolean equal = Math.abs(a - b) < 0.0001; // Use epsilon comparison

4. Efficient Operations​

// Multiplication/Division by powers of 2
int multiplyBy8 = x << 3; // Faster than x * 8
int divideBy4 = x >> 2; // Faster than x / 4

// Use appropriate literals
long big = 1000000000L; // Use L suffix
float precise = 3.14f; // Use f suffix to avoid double conversion

5. Initialization & Default Values​

// Primitives have default values in class fields
class Example {
int number; // Defaults to 0
boolean flag; // Defaults to false
double price; // Defaults to 0.0
}

// Local variables must be initialized
void method() {
int x; // Compilation error if used without initialization
int y = 0; // Must initialize before use
}