Skip to content
notes.vinhnq.com

Search

Java CoreJunior23 min read

Java basics: variables, data types and casting

Review 17 cards
On this page

Java basics series: 1. JVM and JDK · 2. Hello World and the three kinds of errors · 3. Variables and types · 4. Operators and branching · 5. Loops and methods · 6. Arrays and strings · 7. Console and text files · 8. Byte streams and serialization

Picking the wrong data type causes some of the hardest bugs to spot: overflow that raises no error, money in double that drifts by a cent, casts that silently drop data. After this post you can pick the right type, say where primitives and references live in memory, and cast without losing data. Read the JVM post and Hello World first; binary and two’s complement come next, in operators and branching, alongside the bitwise operators.

1. Variables and data types

Key idea: a variable is a name bound to a piece of memory whose value can change while the program runs. A data type decides how big that memory is and which operations are allowed on it.

Think of sorting containers: the box for whole numbers is not the box for text.

The 8 primitive types

Key idea: six numeric types (four integer, two floating-point), plus char and boolean. Knowing the range of int (±2.1 billion) and the precision of float/double covers most decisions.

Type Size Range / precision Default (as a field)
byte 8 bits -128 … 127 0
short 16 bits -32,768 … 32,767 0
int 32 bits about ±2.1 billion (-2³¹ … 2³¹-1) 0
long 64 bits about ±9.2 × 10¹⁸ 0L
float 32 bits about 6–7 significant digits 0.0f
double 64 bits about 15–16 significant digits 0.0
char 16 bits one UTF-16 code unit, '\u0000' to '\uFFFF' '\u0000'
boolean not specified true / false false

String is not a primitive. It is an immutable class (it can’t be changed once created); more in wrapper classes, BigDecimal and String.

Where primitives and references live

Key idea: a local primitive variable holds the value itself on the stack; a reference variable only holds the address of an object on the heap.

The stack is per-method-call memory, cleaned up when the method returns. The heap is shared memory for objects, cleaned up by the GC.

flowchart LR
  subgraph Stack["Stack (main's frame)"]
    a["int age = 30"]
    s["String name = ref"]
  end
  subgraph Heap
    o["String object 'Vinh'"]
  end
  s --> o

With this picture in mind it’s obvious why passing an array to a method lets the method change it while passing an int doesn’t (see the loops and methods post).

Why Java separates primitives from references

Key idea: performance. An int is 4 bytes stored right in the variable, while an object needs a header, a reference and an extra memory load.

  • Reference types include String, Object, arrays (int[] is an object too), collections (List, Map, Set) and every class you write.
  • The cost of an object: a header of roughly 12–16 bytes (metadata the JVM attaches to every object), plus a reference pointing to it.
  • The cost of a primitive: no methods, no null, and no direct use with generics.

Wrapper classes, boxing and unboxing

Key idea: every primitive has a “wrapper” class for places that only accept objects. The compiler converts back and forth for you (autoboxing / unboxing).

The pairs: byte → Byte, short → Short, int → Integer, long → Long, float → Float, double → Double, char → Character, boolean → Boolean. You need wrappers because:

  • collections only hold objects (List<Integer>, there is no List<int>);
  • you sometimes need null to mean “no value” (a nullable database column);
  • wrappers carry handy utility methods.
Integer boxed = 42;                    // autoboxing: the compiler writes Integer.valueOf(42)
int unboxed = boxed;                   // unboxing: the compiler writes boxed.intValue()
int parsed = Integer.parseInt("123");  // String -> int; a malformed string throws NumberFormatException
Integer.MAX_VALUE;                     // 2147483647
Character.isDigit('7');                // true
Boolean.parseBoolean("yes");           // false: only "true" (case-insensitive) is true

Declaration, initialization, var, final

Key idea: declaring reserves memory, initializing puts a value in it. var lets the compiler infer the type, final allows only one assignment.

int quantity;            // declaration: reserve memory for an int
quantity = 3;            // initialization/assignment: put a value into it
double price = 19.99;    // both at once

var total = price * quantity;   // Java 10+: the compiler infers double
final int MAX_ITEMS = 100;      // can be assigned exactly once

