(JAVA) 연산자,조건식

InAnarchy·2022년 10월 20일
0

JAVA

목록 보기
1/18
post-thumbnail

Table of Contents

  • 비교 연산자
  • 논리 연산자
  • 증감 연산자
  • 삼항 연산자
  • 조건식의 예

비교 연산자

논리 연산자

증감 연산자

위의 b = ++a;, b = a++;에서는 차이가 있지만
++a; a++;처럼 증감 연산자가 독립적으로 사용되면 차이가 없다.

public class op{
    public static void main(String[] args) {
        int x = 0, y = 0;
        y = ++x;
        x = x + 1;
        y = x;
        System.out.printf("x: %d, y: %d%n", x, y);

        y = x++;
        System.out.printf("x: %d, y: %d%n", x, y);

        y = -x;
        System.out.printf("x: %d, y: %d%n", x, y);
    }
}
output
x: 2, y: 2
x: 3, y: 2
x: 3, y: -3

삼항연산자(Ternary)

Sysntax : (조건문) ? 참 : 거짓

Example

public class Ternary {
    public static void main(String[] args) {
        int a = 3; int b = 5;
        System.out.println("두 수의 차는 " + ((a>b)?(a-b):(b-a))); //2
    }
}
public class Ternary {
    public static void main(String[] args) {
       int score = 83;
        System.out.println((score>80)?("pass"):("fail"));
    }
}
public class Ternary {
    public static void main(String[] args) {
        String name = "name";
        System.out.println((name.equals("name") ? "name" : "who?"));
    }
}
public class Ternary {
    public static void main(String[] args) {
        int num1 = 3;
        int num2 = 5;
        int num3 = (num1 < num2) ? ++ num1 : ++ num2;

        System.out.println(num3); //4
    }
}

삼항연산자의 중첩

public class Ternary {
    public static void main(String[] args) {
       int x = 4; int y = 6;
        System.out.println((x<y)?((x==4)?4:6):(y));
    }
}

이 코드를 풀어쓰면 아래와 같다.

public class Ternary {
    public static void main(String[] args) {
        int x = 4;
        int y = 6;
        if (x < y) {
            if (x == 4)
                System.out.println(4);
            else
                System.out.println(6);
        } else
            System.out.println(y);
    }
}

조건식의 예

profile
github blog 쓰다가 관리하기 귀찮아서 돌아왔다

0개의 댓글