Skip to main content

[Java] 삼항 연산자, 논리 연산자, char, 자료 형변환

Updated 5 min readMarkdown
Part of seriesTIL
[Java] 삼항 연산자, 논리 연산자, char, 자료 형변환

쉬프트(shift) 연산

삼항연산자 (4)

import java.util.Scanner;
public class Ternary4 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int random;

        System.out.print("값을 입력하세요 : ");
        random = sc.nextInt();

        sc.close();

        //int s = random % 2 == 0 ? 1 : (random % 3 == 0 ? 1 : 0);  <-- 연산자 중첩
        int s = (random % 2 == 0) || (random % 3 == 0) ? 1 : 0;          // <-- 논리연산자 && 사용

        System.out.println();
        System.out.println("입력하신 값 : " + random);
        System.out.println("결과 = " + s);

    }
}

삼항연산자 (5)

import java.util.Scanner;
public class Ternary5 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        char one;            //변수 one : 키보드 입력 문자

        System.out.print("알파벳를 입력하세요 : ");
        one = sc.next().charAt(0);

        sc.close();

        String s = ('A' <= one && one <= 'Z') ? " 대문자 입력완료" : ('a' <= one && one <= 'z')? "소문자" :" 알파벳이 아닙니다.";

        System.out.println();
        System.out.println("입력한 값의 첫번째 자리 : " + one);
        System.out.println("결과 > " + s);
    }
}

비트 논리 부정연산자 (~)

  • 10진수 : 0,1,2,3,4,5,6,7,8,9

  • 16진수 : 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

  • 8진수 : 0,1,2,3,4,5,6,7

  • 2진수 : 0,1

  • 10진수

    • 1234 => 1 x 10^3 + 2 x 10^2 + 3 x 10^1 + 4 x10^0 => 1000 + 200 + 30 + 4
  • 16진수 => 10진수

    • 0xAOE => 10x16^2 + 0x16^1 + 14x16^0 => 2360 + 0 +14 => 2574
  • 8진수 => 10진수

    • 0125 => 1x8^2 + 2x8^1 + 5x8^0 => 64 + 16 + 5 => 85
  • 2진수 => 10진수

    • 01101 => 0x2^4 + 1x2^3 + 1x2^2 + 0x2^1 + 1x2^0 => 0 + 8 + 4 + 0 + 1 => 13
  • 10진수 => 2진수

  • 10진수 13을 2진수로 변환 1101

[1] 음수 10진수를 2진수로 표현하는 방법 => 2의 보수를 구한다. (1의 보수 + 1)

    • 예) 10진수 -8 을 2진수로 표현

      1. (부호-) 8을 2진수 ( 부호와 절대치)로

10001000

  1. (부호-) 1의 보수로 변환

11110111

  1. (부호-) 1의 보수에 1을 더한다.

11111000 => 2의 보수 (-8)

  • [2] 음수 2진수를 10진수로 변환 빨리확인하기 (Tip)

    • 예) 11111000를 10진수로 변환

      1. 앞에서부터 시작해서 마지막 1만 취하고 왼쪽 버린다.

1000

  1. 첫번째 자리만 -로 계하고 나머지를 +로 계산

1x-8 + 0x4 + 0x2 + 0x1 => -8

  • 예) 11110111를 10진수로 변환

    10111 => 1x-16 + 0x8 + 1x4 +1x2 + 1x1 => -23

package oop20230414;

public class Operator10 {

    public static void main(String[] args) {

        System.out.println(~0);
        // 0 0000000
        // 1 1111111
        System.out.println(~1);
        // 0 0000001
        // 1 1111110     ---> 부호를 먼저 생각하고 연속되는 1의 마지막 자리만 취한다. 
                                                // 111111은 버리고 10만 생각하면 2 , 거기에 부호 자리가
                                                // 1이므로 -, 그 결과 -2가 나온다.
    }
}