long population = 8_100_000_000L;  // needs the L suffix, otherwise it is an int literal and too big
float ratio = 0.75f;               // 0.75 is a double literal by default; f makes it a float

Think of a cup: declaring is grabbing an empty cup of the right kind, initializing is pouring the drink in. Pour something that doesn’t fit (assign "abc" to an int) and the compiler stops you right away.

Naming

Key idea: there are two layers. Hard rules (break them and it won’t compile) and conventions (break them and it still runs, but Checkstyle or Sonar will flag it).

Java conventions:

Kind Convention Example
Variables, methods camelCase orderTotal, findById()
Classes, interfaces, records, enums PascalCase OrderService
Constants (static final) UPPER_SNAKE_CASE MAX_RETRY
Packages lowercase, reversed domain com.vinhnq.billing

The slides list snake_case as an option for variable names. It is legal syntax but not Java convention. When you see snake_case in Java code, it usually mirrors a database column or a JSON field.

Hard rules:

  • Only letters, digits, _ and $. điểm is legal too (Unicode letters), but don’t use it.
  • Must not start with a digit.
  • Must not be a keyword (if, class, new, int…) or the literals true, false, null. Since Java 9, _ on its own is a keyword too.
  • Case-sensitive: total and Total are different variables.

Guess first: abc, 1abc, ab_c, _abc, $abc, ab-c, _123, $123, if, $if. Only 1abc (starts with a digit), ab-c (- is the minus operator) and if (a keyword) are invalid; $if is fine because it’s no longer a keyword. Legal doesn’t mean advisable: $ is meant for generated code, and _123 tells the reader nothing.

Casting

Key idea: narrow to wide happens automatically (widening); wide to narrow needs (type) (narrowing) and can lose data without warning.

flowchart LR
  byte --> short --> int --> long --> float --> double
  char --> int
  • Implicit (widening): follows the arrows, done by the compiler. But int → float and long → float, although automatic, can lose precision, because a float only has about 24 bits of mantissa.
  • Explicit (narrowing): goes against the arrows and requires (type). It loses data without any warning.
long big = 123_456_789_123L;
float f = big;                 // automatic, but now 1.23456790528E11 (already off)

double d = 3.99;
int truncated = (int) d;       // 3: the fraction is cut off, not rounded
int negative = (int) -3.99;    // -3: truncation goes toward zero
long rounded = Math.round(d);  // 4

int tooBig = 200;
byte b = (byte) tooBig;        // -56: only the low 8 bits survive, so the value wraps around

char letter = 'A';
int code = letter;             // 65: char widens to int automatically
char next = (char) (code + 1); // 'B'

int safe = Math.toIntExact(5_000_000_000L); // throws ArithmeticException instead of silently truncating

Characters are numbers: ASCII, Unicode and number bases

Key idea: computers only store numbers, so every character has a numeric code. In Java a char is an unsigned 16-bit integer, so you can do arithmetic with it.

ASCII is a 7-bit code (values 0–127) from the 1960s: English letters, digits, punctuation, control characters. A few landmarks worth memorizing:

Character Decimal Hex Note
'\n' 10 0x0A line feed (LF)
' ' 32 0x20 space
'0' … '9' 48 … 57 0x30 … 0x39 the character '0' is not the number 0
'A' … 'Z' 65 … 90 0x41 … 0x5A
'a' … 'z' 97 … 122 0x61 … 0x7A lowercase = uppercase + 32
int code = 'e';                    // 101
char letter = (char) 65;           // 'A'
int digit = '7' - '0';             // 7: turns a digit character into its value
int gap = 'a' - 'A';               // 32
char upper = (char) ('g' - 32);    // 'G' (real code should use Character.toUpperCase)

char c = 'A';
c += 1;                            // 'B': compound assignment casts back to char
// c = c + 1;                      // compile error: c + 1 is an int

System.out.println('A' + 'B');      // 131: adding two chars gives an int
System.out.println("" + 'A' + 'B'); // AB

