Data Types
Java has two top-level type families: primitives (8 of them, stored by value) and references (everything else, including String and the boxed wrappers).
The 8 primitives + their wrappers
EXAMPLE
// Integers Default Wrapper
byte b = 1; // 0 Byte
short s = 2; // 0 Short
int i = 3; // 0 Integer
long l = 4L; // 0L Long
// Floats
float f = 1.5f; // 0.0f Float
double d = 2.5; // 0.0d Double
// Other
boolean t = true; // false Boolean
char c = 'A'; // '\u0000' Character
// Strings are objects, not primitives
String name = "Ada"; // null String
// Autoboxing / autounboxing
List<Integer> ages = new ArrayList<>();
ages.add(36); // auto-box int → Integer
int a = ages.get(0); // auto-unbox
// Don't use == on objects — use equals()
String a1 = new String("hi");
String a2 = new String("hi");
System.out.println(a1 == a2); // false (different objects)
System.out.println(a1.equals(a2)); // true
Why it matters
Reach for BigDecimal for money — double can’t represent 0.10 + 0.20 exactly. Optional<T> on return types is the modern way to say “might be empty”.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
byte b = 1; short s = 2; int i = 3; long l = 4L; float f = 1.5f; double d = 2.5; boolean t = true; char c = 'A';Try it Yourself »
Discussion
Loading…