본문 바로가기
예제 노트/Java 예제

Java 예제 ch 3 연산자 예제

by Ing_til_death 2021. 10. 20.

- 실수형 끼리의 대소 비교

public class Test {
    public static void main(String[] args) {
        float f = 0.1f; // 저장할 때 2진수로 변화하는 과정에서 오차 발생
        double d = 0.1; // 똑같이 오차가 발생하나 float타입 0.1f보다 적은 오차로 저장.
        double d2 = (double) f;

        System.out.printf("10.0==10.0f %b%n", 10.0==10.0f); // 오차없이 저장 가능
        System.out.printf("0.1 == 0.1f %b%n", 0.1 == 0.1f); 
        // 정수형과 달리 실수형은 근사값으로 저장되므로 오차 발생 가능
        System.out.printf("f == %19.17f%n", f);
        System.out.printf("d == %19.17f%n", d);
        System.out.printf("d2 == %19.17f%n", d2); // f->d 형변환은 값 변화x
        System.out.printf("d==f %b%n", d==f);
        System.out.printf("d==d2 %b%n", d==d2);
        System.out.printf("d2=f %b%n", d2==f);
        System.out.printf("(float)d ==f %b%n", (float)d == f); 
        // f->d 형변환해도 값 변화가 없으니 d->f 형변환을 해야 f과 d 타입 값 비교 가능
     	// 애초에 d가 f보다 적은 오차로 저장했으니..
    }
}


결과
10.0==10.0f true
0.1 == 0.1f false
f == 0.10000000149011612
d == 0.10000000000000000
d2 == 0.10000000149011612
d==f false
d==d2 false
d2=f true
(float)d ==f true

- 문자열의 비교

public class Test {
    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = new String("abc");
        System.out.printf( "str1 == \"abc\" ? %b%n", str1=="abc");
        System.out.printf( "str2 == \"abc\" ? %b%n", str2=="abc");
    }
}

결과
str1 == "abc" ? true // 왜 이게 true인지 의문이다
str2 == "abc" ? false

// => 다른 이유는, 
// 모든 객체의 메모리 주소는 다른 게 맞습니다. heap이라는 메모리 공간에 만듭니다.
// 그런데 String은 조금 다릅니다. 
// String은 같은 문자열을 여러 다른 객체로 만들 필요가 없어서 Constant pool이라는 곳에 하나만 만듭니다.
// Constant pool도 heap 내부에 있고, 문자열 리터럴로 만들면 Constant pool을 이용.
// but new로 문자열을 만들면 그렇지 않고 별개의 객체로 만든다고 합니다.
// 출처: https://starkying.tistory.com/entry/what-is-java-string-pool
// String literal로 생성한 객체는 "String Pool"에 들어간다.
// String literal로 생성한 객체의 값(ex. "Cat")이 이미 String Pool에 존재한다면, 
// 해당 객체는 String Pool의 reference를 참조한다. s1과 s2가 같은 곳을 가리키고 있는 것
// new 연산자로 생성한 String 객체는 같은 값이 String Pool에 이미 존재하더라도, 
// Heap 영역 내 별도의 객체를 가리키게 된다.

- 비트 전환 연산자 예제, toBinaryString(4byte의 정수를 32자리의 2진수로 변환) 을 사용한 예제. 

public class Test {
    public static void main(String[] args) {
        byte p = 10;
        byte n = -10;

        System.out.printf(" p =%d \t%s%n", p, toBinaryString(p));
        System.out.printf(" ~p = %d \t%s%n", p, toBinaryString(~p));
        System.out.printf(" ~~p = %d \t%s%n", p, toBinaryString(~~p));
        System.out.println("");
        System.out.printf(" n = %d%n", n);
        System.out.printf(" ~(n-1) = %d%n", ~(n - 1));
    }

    static String toBinaryString(int x){
        String zero = "00000000000000000000000000000000";
        String tmp = zero + Integer.toBinaryString(x);
        return tmp.substring(tmp.length()-32); // substring(i) 는 index i부터 끝까지
        }

    }

결과
 p =10 	00000000000000000000000000001010
 ~p = 10 	11111111111111111111111111110101
 ~~p = 10 	00000000000000000000000000001010

 n = -10
 ~(n-1) = 10

 

'예제 노트 > Java 예제' 카테고리의 다른 글

Java 예제 ch 5 배열  (0) 2021.10.21
Java 예제 Ch 4 조건문, 반복문  (0) 2021.10.21

댓글