Back to blog
Backend Systemsbeginner

Java Basics: Types, Variables & Control Flow

Learn Java from scratch: primitive types, variables, operators, conditionals, loops, and methods. The foundation you need before everything else.

Asma HafeezApril 17, 20266 min read
javabasicstypescontrol-flow
Share:𝕏

Java Basics: Types, Variables & Control Flow

Java is statically typed — every variable has a declared type. This strictness catches bugs early and makes large codebases manageable.


Hello World

JAVA
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Every Java program starts in a main method inside a public class.


Primitive Types

JAVA
// Integer types
byte   b = 127;           // 8-bit,  -128 to 127
short  s = 32000;         // 16-bit
int    i = 2_000_000;     // 32-bit (most common)
long   l = 9_000_000_000L; // 64-bit, note the L suffix

// Floating-point
float  f = 3.14f;         // 32-bit, note the f suffix
double d = 3.14159265;    // 64-bit (most common)

// Other
boolean flag = true;
char    c    = 'A';       // single quotes, UTF-16 character

Overflow — watch out

JAVA
int max = Integer.MAX_VALUE;  // 2,147,483,647
int overflowed = max + 1;     // becomes -2,147,483,648 — no exception!

// Use long for large numbers
long safeMax = Long.MAX_VALUE; // 9,223,372,036,854,775,807

Strings

Strings in Java are objects, not primitives.

JAVA
String name = "Alice";
String greeting = "Hello, " + name;  // concatenation

// Useful methods
int len = name.length();             // 5
String upper = name.toUpperCase();   // "ALICE"
String lower = name.toLowerCase();   // "alice"
boolean starts = name.startsWith("Al"); // true
int idx = name.indexOf("l");         // 1
String sub = name.substring(1, 3);   // "li"
String trimmed = "  hello  ".strip(); // "hello"

// String comparison — ALWAYS use .equals(), never ==
String a = "hello";
String b = "hello";
System.out.println(a == b);       // might be true (JVM intern pool) but unreliable
System.out.println(a.equals(b));  // true — always use this

// String formatting
String msg = String.format("Name: %s, Age: %d", name, 30);
// or
String msg2 = "Name: %s, Age: %d".formatted(name, 30); // Java 15+

var — Local Type Inference (Java 10+)

JAVA
var count = 42;           // inferred as int
var name = "Alice";       // inferred as String
var list = new ArrayList<String>(); // inferred as ArrayList<String>

// var is only for local variables — not fields or parameters

Operators

JAVA
// Arithmetic
int sum  = 10 + 3;   // 13
int diff = 10 - 3;   // 7
int prod = 10 * 3;   // 30
int quot = 10 / 3;   // 3 (integer division)
int rem  = 10 % 3;   // 1 (modulo)
double div = 10.0 / 3; // 3.3333... (float division)

// Compound assignment
int x = 5;
x += 3;   // x = 8
x *= 2;   // x = 16
x /= 4;   // x = 4

// Increment / decrement
int a = 5;
a++;   // a = 6
a--;   // a = 5
int b = ++a;  // pre-increment: b = 6, a = 6
int c = a++;  // post-increment: c = 6, a = 7

// Comparison
boolean eq  = (5 == 5);  // true
boolean neq = (5 != 4);  // true
boolean gt  = (5 > 4);   // true
boolean gte = (5 >= 5);  // true

// Logical
boolean and = (true && false); // false
boolean or  = (true || false); // true
boolean not = !true;           // false

Conditionals

if / else if / else

JAVA
int score = 85;

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else if (score >= 70) {
    System.out.println("C");
} else {
    System.out.println("F");
}

Ternary operator

JAVA
int age = 20;
String status = (age >= 18) ? "adult" : "minor";

switch (classic)

JAVA
int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Other");
}

switch expression (Java 14+)

JAVA
String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Other";
};

Loops

for

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

// Count backwards
for (int i = 10; i > 0; i -= 2) {
    System.out.println(i);  // 10 8 6 4 2
}

while

JAVA
int count = 0;
while (count < 5) {
    System.out.println(count++);
}

do-while

JAVA
int n = 0;
do {
    System.out.println(n++);  // runs at least once
} while (n < 3);

Enhanced for (for-each)

JAVA
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

break and continue

JAVA
for (int i = 0; i < 10; i++) {
    if (i == 3) continue;  // skip 3
    if (i == 7) break;     // stop at 7
    System.out.println(i); // 0 1 2 4 5 6
}

Arrays

JAVA
// Declare and initialize
int[] nums = new int[5];          // [0, 0, 0, 0, 0]
int[] primes = {2, 3, 5, 7, 11}; // array literal

// Access and modify
primes[0] = 2;
int first = primes[0];  // 2

// Length
int len = primes.length;  // 5

// Iterate
for (int i = 0; i < primes.length; i++) {
    System.out.println(primes[i]);
}

// 2D array
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
System.out.println(matrix[1][2]);  // 6

Methods

JAVA
public class Calculator {

    // Static method — called on the class, not an instance
    public static int add(int a, int b) {
        return a + b;
    }

    // Returns nothing
    public static void printGreeting(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Multiple return points
    public static String classify(int n) {
        if (n > 0) return "positive";
        if (n < 0) return "negative";
        return "zero";
    }

    public static void main(String[] args) {
        int result = add(3, 4);         // 7
        printGreeting("Alice");          // Hello, Alice!
        System.out.println(classify(-5)); // negative
    }
}

Method overloading

JAVA
public static int multiply(int a, int b) {
    return a * b;
}

public static double multiply(double a, double b) {
    return a * b;
}

// Java picks the right one based on argument types
multiply(3, 4);       // calls int version → 12
multiply(2.5, 3.0);   // calls double version → 7.5

Type Casting

JAVA
// Widening (automatic) — no data loss
int i = 100;
long l = i;   // int → long, automatic
double d = i; // int → double, automatic

// Narrowing (explicit) — may lose data
double pi = 3.14159;
int truncated = (int) pi;  // 3 — fractional part lost

// Watch for overflow
long big = 1_000_000_000_000L;
int small = (int) big;  // wrong result — data lost

Key Takeaways

  1. Java is statically typed — declare types explicitly (or use var for local variables)
  2. Use long for integers larger than ~2 billion; use double for decimals
  3. Always use .equals() to compare Strings — == compares references, not values
  4. Integer division truncates — use 10.0 / 3 for float division
  5. switch expressions (Java 14+) with -> are cleaner than the classic switch with break

Enjoyed this article?

Explore the Backend Systems learning path for more.

Found this helpful?

Share:𝕏

Leave a comment

Have a question, correction, or just found this helpful? Leave a note below.