스파르타 spring 2기 TIL day9

fart man·2025년 12월 3일

Java String Interning

import util.*;
import java.util.Scanner;
import java.util.Arrays;

class ArrrayRefTest {
    public static void main(String[] args) {
        String hello1 = "hello"; // interned "hello"
        String hello2 = "hello"; // same interned "hello"
        String hello3 = "he" + "llo"; // becomes "hello" at compile time, interned as "hello"
        String hello4 = new String("hello"); // creates a new string object
        String hello5 = new String("he") + "llo"; // String object + string literal. javac compiler can't figure out this will result "hello"
        String hello6 = null;
        {
            String hel = "hel";
            String lo = "lo";
            hello6 = hel + lo; // Java compiler also can't figure this out. Even though it's adding two String objects created from two string literals.
        }

        System.out.println("================================================");
        System.out.printf("hello1 hashCode %d\n", hello1.hashCode());  // 99162322
        System.out.printf("hello2 hashCode %d\n", hello2.hashCode());  // 99162322
        System.out.printf("hello3 hashCode %d\n", hello3.hashCode());  // 99162322
        System.out.printf("hello4 hashCode %d\n", hello4.hashCode());  // 99162322
        System.out.printf("hello5 hashCode %d\n", hello5.hashCode());  // 99162322
        System.out.printf("hello6 hashCode %d\n", hello6.hashCode());  // 99162322

        System.out.println("================================================");
        System.out.printf("hello1 identity hash %d\n", System.identityHashCode(hello1));  // 1213349904
        System.out.printf("hello2 identity hash %d\n", System.identityHashCode(hello2));  // 1213349904
        System.out.printf("hello3 identity hash %d\n", System.identityHashCode(hello3));  // 1213349904
        System.out.printf("hello4 identity hash %d\n", System.identityHashCode(hello4));  // 3923182939
        System.out.printf("hello5 identity hash %d\n", System.identityHashCode(hello5));  // 444920847
        System.out.printf("hello6 identity hash %d\n", System.identityHashCode(hello6));  // 589835301

        System.out.println("================================================");
        String meme = "meme";
        foo(meme);
        System.out.println(meme);
    }

    // This doesn't modify String s.
    // Java is pass by value everytime.
    // It's just passing a pointer to a s.
    // So assigning to a s doesn't actually change s
    public static void foo(String s) {
        s = s.replaceAll("h", "m");
    }
}

0개의 댓글