C
Java/Basics/Lesson 03

Java Variables, Data Types & Control Flow — The Real Starting Point

45 min·theory

Java Variables, Data Types & Control Flow — The Real Starting Point

🎯 By the End of This Lesson

After reading through this lesson, you will be able to confidently do the following 3 things.

  • ✅ Explain the difference between the 4 primitives used in real projects (int/double/boolean/char) out of the 8 primitive types
  • ✅ Know when to use for-each, for, while, and switch
  • ✅ Explain the integer division pitfall + type casting and the truncate behavior of (int) double

Treat the learning goals as a checklist — close this lesson only when you can answer all of them.

8 Primitive Types — No Need to Memorize Them All

Java Has 2 Categories

  • Primitive types — types that hold the actual value. 8 kinds.
  • Reference types — types that hold the address of an object. String, arrays, classes, etc.

Just memorize 4 primitives: int, double, boolean, char.

The 8 Primitives — One Table

TypeSizeRangeWhen to use
byte1 byte-128 ~ 127Rarely used. Binary processing only.
short2 bytes±32KRarely used.
int4 bytes±2.1BDefault for integers. Use this almost always.
long8 bytes±9.2×10^18Large numbers beyond int range (e.g., timestamps).
float4 bytes~7 decimal digitsInsufficient precision. Rarely used.
double8 bytes~15 decimal digitsDefault for decimals.
boolean1 bittrue/falseTrue/false.
char2 bytessingle characterOne character ('A').

Conclusion: At first, you only need to know int, double, boolean, and char.

Declaration and Assignment

java
int age = 30;
double height = 175.5;
boolean isStudent = true;
char grade = 'A';
String name = "Lim Dong-geun";   // String is a reference type, but frequently used

= means "assign", not "equal" — it places the right-hand value into the left-hand variable.

Output — println vs printf

java
System.out.println("Name: " + name);          // Includes newline

System.out.print("On one line "); // No newline

System.out.printf("Age: %d years old, Height: %.1fcm%n", age, height); // C-style formatting

``

%d = integer, %f = decimal, %s = string, %n = newline. The option %.1f` means 1 decimal place.

Type Casting — Converting Between int and double

Implicit Conversion (Automatic)

Small type → large type is converted automatically.

java
int a = 10;
double b = a;    // 10 → 10.0 automatically converted
System.out.println(b);  // 10.0

Explicit Conversion (Manual)

Large type → small type requires explicit casting. This is intentional — it signals potential data loss.

java
double pi = 3.14;
int x = (int) pi;     // 3 — decimal truncated (not rounded)
System.out.println(x);

Specify the target type in parentheses. It truncates, not rounds3.99 becomes 3.

Common Pitfall — Integer Division

java
int a = 5, b = 2;
System.out.println(a / b);          // 2  (integer division results in integer)
System.out.println((double) a / b); // 2.5 (if one side is double, result is double)

The most common bug. Dividing two integers drops the decimal portion.

if · switch · Loops — One-Page Reference

if / else

java
int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");   // Printed
} else {
    System.out.println("C");
}

The condition must be a boolean. You cannot use 0/1 like in C (e.g., if (x) is not valid).

switch — When Comparing Many Values

Java 14+ introduced arrow syntax, which is much cleaner.

java
String day = "MON";
String korDay = switch (day) {
    case "MON", "TUE", "WED" -> "Weekday";
    case "SAT", "SUN"        -> "Weekend";
    default                  -> "Unknown";
};

The old syntax (Java 13 and below) had a pitfall: forgetting break causes fall-through to the next case — use arrow syntax in new code.

for — When the Number of Iterations is Known

java
for (int i = 0; i < 5; i++) {
    System.out.println(i);    // 0, 1, 2, 3, 4
}

The order is init → condition check → body → increment → condition check .... This is called the lifecycle.

while / do-while — When You Only Have a Condition

java
int n = 0;
while (n < 3) {       // Check condition first
    System.out.println(n++);
}

do {                   // Execute once, then check condition
    System.out.println("Execute at least once");
} while (false);

do-while always executes once before checking the condition. Rarely used in practice.

Example — Sum of 1 to 100

java
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println(sum);   // 5050

Arrays — Grouping Multiple Values of the Same Type

Array Declaration and Initialization

java
int[] arr = new int[5];          // Length 5, all initialized to 0
int[] nums = {10, 20, 30, 40};   // Declared with values
String[] names = {"Kim", "Lee", "Park"};

int[] is the "int array" type. The C-style int arr[] also works but is not recommended.

Access — Indexes Start at 0

java
int[] nums = {10, 20, 30};
System.out.println(nums[0]);    // 10
System.out.println(nums[2]);    // 30
nums[1] = 999;                  // Modify
System.out.println(nums[1]);    // 999

Accessing out-of-bounds throws ArrayIndexOutOfBoundsException — the most common runtime error.

Length — .length

java
int[] nums = {10, 20, 30};
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

.length is a field (no parentheses) — it is not length(). Do not confuse it with String's length().

for-each — More Concise Iteration

java
int[] nums = {10, 20, 30};
for (int n : nums) {
    System.out.println(n);
}

When you don't need the index, this is far more readable. However, since the index is unavailable, use a regular for loop when you need to modify elements.

2D Arrays

java
int[][] grid = {
    {1, 2, 3},
    {4, 5, 6}
};
System.out.println(grid[1][2]);   // 6 — row 1, column 2

Commonly used for game boards and matrices. In production code ArrayList is used most of the time, but arrays are faster for algorithm problems.

What's Next

Variables, control flow, arrays — this is the fundamental building material of all Java code. In the next chapter on OOP, you will explore "why we need to group things into classes."

☕ Try It Live — Variables, Types, Operators & Control Flow

Run all 8 primitives and control flow at once. Modify values and observe the results.
☕ Java
✏️ 코드 편집기
📟 출력 결과
▶ Press the Run button
💡 코드를 직접 수정하고 실행해보세요. 변수값을 바꾸거나 println을 추가해 결과를 확인하세요!
☁️ Judge0 API로 서버에서 실행 — Java / Python / JS / C++ 지원

🤖 Try Prompting the AI Like This

Once you know the concepts in this lesson, you can give the AI specific instructions. Instead of vague requests like "fix this," you can make vocabulary-driven requests — that is where token savings begin.

  • "Correct the use of int vs. long and float vs. double in this Java code where appropriate."
  • "Convert this for loop into an enhanced for-each loop."
  • "Refactor this if-else chain into a switch expression (Java 14+)."

Why This Saves Tokens

Without the concepts, you have to ask "what does that mean?" after every AI response. Those follow-up questions burn tokens. Learn the concepts once and the conversation ends in one round.

Java Variables, Data Types & Control Flow — The Real Starting Point - Java