Java data types

Java is statically typed. Its eight primitive types store numeric, boolean, or character values. Reference types include classes, interfaces, and arrays.

A simple example

Tell a number from text

  1. Start with 2 and "2"
  2. Do this Add or join
  3. Result 4 and 22
Adding two numbers gives 4. Joining two copies of the text gives the two characters 22.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(2 + 2);
        System.out.println("2" + "2");
    }
}
Output
4
22
Product label: 007. Quantity × price: 3 × 125¢. Line total: 375¢.
Keep a product code intact

A school shop sells three packs of paper at 125 cents each. Its scanner must print the code 007 exactly as it appears on the shelf. Keep the code as text and multiply the numeric quantity and price.

Primitive Data Types

Data Type Size Default value for fields
byte 1 byte 0
short 2 bytes 0
int 4 bytes 0
long 8 bytes 0L
float 4 bytes 0.0f
double 8 bytes 0.0d
boolean Implementation-dependent false
char 2 bytes '\u0000'

Non-Primitive Data Types

Fields and array elements receive default values. A local variable must be definitely assigned before it is read.

Data Type Size Default value for fields
String ~ null
array ~ null