The slides say “cast a char to int to get its ASCII code”. That only holds for the first 128 characters: (int) 'Đ' is 272, which isn’t in any ASCII table.

Unicode, UTF-16, UTF-8 and literals in four bases

ASCII is just the first 128 codes of Unicode. Unicode assigns a number (a code point, written like U+0110 for Đ) to more than 150,000 characters across every writing system.

  • Java stores strings as UTF-16: a char is one UTF-16 code unit, enough for characters from U+0000 to U+FFFF. Anything beyond that, such as an emoji, takes two chars.
  • When a string is written to a file or sent over the network it is encoded into bytes, usually UTF-8. In UTF-8 an ASCII character still takes exactly one byte, which is a big part of why UTF-8 became the universal default.

ASCII charts usually include octal (base 8) and hex (base 16) columns. Java can write integer literals in all four bases:

int dec = 65;
int hex = 0x41;        // 0x prefix: base 16
int oct = 0101;        // leading zero: base 8
int bin = 0b1000001;   // 0b prefix: base 2 (Java 7+)
// all four equal 65, which is also 'A'

Integer.toHexString(65);    // "41"
Integer.toOctalString(65);  // "101"
Integer.toBinaryString(65); // "1000001"

Hex is the one you’ll meet most at work, because each hex digit maps to exactly 4 bits: colours like 0xFF8800, error codes, memory addresses in logs, hash values, and \u0041 escapes in strings.

Exercises

Each prompt is a short paraphrase. All solutions were run on JDK 21.

Group 2: variables and data types

  • 2.1. Solve the linear equation ax + b = 0. Don’t forget a = 0, the case people miss.
  • 2.2. Convert inches to centimeters (1 inch = 2.54 cm).
  • 2.3. Convert Celsius ↔ Fahrenheit. The input is the current unit plus a value: C 40 gives 104, F 10 gives -12.2.
  • 2.4. Convert minutes into years, days, hours and minutes (a year is 365 days). 71 minutes is 0 years, 0 days, 1 hours, 11 minutes.
  • 2.5. Compute the factorial n!.
Solutions 2.1–2.5

2.1.

static String solveLinear(double a, double b) {
    if (a == 0) return b == 0 ? "Infinitely many solutions" : "No solution";
    return "x = " + (-b / a);
}

2.2. return inch * 2.54;.

2.3.

static double convertTemperature(char unit, double value) {
    return switch (Character.toUpperCase(unit)) {
        case 'C' -> value * 9 / 5 + 32;
        case 'F' -> (value - 32) * 5 / 9;
        default -> throw new IllegalArgumentException("Unit must be C or F: " + unit);
    };
}

2.4.

static String formatMinutes(long totalMinutes) {
    long perDay = 24 * 60, perYear = 365 * perDay;
    long years = totalMinutes / perYear;
    long days = totalMinutes % perYear / perDay;
    long hours = totalMinutes % perDay / 60;
    long minutes = totalMinutes % 60;
    return "%d years, %d days, %d hours, %d minutes".formatted(years, days, hours, minutes);
}

The general pattern: / gives the whole number of the bigger unit, % gives what’s left over. In real code, use java.time.Duration.ofMinutes(n), which already has toDaysPart() and toHoursPart().

2.5.

static long factorial(int n) {
    if (n < 0 || n > 20) throw new IllegalArgumentException("n must be in [0, 20]");
    long result = 1;
    for (int i = 2; i <= n; i++) result *= i;
    return result;
}

21! no longer fits in a long. Beyond that, use BigInteger.

  • 2.7. Convert a positive integer below 1000 to Roman numerals.
  • 2.8. Check whether three numbers can be the sides of a triangle; if so, classify it and compute its perimeter and area.
  • 2.9. Check for a perfect number: one that equals the sum of its proper divisors, e.g. 6 = 1 + 2 + 3.
  • 2.10. Solve the quadratic ax² + bx + c = 0.
  • 2.11. Withdraw an amount using as few banknotes as possible, with denominations 500, 200, 100, 20, 10, 5, 2 and 1.
Solutions 2.7–2.11

2.7. A greedy walk over a value table that already contains the subtractive pairs such as 900 (CM) and 4 (IV):

