본문 바로가기

study

JAVA | Constant expression, Arithmetic Operators, Operator Priority (9월 둘째 주)

Constant Expressions에 관한 5가지 코드

1
2
3
4
5
6
7
8
class dtChar{
    public static void main(String[] args)
    {
        char c;
        c = 'A' + 1;
        System.out.println(c);
    }
}

 

  • Constant expression이므로 컴파일 가능한 코드이다. representable in 2 byte.
자바에서는 캐릭터 타입은 2 byte이다. (C는 1 byte)

 

1
2
3
4
5
6
7
8
class dtChar{
    public static void main(String[] args)
    {
        char c;
        c = 'A' + 1000000;
        System.out.println(c);
    }
}

 

  • 에러! 숫자가 2 byte에 맞지 않으므로.

 

1
2
3
4
5
6
7
8
9
class dtChar{
    public static void main(String[] args)
    {
        char c;
        char a = 'A';
        c = a + 1;
        System.out.println(c);
    }
}
 

 

  • 에러! Constant expression이 아니다.
  • a는 변수이기 때문에 계산 불가. 컴파일 시 a는 무슨 값인지 모름.

 

1
2
3
4
5
6
7
8
9
class dtChar{
    public static void main(String[] args)
    {
        char c;
        fianl char a = 'A';
        c = a + 1;
        System.out.println(c);
    }
}
 

 

  • Constant expression이므로 컴파일 가능한 코드이다. (char 대신 final char)

 

1
2
3
4
5
6
7
8
class dtChar{
    public static void main(String[] args)
    {
        char c;
        c += 50000000;
        System.out.println(c);
    }
}
 

 

  • 컴파일 가능한 코드이다.
  • c +=는 되는데 c= c + … 는 안 됨. (이유는 잘 모름)

 

Constant expression is ②represantable → automatically convert 가능하다.

 

 

Arithmetic Operators

  • Typecasting : 변수의 타입을 explicitly 바꾸는 것
  • Automatic conversion : byte → short → int → long → float → double
Okay! Compile error!
  • double d = 100;
  • short s = (short)3.14;
  • long l = (long)d;
  • short s = 3.14;
  • long l = d;
  • Relational operators and logical operators : ==, !=, >, <, <=, >=, &&, ||, !
  • &&을 쓰는데 첫 번째 명제가 거짓일 경우, 두 번째 명제는 계산되지 않는다. (아예 확인도 안 함)
  • ||을 쓰는데 첫 번째 명제가 참일 경우, 두 번째 명제는 계산되지 않는다.
  • Bit-wise operators : AND "&", OR "|", EXCLUSIVE-OR "^", COMPLEMENT "~", SHIFT RIGHT ">>", SHIFT LEFT "<<"

Operator Priority