Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

3.2 산술 연산자 - 산술 연산의 특징 본문

이것이 자바다/03 연산자

3.2 산술 연산자 - 산술 연산의 특징

빌드이너프 2024. 3. 29. 08:59

- 피연산자가 정수 타입(byte, short, char, int)이면 연산의 결과는 Int 타입

- 피연산자가 정수 타입이고 그 중 하나가 long 타입이면 연산의 결과는 long 타입

- 피연산자 중 하나가 실수 타입이면 연산의 결과는 실수 타입

package ch03.sec02;

public class ArithmeticOperatorExample {
	public static void main(String[] args) {
		byte v1 = 10;
		byte v2 = 4;
		int v3 = 5;
		long v4 = 10L;
		
		int result1 = v1+v2; // 모든 피연산자는 int 타입으로 자동 변환 후 연산
		System.out.println("result1: " + result1);
		
		long result2 = v1+v2-v4; // 모든 피연산자는 long 타입으로 자동 변환 후 연산
		System.out.println("result2: " + result2);
		
		double result3 = (double) v1/v2; // double 타입으로 강제 변환 후 연산
		System.out.println("result3: " + result3);
		
		int result4 = v1%v2;
		System.out.println("result4: " + result4);
	}
}
result1: 14
result2: 4
result3: 2.5
result4: 2