static String toRoman(int n) {
    if (n <= 0 || n >= 1000) throw new IllegalArgumentException("n must be in [1, 999]");
    int[] values = {900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    String[] symbols = {"CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < values.length; i++) {
        while (n >= values[i]) { sb.append(symbols[i]); n -= values[i]; }
    }
    return sb.toString();   // 944 -> CMXLIV
}

2.8. Area comes from Heron’s formula. Compare doubles with a tolerance eps, never with ==.

static String describeTriangle(double a, double b, double c) {
    if (a <= 0 || b <= 0 || c <= 0 || a + b <= c || a + c <= b || b + c <= a) return "Not a triangle";
    final double eps = 1e-9;
    double[] s = {a, b, c};
    java.util.Arrays.sort(s);
    boolean right = Math.abs(s[0] * s[0] + s[1] * s[1] - s[2] * s[2]) < eps;
    boolean equilateral = Math.abs(a - b) < eps && Math.abs(b - c) < eps;
    boolean isosceles = Math.abs(a - b) < eps || Math.abs(b - c) < eps || Math.abs(a - c) < eps;
    String kind = equilateral ? "equilateral" : isosceles ? (right ? "right isosceles" : "isosceles") : (right ? "right" : "scalene");
    double p = (a + b + c) / 2;
    double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
    return "%s, perimeter=%.2f, area=%.2f".formatted(kind, a + b + c, area);
}

2.9. Only go up to √n, adding both d and n/d each time you find a divisor:

static boolean isPerfect(long n) {
    if (n < 2) return false;
    long sum = 1;
    for (long d = 2; d * d <= n; d++) {
        if (n % d == 0) {
            sum += d;
            if (d != n / d) sum += n / d;
        }
    }
    return sum == n;   // 6, 28, 496, 8128
}

O(√n) instead of O(n). For n around 10¹², that’s 10⁶ versus 10¹² operations.

2.10.

static String solveQuadratic(double a, double b, double c) {
    if (a == 0) return solveLinear(b, c);            // degenerates into a linear equation
    double delta = b * b - 4 * a * c;
    if (delta < 0) return "No real roots";
    if (delta == 0) return "Double root x = " + (-b / (2 * a));
    double sqrt = Math.sqrt(delta);
    return "x1 = " + (-b + sqrt) / (2 * a) + ", x2 = " + (-b - sqrt) / (2 * a);
}

2.11.

static java.util.Map<Integer, Integer> withdraw(int amount) {
    int[] notes = {500, 200, 100, 20, 10, 5, 2, 1};
    var result = new java.util.LinkedHashMap<Integer, Integer>();
    for (int note : notes) {
        if (amount >= note) { result.put(note, amount / note); amount %= note; }
    }
    return result;   // 1288 -> {500=2, 200=1, 20=4, 5=1, 2=1, 1=1}, 10 notes in total
}
  • 2.12. Build an order (only in the second copy of the slides): read the name, price and quantity of 3 products, then print the average price and the order total. The key points: money uses BigDecimal, and every value is read with nextLine() and parsed by hand, which sidesteps the nextInt/nextLine trap explained in the console and file I/O post.
Solution 2.12
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;

public class OrderDemo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        BigDecimal sumPrice = BigDecimal.ZERO, total = BigDecimal.ZERO;
        for (int i = 1; i <= 3; i++) {
            System.out.print("Product " + i + " name: ");
            String name = in.nextLine();
            System.out.print("Price: ");
            BigDecimal price = new BigDecimal(in.nextLine().trim());
            System.out.print("Quantity: ");
            int qty = Integer.parseInt(in.nextLine().trim());
            sumPrice = sumPrice.add(price);
            total = total.add(price.multiply(BigDecimal.valueOf(qty)));
            System.out.println("Added " + name);
        }
        System.out.println("Average price: " + sumPrice.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP));
        System.out.println("Order total: " + total);
    }
}

Lab 01: reading from the keyboard and printing results

The task, paraphrased: (1) read a student’s name and average score and print it as "Eric" scored 9.6; (2) read the two sides of a rectangle and print its perimeter, area and shorter side; (3) read the edge of a cube and print its volume.

