Java Variables and Types | Primitives, References, and Casting

Java Variables and Types | Primitives, References, and Casting

이 글의 핵심

Java primitive and reference types, casting, String pitfalls, and autoboxing—explained with examples.

Introduction

Java is a statically typed language: you must declare a type for every variable.


1. Primitive types

Integers

byte b = 127;

short s = 32767;

int i = 2147483647;

long l = 9223372036854775807L;  // L suffix required for long literals

int million = 1_000_000;
long billion = 1_000_000_000L;

Choosing integer types: For most business logic int is the default. Use long for large ranges (file sizes, timestamps). Use byte/short only when memory is extremely constrained. Omitting L makes the literal an int, which can overflow at compile time.

Floating-point types

float f = 3.14f;  // f suffix required

double d = 3.14159;
double scientific = 1.23e-4;

Floating-point caveat: float and double are binary floating-point, so expressions like 0.1 + 0.2 may surprise you. For exact decimal arithmetic, use BigDecimal.

Character type

char c = 'A';
char korean = '\uAC00';  // example Unicode code point
char unicode = '\u0041';  // 'A'

Boolean type

boolean flag = true;
boolean isActive = false;

boolean isAdult = age >= 18;

boolean vs null: Primitive boolean cannot be null. Wrapper Boolean can—watch for NullPointerException. If you need three states (true/false/unknown), consider Optional<Boolean> or an enum.


2. Reference types

String

String name1 = "Jane";
String name2 = "Jane";
System.out.println(name1 == name2);  // often true (interned literal)

String name3 = new String("Jane");
System.out.println(name1 == name3);  // false (different objects)
System.out.println(name1.equals(name3));  // true (value equality)

== vs equals: Literals may intern so == can appear to work, but always compare strings with equals for user input and data from external systems.

Arrays

int[] numbers = {1, 2, 3, 4, 5};
int[] arr = new int[5];

System.out.println(numbers[0]);
numbers[0] = 10;

System.out.println(numbers.length);

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};
System.out.println(matrix[0][1]);

Arrays in practice: Length is fixed; for dynamic growth prefer ArrayList. Multi-dimensional arrays are “arrays of arrays”—rows can differ in length.


3. Type casting

Widening (implicit)

byte b = 10;
int i = b;
long l = i;
float f = l;
double d = f;

Narrowing (explicit)

double d = 3.14;
int i = (int) d;

long l = 1000L;
int i2 = (int) l;

int big = 130;
byte small = (byte) big;  // overflow → -126

4. Wrapper classes

Primitive vs wrapper

PrimitiveWrapper
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Autoboxing and unboxing

Integer obj = 10;

int primitive = obj;

Integer a = 10;
Integer b = 20;
Integer sum = a + b;

List<Integer> numbers = new ArrayList<>();
numbers.add(10);
int first = numbers.get(0);

Integer nullValue = null;
// int x = nullValue;  // NullPointerException

Integer value = maybeNull();
int result = (value != null) ? value : 0;

Performance note:

Integer sum = 0;
for (int i = 0; i < 1000; i++) {
    sum += i;
}

int sum2 = 0;
for (int i = 0; i < 1000; i++) {
    sum2 += i;
}
Integer result = sum2;

Wrapper utilities

int num = Integer.parseInt("123");
double d = Double.parseDouble("3.14");

String str = Integer.toString(123);
String str2 = String.valueOf(123);

Integer a = 100;
Integer b = 100;
System.out.println(a.equals(b));

System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);

5. var (Java 10+)

var name = "Jane";
var age = 25;
var price = 19.99;
var list = new ArrayList<String>();

// var x;  // error: cannot infer type without initializer

6. Practical examples

Example 1: Parsing and conversion

public class TypeConversion {
    public static void main(String[] args) {
        String input = "123";
        int num = Integer.parseInt(input);
        
        try {
            int result = Integer.parseInt("abc");
        } catch (NumberFormatException e) {
            System.out.println("Parse failed");
        }
        
        int value = 123;
        String str = String.valueOf(value);
        String str2 = Integer.toString(value);
    }
}

Example 2: Arrays

public class ArrayExample {
    public static void main(String[] args) {
        int[] scores = {85, 92, 78, 95, 88};
        
        int sum = 0;
        for (int score : scores) {
            sum += score;
        }
        
        double average = (double) sum / scores.length;
        System.out.println("Average: " + average);
        
        int max = scores[0];
        for (int score : scores) {
            if (score > max) {
                max = score;
            }
        }
        System.out.println("Max: " + max);
    }
}

Summary

  1. Primitives: byte, short, int, long, float, double, char, boolean
  2. References: String, arrays, objects
  3. Casting: widening (implicit), narrowing (explicit)
  4. Wrappers: Integer, Double, …
  5. Autoboxing: automatic primitive ↔ wrapper conversion

Next steps

  • Classes and objects
  • Collections
  • Stream API

  • C++ variables and types
  • Kotlin variables
  • Swift variables
  • C++ numeric_limits
  • C++ templates