Primitive Types
Java has 8 primitive data types:
Integer Types:
- byte: 8-bit (-128 to 127)
- short: 16-bit (-32,768 to 32,767)
- int: 32-bit (most common)
- long: 64-bit (for large numbers)
Floating Point:
- float: 32-bit single precision
- double: 64-bit double precision (most common)
Other:
- char: 16-bit Unicode character
- boolean: true or false
Wrapper Classes: Each primitive has an object wrapper: Integer, Double, Boolean, etc. Used for collections and null values.
Type Casting:
- Widening (implicit): smaller to larger type
- Narrowing (explicit): larger to smaller type
Code Examples
Java Data Typesjava
public class DataTypes {
public static void main(String[] args) {
// Integer types
byte smallNum = 100;
short shortNum = 30000;
int number = 2000000000;
long bigNum = 9223372036854775807L; // L suffix for long
// Floating point
float decimal = 3.14f; // f suffix for float
double precise = 3.141592653589793;
// Character and boolean
char letter = 'A';
char unicode = '\u0041'; // Also 'A'
boolean isJavaFun = true;
// Printing types
System.out.println("int: " + number);
System.out.println("double: " + precise);
System.out.println("char: " + letter);
System.out.println("boolean: " + isJavaFun);
// Type casting
int intValue = 100;
double doubleValue = intValue; // Widening (automatic)
System.out.println("Widened: " + doubleValue);
double pi = 3.14159;
int truncated = (int) pi; // Narrowing (explicit cast)
System.out.println("Truncated: " + truncated);
// Wrapper classes
Integer wrappedInt = Integer.valueOf(42);
int unwrapped = wrappedInt.intValue();
// Auto-boxing and unboxing
Integer autoBoxed = 100; // Auto-boxing
int autoUnboxed = autoBoxed; // Auto-unboxing
}
}Java is strongly typed - you must declare the type of every variable. Wrapper classes allow primitives to be used as objects.
Quick Quiz
1. Which primitive type should you use for precise decimal calculations?
2. What suffix is required for a long literal?
Was this lesson helpful?