Java ยท Chapter 8 of 42

Java Data Types

Java has two categories of data types: primitive types (byte, short, int, long, float, double, char, boolean) and reference types (objects, arrays, Strings).

Each primitive type has a fixed size defined by the Java specification, unlike C where sizes are platform-dependent.

Syntax
int a;
double b;
char c;
boolean d;

Primitive types

int (4 bytes) and double (8 bytes) are the most commonly used numeric types. byte, short and long provide other integer ranges, float is a single-precision decimal, char stores a single 16-bit Unicode character, and boolean stores true/false.

Reference types

String, arrays, and custom classes are reference types โ€” they store a reference to an object in memory rather than the value itself.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    int a = 5;
    double b = 5.5;
    char c = 'A';
    boolean d = true;
    System.out.println(a + " " + b + " " + c + " " + d);
  }
}
Output
5 5.5 A true

Four primitive types are declared, initialized and printed.

Key points

  • Primitive types include int, double, char, boolean, byte, short, long, float.
  • Reference types include String, arrays and objects.
  • Primitive sizes are fixed by the Java spec, not the platform.
  • boolean stores only true or false.
๐Ÿ’ก Note: Java has no unsigned integer types except char, which behaves like an unsigned 16-bit value.

๐Ÿ“ Quick Quiz

1. Which type stores true/false?

2. Which is a reference type in Java?

3. How many bytes does an int occupy in Java?