Solution to Lab 01 and notes
import java.util.Locale;
import java.util.Scanner;

public class Lab01 {
    // Read the whole line and parse it: avoids the nextDouble() + nextLine() trap, accepts "9,6" and "9.6"
    static double readNumber(Scanner in, String prompt, double min, double max) {
        while (true) {
            System.out.print(prompt);
            String raw = in.nextLine().trim().replace(',', '.');
            try {
                double value = Double.parseDouble(raw);
                if (value >= min && value <= max) return value;
            } catch (NumberFormatException ignored) {
                // fall through to the error message below
            }
            System.out.printf("Expected a number in [%s, %s], got \"%s\"%n", min, max, raw);
        }
    }

    static double perimeter(double length, double width) { return 2 * (length + width); }
    static double area(double length, double width)      { return length * width; }
    static double cubeVolume(double edge)                 { return edge * edge * edge; }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double minSide = 0.001, maxSide = 1_000_000;   // sides must be positive; the cap rejects absurd input

        // Task 1: name and average score
        System.out.print("Student name: ");
        String name = in.nextLine().strip();
        double score = readNumber(in, "Average score: ", 0, 10);
        System.out.printf(Locale.ROOT, "\"%s\" scored %.1f%n", name, score);

        // Task 2: rectangle
        double length = readNumber(in, "First side: ", minSide, maxSide);
        double width = readNumber(in, "Second side: ", minSide, maxSide);
        System.out.printf(Locale.ROOT, "Perimeter: %.2f%nArea: %.2f%nShorter side: %.2f%n",
                perimeter(length, width), area(length, width), Math.min(length, width));

        // Task 3: cube
        double edge = readNumber(in, "Cube edge: ", minSide, maxSide);
        System.out.printf(Locale.ROOT, "Volume: %.2f%n", cubeVolume(edge));
    }
}

The input Eric, 9,6, abc, 4, -2, 2.5, 3 gives "Eric" scored 9.6, re-prompts on abc and -2, then prints 13.00, 10.00, 2.50 and 27.00.

  • The task hints at Math.pow(edge, 3). That works, but pow is a general function for real exponents: slower, and it always returns a double. For a small integer exponent, edge * edge * edge is clearer and exact.
  • Locale.ROOT keeps the decimal point. Without it, a machine with a Vietnamese locale prints 9,6.
  • What a senior would add: keep the calculations pure (no I/O) so they can be unit-tested; use BigDecimal if scores must be rounded by a formal rule; always range-check user input rather than trusting it.

Remember

  • Name the 8 primitive types and explain why String isn’t one of them.
  • Draw the stack and heap for an int variable and a String variable.
  • Explain why int q = map.get("x") can throw NullPointerException.
  • Know when a cast loses data ((byte) 200, (int) 3.99, long → float) and how Math.toIntExact guards it.
  • Know why money never goes in a double, and what to use instead.

Interview questions

Junior

What are Java’s 8 primitive types? Is String one of them?

byte, short, int, long, float, double, char, boolean. String is not: it is an immutable class (a reference type).

The compiler just gives String special support for "..." literals and the + operator.

Which of these are valid identifiers: 1abc, _123, $if, ab-c, if?

Valid: _123 and $if. Invalid: 1abc (starts with a digit), ab-c (- is an operator), if (a keyword).

The rules: only letters, digits, _ and $; no leading digit; not a keyword or true/false/null; a lone _ has been a keyword since Java 9. Legal isn’t the same as conventional: variables use camelCase, constants UPPER_SNAKE_CASE.

What are wrapper classes for? What is autoboxing?

Wrappers turn a primitive into an object so it works with collections and generics, can be null, and has utility methods. Autoboxing is the compiler converting int to Integer for you.

Autoboxing calls Integer.valueOf; unboxing is the reverse, via intValue(). The traps: unboxing null throws NullPointerException, and comparing two wrappers with == compares references.

Do local variables have default values?

No. Only object fields and array elements get defaults (0, false, null…).

