| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- java
- 추상클래스
- GoF 23
- 템플릿 메서드 패턴
- 김영한
- 스케줄러
- Spring
- lv1
- 프로그래머스
- 코드카타
- 빌더 패턴
- 성능 개선
- DB
- 디자인 패턴
- 이펙티브 자바
- 토스
- Spring Batch
- 스프링
- 자바
- Effective Java
- 백엔드
- 계산기
- 배치
- redis
- Til
- 트러블슈팅
- 로드밸런서
- spring boot
- 스프링 배치
- 프록시 패턴
Archives
- Today
- Total
김코딩
자바 - 형변환 본문
형변환
int -> long -> double
- 작은 범위에서 큰 범위로는 대입할 수 있다.
-> 이것을 묵시적 형변환 또는 자동 형변환이라 한다.
- 큰 범위에서 작은 범위의 대입은 다음과 같은 문제가 발생할 수 있다. 이때는 명시적 형변환을 사용해야 한다.
-> 소수점 버림
-> 오버플로우
- 연산과 형변환
-> 같은 타입은 같은 결과를 낸다.
-> 서로 다른 타입의 계산은 큰 범위로 자동 형변환이 일어난다.
예제 1
package castiong;
public class casting1 {
public static void main(String[] args) {
int intValue = 10;
long longValue;
double doubleValue;
longValue = intValue;
System.out.println("longValue = " + longValue);
doubleValue = intValue;
System.out.println("doubleValue = " + doubleValue);
doubleValue = 20L;
System.out.println("doubleValue2 = " + doubleValue);
}
}

예제 2
package castiong;
public class casting2 {
public static void main(String[] args) {
double doubleValue = 1.5;
int intValue = 0;
// intValue = doubleValue
intValue = (int) doubleValue;
System.out.println(intValue);
int z = (int) 10.5;
System.out.println(z);
}
}

예제 3
package castiong;
public class casting3 {
public static void main(String[] args) {
long maxIntvalue = 2147483647; //int 최고값
long maxIntOver = 2147483650L; //int 최고값 + 1(초과)
int intValue = 0;
intValue = (int) maxIntvalue;
System.out.println("maxIntValue casting = " + intValue);
intValue = (int) maxIntOver;
System.out.println("maxIntOver casting = " + intValue);
}
}

예제 4
package castiong;
public class casting4 {
public static void main(String[] args) {
int div1 = 3/2; //1
System.out.println("divi = " + div1);
double div2 = 3/2; //1.0
System.out.println("div2 = " + div2);
double div3 = 3.0/2; //1.5
System.out.println("div3 = " + div3);
double div4 = (double) 3/2; //1.5
System.out.println("div4 = " + div4);
int a= 3;
int b = 2;
double result = (double) a/b;
System.out.println("result = " + result); //1.5
}
}

'Java' 카테고리의 다른 글
| 자바 - 다형성1 (0) | 2025.04.01 |
|---|---|
| 자바 - 메서드 (0) | 2025.02.26 |
| 자바 - 반복문 (0) | 2025.01.31 |
| 자바 - Scanner (1) | 2024.04.25 |