Day 2: Variables and Data Types
What You'll Learn Today
- Declaring and initializing variables
- Primitive types (all 8)
- Reference types basics
- Type conversion (casting)
- Operators
Variables
A variable is a container that holds a value. Since Java is a statically typed language, you must declare the type of every variable before using it.
// type variableName = value;
int age = 25;
String name = "Alice";
double price = 1980.5;
boolean isActive = true;
Naming Conventions
// OK
int myAge = 25;
String firstName = "Alice";
final int MAX_SIZE = 100;
// Not allowed
int 1stNumber = 10; // Starts with a digit
int my-age = 25; // Hyphens not allowed
int class = 1; // Reserved keyword
| Convention | Example | Used For |
|---|---|---|
| camelCase | myVariableName |
Variables and methods |
| PascalCase | MyClassName |
Classes |
| UPPER_SNAKE_CASE | MAX_VALUE |
Constants |
Primitive Types
Java has 8 primitive types.
flowchart TB
subgraph Primitive["Primitive Types"]
subgraph Integer["Integer Types"]
Byte["byte<br>8-bit"]
Short["short<br>16-bit"]
Int["int<br>32-bit"]
Long["long<br>64-bit"]
end
subgraph Float["Floating-Point Types"]
FloatT["float<br>32-bit"]
Double["double<br>64-bit"]
end
Char["char<br>16-bit"]
Bool["boolean<br>true/false"]
end
style Int fill:#3b82f6,color:#fff
style Double fill:#22c55e,color:#fff
style Char fill:#f59e0b,color:#fff
style Bool fill:#8b5cf6,color:#fff
Integer Types
byte b = 127; // -128 to 127
short s = 32767; // -32,768 to 32,767
int i = 2147483647; // -2^31 to 2^31-1 (approx. 2.1 billion)
long l = 9223372036854775807L; // -2^63 to 2^63-1
| Type | Size | Range | Use Case |
|---|---|---|---|
byte |
1 byte | -128 to 127 | Binary data |
short |
2 bytes | -32,768 to 32,767 | Rarely used |
int |
4 bytes | approx. +/- 2.1 billion | Most common |
long |
8 bytes | approx. +/- 9.2 quintillion | Very large numbers |
Recommendation: Use
intfor integers by default. AppendLtolongliterals.
Floating-Point Types
float f = 3.14f; // Must have trailing f
double d = 3.14159; // Default floating-point type
| Type | Size | Precision | Use Case |
|---|---|---|---|
float |
4 bytes | ~7 digits | Rarely used |
double |
8 bytes | ~15 digits | Most common |
Recommendation: Use
doublefor decimal numbers by default.
Character and Boolean Types
char c = 'A'; // Single quotes
char jp = '\u3042'; // Unicode character
boolean flag = true; // true or false
Reference Types Basics
Everything that is not a primitive type is a reference type. The most common example is String.
String greeting = "Hello";
String name = new String("Alice");
// String supports concatenation with +
String message = greeting + ", " + name + "!";
System.out.println(message); // Hello, Alice!
Primitive vs. Reference Types
flowchart LR
subgraph Prim["Primitive Type"]
Var1["age = 25"]
Stack1["Stack: 25"]
end
subgraph Ref["Reference Type"]
Var2["name"]
Stack2["Stack: reference"]
Heap["Heap: \"Alice\""]
end
Var1 --> Stack1
Var2 --> Stack2 --> Heap
style Prim fill:#3b82f6,color:#fff
style Ref fill:#22c55e,color:#fff
| Feature | Primitive Type | Reference Type |
|---|---|---|
| Stores | The value itself | A memory address (reference) |
| Default value | 0, false |
null |
| Examples | int, boolean |
String, arrays |
var (Local Variable Type Inference)
Since Java 10, you can use var to let the compiler infer the type:
var count = 10; // Inferred as int
var name = "Alice"; // Inferred as String
var price = 19.99; // Inferred as double
var items = new ArrayList<String>(); // Inferred as ArrayList<String>
Note:
varcan only be used with local variables. It cannot be used for fields or method parameters.
Constants (final)
final int MAX_SIZE = 100;
final double TAX_RATE = 0.10;
final String APP_NAME = "MyApp";
// MAX_SIZE = 200; // Compile error!
Convention: Constants use UPPER_SNAKE_CASE (e.g.,
MAX_SIZE).
Type Conversion (Casting)
Implicit Conversion (Widening)
Smaller types are automatically converted to larger types:
int i = 100;
long l = i; // int -> long (automatic)
double d = i; // int -> double (automatic)
Explicit Conversion (Narrowing)
Larger types require an explicit cast to convert to smaller types:
double d = 3.99;
int i = (int) d; // 3 (decimal part is truncated)
long l = 100L;
int j = (int) l; // 100
flowchart LR
Byte["byte"] --> Short["short"] --> Int["int"] --> Long["long"] --> Float["float"] --> Double["double"]
style Int fill:#3b82f6,color:#fff
style Double fill:#22c55e,color:#fff
Caution: Narrowing conversions can result in data loss.
Operators
Arithmetic Operators
int a = 10, b = 3;
System.out.println(a + b); // 13 (addition)
System.out.println(a - b); // 7 (subtraction)
System.out.println(a * b); // 30 (multiplication)
System.out.println(a / b); // 3 (integer division)
System.out.println(a % b); // 1 (remainder)
Caution: Integer division truncates the decimal part.
10 / 3evaluates to3.
Assignment Operators
int x = 10;
x += 5; // x = x + 5 -> 15
x -= 3; // x = x - 3 -> 12
x *= 2; // x = x * 2 -> 24
x /= 4; // x = x / 4 -> 6
x %= 4; // x = x % 4 -> 2
Increment and Decrement
int count = 0;
count++; // 1 (postfix)
++count; // 2 (prefix)
count--; // 1 (postfix)
--count; // 0 (prefix)
Comparison Operators
int a = 10, b = 20;
a == b // false (equal to)
a != b // true (not equal to)
a > b // false (greater than)
a < b // true (less than)
a >= b // false (greater than or equal to)
a <= b // true (less than or equal to)
Logical Operators
boolean x = true, y = false;
x && y // false (AND)
x || y // true (OR)
!x // false (NOT)
Basic String Operations
String s = "Hello, Java!";
s.length() // 12 (number of characters)
s.charAt(0) // 'H' (character at index 0)
s.toUpperCase() // "HELLO, JAVA!"
s.toLowerCase() // "hello, java!"
s.contains("Java") // true
s.startsWith("Hello") // true
s.substring(0, 5) // "Hello"
s.replace("Java", "World") // "Hello, World!"
s.trim() // Removes leading/trailing whitespace
s.isEmpty() // false
Important:
Stringis immutable. Calling a method on a string does not modify the original -- it returns a new string.
Practice: BMI Calculator
public class BmiCalculator {
public static void main(String[] args) {
double height = 1.70; // meters
double weight = 65.0; // kilograms
double bmi = weight / (height * height);
System.out.println("=== BMI Calculator ===");
System.out.printf("Height: %.2f m%n", height);
System.out.printf("Weight: %.1f kg%n", weight);
System.out.printf("BMI: %.1f%n", bmi);
// Classification
String category;
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 25.0) {
category = "Normal weight";
} else if (bmi < 30.0) {
category = "Overweight";
} else {
category = "Obese";
}
System.out.printf("Category: %s%n", category);
}
}
Summary
| Concept | Description |
|---|---|
| Variable | Declare a type and store a value |
| Primitive types | int, double, boolean, char, and 4 others (8 total) |
| Reference types | String and other objects (stored by reference) |
var |
Local variable type inference (Java 10+) |
final |
Constant (cannot be reassigned) |
| Casting | (int) 3.14 for type conversion |
| Operators | Arithmetic, comparison, logical, assignment |
Key Takeaways
- Use
intfor integers anddoublefor decimals as your defaults Stringis a reference type and is immutable- Integer division truncates the decimal part
- Widening conversions are automatic; narrowing conversions require a cast
Exercises
Exercise 1: Basic
Write a program that stores a circle's radius as a double, then calculates and displays its area and circumference.
Exercise 2: Applied
Write a program that converts a temperature from Fahrenheit to Celsius using the formula: Celsius = (Fahrenheit - 32) * 5 / 9.
Exercise 3: Challenge
Write a program that takes a number of seconds as an int and displays it in the format "X hours Y minutes Z seconds" (e.g., 3661 seconds -> 1 hour 1 minute 1 second).
References
Next up: On Day 3, we'll tackle Control Flow. You'll learn how to use if statements, switch expressions, and loops to control program execution.