Reading a local variable before assigning it is a compile error (“variable might not have been initialized”). That’s how the compiler prevents C-style use of garbage values.

What is the type of 'a' + 1? Why does c = c + 1 fail for a char c while c += 1 compiles?

'a' + 1 is an int (98), because a char is promoted to int before arithmetic. c += 1 includes an implicit cast back to char; c = c + 1 doesn’t.

byte and short are promoted the same way. Assigning an int to a char is a narrowing conversion that needs c = (char) (c + 1). For the same reason, 'A' + 'B' prints 131 rather than AB.

Mid

What is the difference between implicit and explicit casting? Give an example of data loss.

Implicit (widening) casts go from a narrower to a wider type automatically. Explicit (narrowing) casts go the other way, need (type), and can lose data.

Examples: (byte) 200 == -56 (only the low 8 bits survive) and (int) 3.99 == 3 (truncation). Even the implicit long → float conversion can lose precision.

Why is 0.1 + 0.2 != 0.3? How do you handle money?

Because double is IEEE 754 binary floating point, and 0.1 has no exact binary representation. For money, use BigDecimal or a long in the smallest unit.

Create BigDecimal from a String with an explicit RoundingMode. With a long, store cents or đồng.

Does var make Java dynamically typed?

No. var is compile-time type inference for local variables; the type is still fixed.

var list = new ArrayList<String>() has the type ArrayList<String>, and assigning list = 5 later is a compile error. var can’t be used for fields, method parameters or return types, and it needs an initializer (no var x; or var x = null;).

Where do primitive variables and objects live in memory?

Local variables, primitive or reference, live in the running method’s stack frame. Objects, arrays included, live on the heap.

A reference variable only holds the object’s address. A primitive that is a field of an object lives inside that object, so on the heap. One nuance: the JIT performs escape analysis (checking whether an object “escapes” the method), so an object that never escapes can be broken into scalar values and never allocated on the heap.

Senior

Does integer overflow throw an exception? How do you guard against it in production code?

No. Integers are stored in two’s complement, so overflow silently wraps: Integer.MAX_VALUE + 1 == Integer.MIN_VALUE.

Guards:

  • Math.addExact, multiplyExact and toIntExact throw ArithmeticException on overflow.
  • Use long for money, counters and timestamps; BigInteger when there’s no known bound.
  • Classic bug: the binary-search midpoint (lo + hi) / 2 overflows. Write lo + (hi - lo) / 2 or (lo + hi) >>> 1.
Why is there no List<int>, and how expensive is boxing with large data?

Generics are erased to Object (type erasure), and primitives aren’t objects. With large data, boxing costs 4–5 times the memory of a primitive array.

A List<Integer> with a million elements is an array of references (4–8 bytes each) plus a million Integer objects (around 16 bytes each) scattered across the heap. An int[] is just 4 contiguous MB. The result: more memory, many more cache misses, extra GC pressure.

For large numeric data, use primitive arrays, IntStream, or primitive-specialised collection libraries (fastutil, Eclipse Collections). Project Valhalla aims to allow generics over value types.

Useful phrases for interviews

  • “I never use double for money; I use BigDecimal with an explicit rounding mode, or store minor units as a long.”
  • “Narrowing casts can silently lose data, so where it matters I use Math.toIntExact and let it fail fast.”
  • “Overflow wraps around silently in Java, so for anything that can grow, such as counters or totals, I pick long or the *Exact methods.”
  • “Unboxing a null Integer throws a NullPointerException, so I use getOrDefault on maps of counters.”
  • “Collections only hold objects, so every int gets boxed into an Integer, which costs memory and cache locality.”
  • “var is still statically typed; it just lets the compiler infer the type from the initializer.”
  • “A local variable has no default value; the compiler rejects reading it before it’s assigned.”
  • “For large numeric data I’d use a primitive array rather than a list of wrappers.”
  • “A Java char is a UTF-16 code unit, so it only matches ASCII for the first 128 characters.”
  • “I always pass the character encoding explicitly, usually UTF-8, instead of relying on the platform default.”
  • “A float keeps about seven significant digits, not seven decimal places.”

Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.