← Back to Java series
β˜•
Basics
Basics Β· Prerequisite: previous lecture

02. Variables and Types

A variable is a "labeled box" that holds data. Java is a **statically-typed** language, so the type of each variable must be declared up front. This lecture covers the 8 primitive types, type conversion, and the `var` keyword (JDK 10+).

JavaJDKbasicsvariables and types
Duration
⏱ ~1-1.5 hours
Level
πŸ“Š Beginner
Prerequisite
🎯 Previous lecture or equivalent knowledge
OUTCOME
A variable is a "labeled box" that holds data. Java is a **statically-typed** language, so the type of each variable must be declared up front. This lecture covers the 8 primitive types, type conversion, and the `var` keyword (JDK 10+).

What you'll learn

  • 1Know the size and default value of each of the 8 primitive types
  • 2Understand when implicit / explicit type conversion happens
  • 3Distinguish where `var` can and cannot be used
  • 4Understand the difference between a `String` literal and `new String()`

Overview

A variable is a "labeled box" that holds data. Java is a **statically-typed** language, so the type of each variable must be declared up front. This lecture covers the 8 primitive types, type conversion, and the `var` keyword (JDK 10+).

Core Concepts

1) The 8 primitives

TypeSizeDefaultRange
`byte`1 byte0-128 ~ 127
`short`2 bytes0-32,768 ~ 32,767
`int`4 bytes0~Β±2.1 billion
`long`8 bytes0L~Β±9 Γ— 10^18
`float`4 bytes0.0fIEEE 754 single-precision
`double`8 bytes0.0dIEEE 754 double-precision
`boolean`JVM-dependent`false``true` / `false`
`char`2 bytes' 'UTF-16 code unit
java
int age = 21;
long population = 50_000_000L;   // long literal ends in L
double pi = 3.14159;
boolean done = false;
char grade = 'A';

2) Type conversion

java
int i = 100;
double d = i;          // int -> double : implicit (value-preserving)
int back = (int) d;    // double -> int : explicit (truncates)

Small β†’ large is automatic, but large β†’ small requires an **explicit cast** because data can be lost.

3) The `var` keyword (JDK 10+)

java
var name = "Jisoo";    // inferred as String
var nums = new int[]{1, 2, 3};
  • **Local variables only** β€” not fields or method signatures
  • Must be initialized at declaration, so the type can be inferred
  • Use it only when it improves readability

4) `String` literal vs `new String()`

java
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b);          // true  (shared string pool)
System.out.println(a == c);          // false (different object)
System.out.println(a.equals(c));     // true  (content comparison)

Examples

Example 1 β€” `Primitives.java`: print all 8 primitives

java
public class Primitives {
    public static void main(String[] args) {
        byte b = 10;
        short s = 200;
        int i = 100_000;
        long l = 9_999_999_999L;
        float f = 3.14f;
        double d = 3.141592653589793;
        boolean t = true;
        char c = 'A';
        System.out.printf("byte=%d, short=%d, int=%d, long=%d%n", b, s, i, l);
        System.out.printf("float=%.2f, double=%.6f%n", f, d);
        System.out.printf("boolean=%b, char=%c(%d)%n", t, c, (int) c);
    }
}

**Output**

text
byte=10, short=200, int=100000, long=9999999999
float=3.14, double=3.141593
boolean=true, char=A(65)

**Note:** large numbers can be split with `_` for readability (`100_000`).

Example 2 β€” `Conversion.java`: type conversion pitfalls

java
public class Conversion {
    public static void main(String[] args) {
        int i = 100;
        double d = i;
        System.out.println("int -> double: " + d);

        double pi = 3.99;
        int truncated = (int) pi;
        System.out.println("double -> int (truncated): " + truncated);

        int big = 1_000;
        byte overflow = (byte) big;
        System.out.println("byte overflow: " + overflow);
    }
}

**Output**

text
int -> double: 100.0
double -> int (truncated): 3
byte overflow: -24

**Note:** outside `byte`'s range (-128~127), bits are dropped and the value becomes unpredictable.

Example 3 β€” `VarKeyword.java`: where `var` can and cannot be used

java
import java.util.ArrayList;
import java.util.List;

public class VarKeyword {
    public static void main(String[] args) {
        var name = "Jisoo";
        var list = new ArrayList<String>();
        list.add("Java");
        list.add("Spring");

        for (var s : list) {
            System.out.println(s);
        }

        // var x;          // compile error: needs initializer
        // var n = null;   // compile error: cannot infer type
        List<Integer> nums = List.of(1, 2, 3);
        System.out.println("name: " + name);
        System.out.println("type: " + nums.getClass().getSimpleName());
    }
}

**Output**

text
Java
Spring
name: Jisoo
type: ListN

**Note:** `var` does **not** work on fields, parameters, or return types β€” local variables only.

Example 4 β€” `StringBasics.java`: literal vs `new String()`

java
public class StringBasics {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = new String("hello");
        System.out.println("a == b : " + (a == b));
        System.out.println("a == c : " + (a == c));
        System.out.println("a.equals(c) : " + a.equals(c));
        System.out.println("length : " + a.length());
        System.out.println("upper  : " + a.toUpperCase());
    }
}

