Variables & Primitive Types
Java is a strictly, statically-typed programming language. This means you must explicitly declare the data type of every variable before you store values in them, and this type cannot change later.
1 Primitive Data Types
Java features 8 built-in primitive data types. They store raw values directly in memory (on the stack) rather than references to objects:
| Type | Size | Default Value | Stores |
|---|---|---|---|
| byte | 1 byte (8 bits) | 0 | Integers from -128 to 127 |
| short | 2 bytes | 0 | Integers from -32,768 to 32,767 |
| int | 4 bytes | 0 | Integers from -2 Billion to 2 Billion (Standard default) |
| long | 8 bytes | 0L | Massive integers (must append `L` suffix) |
| float | 4 bytes | 0.0f | Single precision floating points (must append `f` suffix) |
| double | 8 bytes | 0.0d | Double precision floating points (Standard default) |
| boolean | 1 bit (virtual) | false | `true` or `false` values |
| char | 2 bytes | '\u0000' | Single UTF-16 characters (surrounded by single quotes) |
⚠️ Warning: If you write a decimal number like `3.14`, Java treats it as a `double`. If you attempt to assign it directly to a `float` variable without the `f` suffix (e.g. `float f = 3.14;`), the compiler will throw an error due to potential loss of precision.
2 Declaring and Casting Variables
Let's write a program declaring different data types and exploring widening vs. narrowing conversions:
Java — Data Types and Casting
▶ Run Code
public class Main {
public static void main(String[] args) {
int age = 25;
double price = 19.99;
float pi = 3.14159f;
long stars = 10000000000L;
char grade = 'A';
boolean isActive = true;
System.out.println("Integer value: " + age);
// Implicit Casting (Widening): Small to Large type
double castedAge = age;
System.out.println("Implicit cast (int -> double): " + castedAge);
// Explicit Casting (Narrowing): Large to Small type (risk of loss)
double score = 98.76;
int integerScore = (int) score; // Fractional part is truncated
System.out.println("Explicit cast (double -> int): " + integerScore);
}
}
3 Code Challenge
Challenge: Write a program that defines an integer representation of a product price (e.g. 299) and casting it to a double. Then, create a double representation of a temperature (e.g. 36.6) and manually narrow-cast it into an integer, printing both values to verify the truncation.