본문으로 건너뛰기
Previous
Next
Java Variables and Types | Primitives· References

Java Variables and Types | Primitives· References

Java Variables and Types | Primitives· References

이 글의 핵심

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

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



자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. Java primitives and references in one place: sizes, literal rules (L and f suffixes), String pool and equals, arrays, ca… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. Java 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

Java, Variables, Types, Type Casting, Primitives 등으로 검색하시면 이 글이 도움이 됩니다.