Java/Java 문법 연습

연산자 연습

구너드 2023. 5. 12. 00:04
public class 연산자_01 {
public static void main(String[] args) {
int x = 10; int y = 5;

System.out.println(x + y);
System.out.println(-x + 3);
System.out.println(-x * y);
System.out.println(x > y);
System.out.println("-x + 3 =" + (-x + 3));
System.out.println("-x + 3 =" + (-x) + 3);
System.out.print("-x + 3 =");
System.out.println(-x + 3);
System.out.println(-x + 3);
// ? 왜 두 개 값이 다른지 이해 완료
// System.out.println(x = y);
// 대입 연산자는 우변의 값을 좌변에 저장

System.out.println();

System.out.println(x + y * 6);
// 위의 x=y를 주석 처리하지 않았을 경우 x 값과 y 값이 같아진 상태로 진행
System.out.println((x + y) * 6);
// 연산 순서를 수동으로 설정하고 싶다면 괄호 사용
// 산술>비교>논리>대입 순으로 시행
// 단항>이항>삼항 순으로 시행
// 단항 연산자와 대입 연산자를 제외한 모든 연산의 진행방향은 왼쪽에서 오른쪽

public class 연산자_02 {
public static void main(String[] args) {
int x = 10, y = x++, z = y++;

System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
// 의도한 값은 x = 10, y = 11 z = 12이지만 결과가 다름
// 추론: y = x++에서 y = x가 먼저 연산되기에 y = x = 10, x++ = 11로 되고 11 = x = y, 그렇다면 z 값도 11이 되어야 하는데 그렇지 않음.
// y = x = 10으로 반환, 이후 x++ = 11이 되어 x값으로 반환
// z = y = 10으로 반환, 이후 y++ = 11이 되어 y값으로 반환
// 그대로 Z = 10, 따라서 x = 11, y = 11, z = 10

System.out.println();

int a = 0, b = 3;

a = b++;
// a = b;
// b++;
// 후위형은 값이 참조된 후에 증가/감소시킴
System.out.println("a = b++;, a= " + a);
System.out.println("a = b++;, b= " + b);

System.out.println();

a=0; b=3;

a = ++b;
// ++b;
// a = ++b;
// 전위형은 값이 참조되기 전에 증가/감소시킴
System.out.println("a = ++b;, a= " + a);
System.out.println("a = ++b;, b= " + b);

System.out.println();

int i = -10;
i = - i;
System.out.println(i);
// '-'부호 연산자는 피연산자의 부호를 반대로 변경

System.out.println();

int in = 65, num = 10;
char ch = 'A';
float f = 3.14f;

System.out.println("(char)i = " + (char)in);
System.out.println("(int)ch = " + (int)ch);
System.out.println("(int)f = " + (int)f);
System.out.println("(float)num = " + (float)num);
// 형변환, 변수 또는 상수의 타입을 다른 타입으로 변환하는 것을 의미
// (타입)피연산자

System.out.println();

float flo = 1234;
// 상대적으로 int 타입이 float 타입보다 작기 때문에 저장이 가능
// 원래는 float flo = (float)1234;로 변수와 리터럴의 타입을 일치시켜줘야함
// 형변환이 생략되어 있으며 컴파일러에 의해 자동으로 형변환 된 것
// int wjd = 3.14f;
// 이렇게 큰 타입을 작은 타입에 저장할 때 에러 발생
int wjd = (int) 3.14f;
// 값은 3이 나오고 값 손실이 발생했음을 알 수 있음
// "기존의 값을 최대한 보존할 수 있는 타입으로 자동 변환된다."

byte b3 = (byte) 1000;
System.out.println("b3 =" + b3);
// -24가 저장되는 지 알아 볼 것(추론:아마도 연속적인 오버플로우 때문?)

public class 연산자_03 {
public static void main(String[] args) {
char ch = '2';

System.out.print("ch - '0' =");
System.out.println(ch - '0');
// 문자 2 는 숫자로 50, 0 48 따라서 50 - 48 = 2 가 출력

int a = 1_000_000, b = 2_000_000;
long l = a * b;
System.out.println(l);
// int의 저장치를 벗어나기 때문에 오버플로우 발생

long L = (long)a * b;
System.out.println(L);
// 두 피연산자 중에 하나만 타입을 변환시켜줘도 됨
// 타입을 바꿀 때 보다 큰 타입으로 일치시킴
// 피연산자의 타입이 int보다 작은 타입이면 int로 변환됨
System.out.println();

long result = Math.round(3.141592);
// round는 실수를 소수점 첫 째 자리에서 반올림한 정수를 반환
System.out.println("result = " + result);

result = result * 1000;
System.out.println("result = " + result);
// 원래 의도는 3141.592로 해서 바꾸려했으나 이미 result 값은 3이 되었고 여기에 1000을 곱했으므로 3000이 나옴

double pi = 3.141592;
// System.out.println((double)Math.round(pi * 1000) / 1000);
// 내가 작성해본 코드
double shortPi = Math.round(pi * 1000) / 1000.0;
System.out.println(shortPi);

// 3.141구해보기
double Pi = 3.141592;
// double prcPi = (float)(((int)(Pi * 1000)) / 1000); 쓰레기 같은 내가 만든 코드
System.out.println("(int)(Pi * 1000) = " + (int)(Pi * 1000));
System.out.println("(int)(Pi * 1000) / 1000.0 = " + (int) (Pi * 1000) / 1000.0);
// Pi * 1000 int로 형변환하여 3141을 구하고 이를 실수 타입의 1000.0으로 나누어 3.141을 구함

// round():소수점 첫 째 자리에서 반올림한 정수 반환
// ceil():올림값을 double형으로 반환
// floor():내림값을 double형으로 반환
// abs():int,double 기본형 모두 사용 가능하며 절대값을 반환

System.out.println();

int x = 10, y = 3;
System.out.println(x % y);

int n = -7, m = 7;
System.out.println(x % n);
System.out.println(x % m);

x = - x;
System.out.println(x % y);
// 나머지 연산자 %는 오른쪽 피연사자로 나누고 남은 나머지를 반환, n m의 경우처럼 부호는 무시되며, 값은 0이 아닌 정수만을 허용

 


public class 연산자_04 {
public static void main(String[] args) {
int i = 10, j = 15;

System.out.println(i == j);
System.out.println(i != j);
System.out.println(i >= j);
System.out.println(i <= j);

System.out.println();

char ch = 'A', ar = 'B';

System.out.println(ch != ar);
System.out.println(ch <= ar);
// 산술변환규칙(char = 2byte, int = 4byte 이므로 보다 큰 타입에 일치시키는 산술변환규칙) 의해서 char 타입이 int 타입으로 변환되어 연산

System.out.println();

String str1 = "Dog", str2 = "God";
System.out.println(str1.equals(str2));
// 문자열의 비교에는 ==대신 .equals()를 사용

System.out.println();
boolean result1, result2, result3, result4;
char ch1 = 'a', ch2 = 'B';

result1 = 'a'< ch1 && ch1 < 'c';
result2 = 'a'< ch2 && ch2 < 'c';

int num = 10;

result3 = num % 2 ==0 && num % 3 ==0;
result4 = num % 2 !=0 || num % 3 ==0;
System.out.println(result3);
System.out.println(result4);

blic class 연산자_04 {
public static void main(String[] args) {
int i = 10, j = 15;

System.out.println(i == j);
System.out.println(i != j);
System.out.println(i >= j);
System.out.println(i <= j);

System.out.println();

char ch = 'A', ar = 'B';

System.out.println(ch != ar);
System.out.println(ch <= ar);
// 산술변환규칙(char = 2byte, int = 4byte 이므로 보다 큰 타입에 일치시키는 산술변환규칙) 의해서 char 타입이 int 타입으로 변환되어 연산

System.out.println();

String str1 = "Dog", str2 = "God";
System.out.println(str1.equals(str2));
// 문자열의 비교에는 ==대신 .equals()를 사용

System.out.println();
boolean result1, result2, result3, result4;
char ch1 = 'a', ch2 = 'B';

result1 = 'a'<= ch1 && ch1 <= 'c';
result2 = 'a'<= ch2 && ch2 <= 'c';
System.out.println(result1);
System.out.println(result2);

int num = 10;

result3 = num % 2 ==0 && num % 3 ==0;
result4 = num % 2 !=0 || num % 3 !=0;
System.out.println(result3);
System.out.println(result4);

System.out.println();

int num1 = 5, num2 = 7;
int result;

result = num1 - num2 > 0 ? num1 : num2;

System.out.println(result);
// 삼항 연산자 유튜브 강의 다시 한 번 체크할 것

System.out.println();

int x= 10, y = 10, z = 10;

x = x - 5;
y -= 5;
z = -5;

System.out.println(x);
System.out.println(y);
System.out.println(z);
// 대입 연산자들 설명 볼 것