**Output**

text
a == b : true
a == c : false
a.equals(c) : true
length : 5
upper  : HELLO

**Note:** in Java, **string content is compared with `.equals()`** β€” `==` compares references (addresses).

Full example code (src/)

src/Conversion.java

java
public class Conversion {
    public static void main(String[] args) {
        int i = 100;
        double d = i;
        System.out.println("int -> double: " + d);

        double pi = 3.99;
        int truncated = (int) pi;
        System.out.println("double -> int (truncated): " + truncated);

        int big = 1_000;
        byte overflow = (byte) big;
        System.out.println("byte overflow: " + overflow);
    }
}

src/Primitives.java

java
public class Primitives {
    public static void main(String[] args) {
        byte b = 10;
        short s = 200;
        int i = 100_000;
        long l = 9_999_999_999L;
        float f = 3.14f;
        double d = 3.141592653589793;
        boolean t = true;
        char c = 'A';
        System.out.printf("byte=%d, short=%d, int=%d, long=%d%n", b, s, i, l);
        System.out.printf("float=%.2f, double=%.6f%n", f, d);
        System.out.printf("boolean=%b, char=%c(%d)%n", t, c, (int) c);
    }
}

src/StringBasics.java

java
public class StringBasics {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = new String("hello");
        System.out.println("a == b : " + (a == b));
        System.out.println("a == c : " + (a == c));
        System.out.println("a.equals(c) : " + a.equals(c));
        System.out.println("length : " + a.length());
        System.out.println("upper  : " + a.toUpperCase());
    }
}

src/VarKeyword.java

java
import java.util.ArrayList;
import java.util.List;

public class VarKeyword {
    public static void main(String[] args) {
        var name = "Jisoo";
        var list = new ArrayList<String>();
        list.add("Java");
        list.add("Spring");

        for (var s : list) {
            System.out.println(s);
        }

        List<Integer> nums = List.of(1, 2, 3);
        System.out.println("name: " + name);
        System.out.println("type: " + nums.getClass().getSimpleName());
    }
}

Common Mistakes

  1. Omitting `L` on a `long` literal β†’ it's parsed as `int` and overflows
  2. Omitting `f` on a `float` literal β†’ defaults to `double`, requires a cast
  3. Forgetting that `int / int` is integer division (`1 / 2 == 0`)
  4. Not realizing that `char` is interchangeable with a small integer (0~65535)
  5. Comparing strings with `==`

Summary

  • Memorize Java's 8 primitives and their defaults β€” it pays off when debugging
  • Type conversion: small β†’ large is automatic, large β†’ small needs an explicit cast
  • `var` is a readability tool, not a magic keyword
  • String content uses `.equals()`; `==` compares references

Practice

# Practice - 02. Variables and Types

## Exercise 1 β€” Profile variables

  • File: `Homework01.java`
  • Key concepts: primitive declarations, `printf`

Requirements

  • Declare variables for name (String), age (int), height (double), is-student (boolean), grade (char).
  • Print all five on one line with `printf`.

Expected output

text
name=John Doe, age=21, height=175.30, student=true, grade=A

Hint

  • Format string: `%s %d %.2f %b %c`

## Exercise 2 β€” Arithmetic

  • File: `Homework02.java`
  • Key concepts: variables, integer / floating-point math, explicit casting

Requirements

  • Declare two integers `a = 17`, `b = 5`.
  • Print sum, difference, product, integer quotient, remainder, and floating-point quotient.

Expected output

text
17 + 5 = 22
17 - 5 = 12
17 * 5 = 85
17 / 5 = 3
17 % 5 = 2
17 / 5 (float) = 3.40

Hint

  • Cast one operand: `(double) a / b`.

## Solutions After trying it yourself, compare with [`answer/`](./answer/).

Solution code (homework/answer/)

answer/Homework01.java

java
/** Print profile variables. */
public class Homework01 {
    public static void main(String[] args) {
        String name = "John Doe";
        int age = 21;
        double height = 175.30;
        boolean student = true;
        char grade = 'A';
        System.out.printf("name=%s, age=%d, height=%.2f, student=%b, grade=%c%n",
                name, age, height, student, grade);
    }
}

answer/Homework02.java

java
/** Arithmetic on two integers. */
public class Homework02 {
    public static void main(String[] args) {
        int a = 17;
        int b = 5;
        System.out.printf("%d + %d = %d%n", a, b, a + b);
        System.out.printf("%d - %d = %d%n", a, b, a - b);
        System.out.printf("%d * %d = %d%n", a, b, a * b);
        System.out.printf("%d / %d = %d%n", a, b, a / b);
        System.out.printf("%d %% %d = %d%n", a, b, a % b);
        System.out.printf("%d / %d (float) = %.2f%n", a, b, (double) a / b);
    }
}

Try It Yourself

bash
cd 01_basics/02_variables_and_types/src
javac Primitives.java
java Primitives

Next Lecture

[03_Operators_and_Expressions](../03_μ—°μ‚°μžμ™€_ν‘œν˜„μ‹/) β€” arithmetic, comparison, logical, bitwise operators, and `==` vs `.equals()`.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—