Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
관리 메뉴

codingfarm

Type Casting 본문

Programming Language/JAVA

Type Casting

scarecrow1992 2025. 5. 29. 15:46

https://www.w3schools.com/java/java_type_casting.asp

 

W3Schools.com

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

특정 원시타입(Primitive Type)을 다른 타입으로 전환하는 기술

Java에는 2가지 캐스팅 방식이 존재한다.

  • Widening Casting (automatically) - converting a smaller type to a larger type size
    byte -> short -> char -> int -> long -> float -> double

  • Narrowing Casting (manually) - converting a larger type to a smaller size type
    double -> float -> long -> int -> char -> short -> byte

 

▶ Widening Casting의 예

public class Main {
  public static void main(String[] args) {
    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double

    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
  }
}

 

▶ Narrowing Casting의 예

public class Main {
  public static void main(String[] args) {
    double myDouble = 9.78d;
    int myInt = (int) myDouble; // Manual casting: double to int

    System.out.println(myDouble);   // Outputs 9.78
    System.out.println(myInt);      // Outputs 9
  }
}

 

 

 

'Programming Language > JAVA' 카테고리의 다른 글

캡슐화(Encapsulation)  (0) 2025.05.29
제어자(Modifier)  (0) 2025.05.29
사용자정의 예외 만들기  (0) 2021.04.05
예외 되던지기(exception re-throwing  (0) 2021.04.05
예외 처리(exception handling)  (0) 2021.03.22
Comments