Lesson 7 +10 XP

Java Data Types

Java Data Types

A data type defines what kind of value a variable can hold. Java has two groups: primitive types and reference types.

Primitive data types

Primitive types are built into Java and store single values:

TypeSizeStores
byte1 byteWhole numbers from -128 to 127
short2 bytesWhole numbers from -32768 to 32767
int4 bytesWhole numbers from -2147483648 to 2147483647
long8 bytesVery large whole numbers
float4 bytesDecimal numbers
double8 bytesDecimal numbers with more precision
boolean1 bittrue or false
char2 bytesA single character, written in single quotes

Examples

int myNum = 5;
float myFloat = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";

int vs double

  • Use int for whole numbers like 42.
  • Use double for numbers with decimals like 3.14.

float vs double

Both store decimals. double is the default and is more precise. Use double unless you have a reason not to.

TL;DR

  • Primitive types store a single value.
  • Common types: int, double, boolean, char, and the String reference type.
  • char uses single quotes; String uses double quotes.