정수연산 : %, &, ^, |, ~ <<. >>, >>> , 비트 shift 연산자 : << , >> , >>>

public class Operator11 {

    public static void main(String[] args) {

        System.out.println(14<<2);
        System.out.println(14>>2);
        System.out.println(14>>>2);

        // << : Left Shift bitwise-operator
        // x << n : n회 좌측으로 이동
        // 1 : 0000 0001

        System.out.println(1<<1);
        System.out.println(1<<2);
        System.out.println(1<<3);

    }
}

자동 형변환 (1)

  • 자료형 변환 (Type Conversion) : (1) 연산과정, (2) 대입(=)

    1. 자동 형변환(묵시적 형변환) : 컴파일러
  • (연산과정) 자료형이 큰 쪽으로 변환 --> 자료손실이 일어나지 않게 하기 위해

  • int(4) < float(4) < double

  • byte --> short --> int --> long --> float --> double

    char

5.0 / 2 --> 2.5

double / int --> double

(대입) 좌측변수의 자료형 쪽으로 변환 ,

    int a = 10;

    long b = a;

    int --> long
  1. 강제 형변환(명시적 형변환) : 캐스팅 cast 연산자 ---(문법)--> (자료형) 연산대상)
    float a = 3.76f;    a = 3.76

    int b = (int) a;    b = 3

필요한 곳에서 일시적으로 변환 활용

import java.nio.file.spi.FileSystemProvider;

public class Cast1 {

    public static void main(String[] args) {

        int a = 3;
        long b = a;

        System.out.println(a + " " + b);

        float c = 2.4f;
        double d = c;

        System.out.println(c + " " + d);

        int e = 5;
        // byte f = e;    에러

        System.out.println(3/5);
        System.out.println(3/5.0);
        System.out.println(3.0/6);
        System.out.println(3.0/5.0);
    }
}

자동 형변환 (2)

public class Cast2 {

    public static void main(String[] args) {

        System.out.println((int)2.5);                 // (결과) 2
        System.out.println(2.5 + 3.7);                // (결과) 6.2
        System.out.println((int)2.5 + (int)3.7);    // (결과) 5
        //                 int <- double
        System.out.println((int)(2.5 + 3.7));        // (결과) 6

        // **int, char형**
        System.out.println((char)65);           // (결과) 'A'
        System.out.println((char)66);
        System.out.println((char)67);
        System.out.println((char)90);       // (결과) 'Z'

        System.out.println((char)97);           // (결과) 'a'
        System.out.println((char)122);      // (결과) 'z'

        System.out.println((int)'A');       // (결과) 65
        System.out.println((int)'a');       // (결과) 97

        // **Uni코드값, '문자'상수**
        System.out.println('A' + 1);         // (결과) 66 , 자동 형변환
        // **char --> int**
        // 2바이트 -- > 4바이트
        System.out.println((char)('A' + 1));     // (결과) 'B'
        System.out.println((int)('A' + 1));     // (결과) 66

        System.out.println((int)'+');           // (결과) 43
        System.out.println((int)'-');              // (결과) 45
        System.out.println((int)'*');            // (결과) 42    
        System.out.println((int)'/');              // (결과) 47
        System.out.println((int)' ');             // (결과) 32 공백
        System.out.println((int)'\\r');             // (결과) 13 엔터

        System.out.println("#" + (char)('a'-'A') + "#");  // (char)(97 - 65) --> (char)32 --> 공백 ' '

    }
}

자동 형변환 (3)

public class Cast3 {

    public static void main(String[] args) {
        // boolean(1byte), int(4byte)
        // true --> ( 출력)1
        // fasle --> (출력)1
        // false --> (출력)

        int a = 10 > 3 ? 1 : 0;
        System.out.println(a);

        boolean b = 10 > 3; 
        //int c = (b == true) ? 1 :0;

        int c = b ? 1 : 0;
        System.out.println(c);

    }
}

Thumbnail :Image by Freepik

No comments yet. Be the first to comment.

More from this blog