연산 관련 용어
- 연산자
: 연산에 사용되는 기호나 표시- 피연산자
: 연산에 사용되는 데이터 또는 변수- 연산식
: 연산자와 피연산자를 사용하여 연산하는 과정
연산자 | 기능 | 사용 예 | 의미 |
---|---|---|---|
+= | 좌변에 우변을 더함 | a += 2 | a = a + 2 |
-= | 좌변에 우변을 뺌 | a -= 3 | a = a - 3 |
*= | 좌변에 우변을 곱함 | a *= 4 | a = a * 4 |
/+ | 좌변에 우변을 나눔 | a /= 5 | a = a / 5 |
%= | 좌변에 우변을 나눈 나머지 | a %= 6 | a = a % 6 |
🖥️예시
public class helloWorld{
public void main(String[] args) {
int i = 100;
i += 100; // 200 (i = i + 100)
i -= 50; // 150 (i = i - 50)
i *= 2; // 300 (i = i * 2)
i /= 100; // 3 (i = i / 100)
i %= 2; // 1 (i = i % 2)
System.out.println(i); // i = 1
}
}
byte
, short
, int
, long
)와 실수(float
, double
) 연산 시, 정수가 실수 형태로 자동 변환되어 처리되기 때문에 결과는 실수가 됨2-1. 나눗셈에 대해 더 알아보자
🖥️ ' / '
: 몫 출력
public class helloWorld{
public void main(String[] args) {
int num1 = 12;
int num2 = 8;
int result1 = num1 / num2;
System.out.println("12 / 8 = " + result1);
}
}
결과값
12 / 8 = 1
🖥️ ' % '
: 나머지 출력
public class helloWorld{
public void main(String[] args) {
int num1 = 12;
int num2 = 8;
int result2 = num1 % num2;
System.out.println("12 % 8 = " + result2);
}
}
결과값
12 % 8 = 4
증감 연산자 | 설명 |
---|---|
x++ | 먼저 해당 연산을 수행한 후, 피연산자의 값을 1 증가 |
++x | 먼저 피연산자의 값을 1 증가시킨 후, 해당 연산을 진행 |
x-- | 먼저 해당 연산을 수행한 후, 피연산자의 값을 1 감소 |
--x | 먼저 피연산자의 값을 1 감소시킨 후, 해당 연산을 진행 |
🖥️ x++
public class helloWorld{
public void main(String[] args) {
int a = 100;
int x = 1;
int y = a + x++;
// y = 100 + 1; 먼저 계산
// y에 101이라는 값이 대입된 후에 x++ 계산
System.out.println("y = " + y);
System.out.println("x = " + x);
}
}
결과값
y = 101
x = 2
🖥️ x++
//'++x' 예시
public class helloWorld{
public void main(String[] args) {
int a = 100;
int x = 1;
int y = a + ++x;
// ++x가 먼저 계산됨
// y = 100 + 2;
System.out.println("y = " + y);
System.out.println("x = " + x);
}
}
결과값
y = 102
x = 2
연산 결과는
boolean
(true/false) 값으로 생성된다.
* String은?
==에 대한 연산은 String.equals()로 한다.
🖥️ a && b (and 연산자)
: a가 true고 b가 true면(둘 다 true면) 결과는 true
public class helloWorld{
public void main(String[] args) {
int a = 100;
int b = 200;
int x = 5;
int y = 3;
boolean result1 = a < b && a==b; // false
boolean result2 = a < b && x > y; // true
}
}
🖥️ a || b (or 연산자)
: a 또는 b 둘 중 하나라도 true면 결과는 true
public class helloWorld{
public void main(String[] args) {
int a = 100;
int b = 200;
int x = 5;
int y = 3;
boolean result1 = a < b || a==b; // true
boolean result2 = a > b || x < y; // false
}
}
🖥️ !a (not 연산자)
: a가 true면 false, a가 false면 true
public class helloWorld{
public void main(String[] args) {
boolean a = true;
boolean b = !a;
System.out.println(b); // !true -> false
}
}