[2026] Java Variables and Types | Primitives, References, and Casting

[2026] Java Variables and Types | Primitives, References, and Casting

이 글의 핵심

Java primitives and references in one place: sizes, literal rules (L and f suffixes), String pool and equals, arrays, casting, autoboxing pitfalls, and var—beginner-friendly with practical notes.

Introduction

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

1. Primitive types

Integers

아래 코드는 java를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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

아래 코드는 java를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

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

아래 코드는 java를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

// 실행 예제
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)

아래 코드는 java를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

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

Narrowing (explicit)

아래 코드는 java를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

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

다음은 java를 활용한 상세한 구현 코드입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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: 아래 코드는 java를 사용한 구현 예제입니다. 반복문으로 데이터를 처리합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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

아래 코드는 java를 사용한 구현 예제입니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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+)

아래 코드는 java를 사용한 구현 예제입니다. 에러 처리를 통해 안정성을 확보합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.

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

다음은 java를 활용한 상세한 구현 코드입니다. 함수를 통해 로직을 구현합니다, 비동기 처리를 통해 효율적으로 작업을 수행합니다, 에러 처리를 통해 안정성을 확보합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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

다음은 java를 활용한 상세한 구현 코드입니다. 함수를 통해 로직을 구현합니다, 반복문으로 데이터를 처리합니다, 조건문으로 분기 처리를 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.

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


... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3