Type Casting Part 1
Coddy Java 여정의 기초 섹션에 포함된 레슨 — 73개 중 13번째.
형 변환은 값을 하나의 데이터 형식에서 다른 데이터 형식으로 변환하는 과정입니다.
Java에서 정수를 double로, double을 정수로, 그리고 그 외의 변환도 할 수 있습니다. 형변환에는 두 가지 유형이 있습니다: implicit (자동) 및 explicit (수동) 형변환입니다.
예를 들어 integer to double:
묵시적 (자동) 캐스팅:
int number = 5;
double decimal = number; // automatically becomes 5.0
// with calculation
int x = 7;
double result = x / 2.0; // result is 3.5명시적 (수동) 캐스팅 double to integer:
double decimal = 9.7;
int number = (int) decimal; // 9가 됩니다 (소수 부분이 버려집니다)
// 계산과 함께
double price = 19.99;
int roundedPrice = (int) price; // 19가 됩니다챌린지
초급타입 캐스팅을 보여주는 Java 프로그램을 작성하세요. 다음 작업을 수행하세요:
price라는 이름의double변수를 선언하고99.99값으로 초기화하세요.price변수를int로 캐스팅하고 결과를intPrice라는 새 변수에 저장하세요.price와intPrice의 값을 콘솔에 출력하세요.
치트 시트
형 변환은 값을 하나의 데이터 타입에서 다른 데이터 타입으로 변환합니다. 두 가지 유형이 있습니다:
묵시적(자동) 형 변환 - 작은 데이터 타입에서 큰 데이터 타입으로:
int number = 5;
double decimal = number; // automatically becomes 5.0명시적(수동) 형 변환 - 큰 데이터 타입에서 작은 데이터 타입으로:
double decimal = 9.7;
int number = (int) decimal; // becomes 9 (decimal part is truncated)직접 해보기
public class Main {
public static void main(String[] args) {
// 변수 선언 및 초기화
double price = 99.99;
int intPrice = ?;
// 값 출력
System.out.println("Price: " + price);
System.out.println("Int Price: " + intPrice);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else