Data Types
Primitive and reference types
Introduction
In this lesson, you'll learn about data types in Java. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with primitive and reference types.
Java has its own approach to primitive and reference types, which we'll explore step by step.
The Java Way
Let's see how Java handles this concept. Here's a typical example:
// Java types - guaranteed sizes
byte b = 127; // 8 bits, signed
short s = 100; // 16 bits
int i = 1000; // 32 bits
long l = 100000L; // 64 bits
float f = 3.14f;
double d = 3.14159;
char c = 'A'; // 16 bits, Unicode
boolean flag = true; // true or falseComparing to C
Here's how you might have written similar code in C:
// C types - platform dependent
char c = 'A'; // 8 bits
short s = 100; // at least 16 bits
int i = 1000; // at least 16 bits
long l = 100000L; // at least 32 bits
float f = 3.14f;
double d = 3.14159;
int flag = 1; // no booleanYou may be used to different syntax or behavior.
Java has boolean type (true/false)
You may be used to different syntax or behavior.
char is 16-bit Unicode, not 8-bit ASCII
You may be used to different syntax or behavior.
Type sizes are guaranteed across platforms
You may be used to different syntax or behavior.
byte type for 8-bit signed integers
Step-by-Step Breakdown
1. Boolean Type
Java has a real boolean type. No more using 0 and 1.
int isValid = 1;
if (isValid) { ... }boolean isValid = true;
if (isValid) { ... }2. Character Type
Java char is 16-bit Unicode, supporting international characters.
char c = 'A'; // ASCII onlychar c = 'A'; // ASCII works
char unicode = 'δΈ'; // Unicode too!
char emoji = 'π'; // Even emojis (with limits)3. Wrapper Classes
Each primitive has a wrapper class for when you need an object.
// Primitives
int x = 42;
double d = 3.14;
// Wrapper classes (needed for generics, null)
Integer xObj = 42; // auto-boxing
Double dObj = 3.14;
// Useful methods
int parsed = Integer.parseInt("42");
String str = Integer.toString(42);Common Mistakes
When coming from C, developers often make these mistakes:
- Java has boolean type (true/false)
- char is 16-bit Unicode, not 8-bit ASCII
- Type sizes are guaranteed across platforms
Key Takeaways
- Java has boolean (true/false)
- char is 16-bit Unicode
- All type sizes are guaranteed
- Wrapper classes provide object versions