← Back to Core Java Course | Chapter 1: Introduction & Basics | Lesson 8 of 12

Java Data Types

Primitive Data Types

Java splits its type system into 8 primitives (byte, short, int, long, float, double, char, boolean) baked directly into the language, versus reference types like String or arrays that point to objects on the heap.

Example: Primitive Data Types

java
public class Main {
	public static void main(String[] args) {
		int number = 5;       // primitive
		String text = "Hi";   // reference type - points to an object on the heap
		System.out.println(number + " " + text);
	}
}

Numeric Types

Choosing the right numeric size matters for memory and correctness: an int can hold about +-2.1 billion, so counting something that could exceed that (like a national population) needs a long instead.

Example: Numeric Types

java
public class Main {
	public static void main(String[] args) {
		int population = 2_100_000_000; // near int's ~2.1 billion limit
		long worldPopulation = 8_000_000_000L; // needs long - exceeds int's range
		System.out.println(population + " " + worldPopulation);
	}
}

Floating-Point Types

float and double both store fractional values using IEEE 754 floating-point representation, but double's extra bytes give it roughly twice the significant digits of precision, which is why it's the default choice for most decimal math in Java.

Example: Floating-Point Types

java
public class Main {
	public static void main(String[] args) {
		float f = 3.14f;
		double d = 3.14159265358979; // double holds roughly twice the significant digits
		System.out.println(f + " " + d);
	}
}

Character and Boolean Types

char stores exactly one 16-bit Unicode character in single quotes like A, while boolean can only ever hold true or false -- unlike C, Java never lets you treat an int as a boolean or vice versa.

Example: Character and Boolean Types

java
public class Main {
	public static void main(String[] args) {
		char grade = 'A';
		boolean passed = true;
		System.out.println(grade + " " + passed);
	}
}

Reference Data Types

String and arrays are reference types: the variable itself holds a memory address pointing to the actual object on the heap, which is why comparing two Strings with == compares addresses, not their text content.

Example: Reference Data Types

java
public class Main {
	public static void main(String[] args) {
		String a = new String("hi");
		String b = new String("hi");
		System.out.println(a == b);        // false - compares memory addresses
		System.out.println(a.equals(b));   // true - compares actual text content
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.