본문 바로가기
Study/Back

Jul.12.Wed.2023 나도코딩 Java 상수 ~ 형 변환

by Jobsoony 2023. 7. 12.
728x90
반응형

독학 3일차

*상수_06_Constants

  • 변수 - 변할 수 있는 수
  • 상수 - 절대 변하지 않는 수 > 앞에 final을 붙여주면 됨.

              *상수 이름은 대문자들로 하되 띄어쓰기는 _(언더바)로 가독성 높일 것

*형 변환_07_TypeCasting

> 형 변환이란? 정수형에서 실수형으로, 실수형에서 정수형으로 변환하는 것
                       int score = 93 + 98.8;
                      위와 같이 정수형 데이터와 실수형 데이터를 연산해서 집어넣을 때 문제 발생

> 정수에서 실수 int to float, double

int score = 93;
System.out.println(score); // 93
System.out.println((float) score); // 93.0
System.out.println((double) score); // 93.0


> 실수에서 정수 float, double to int

float score_f = 93.3 F; // 혹은 f
double score_d = 98.8;
System.out.println((int) score_f); // 93
System.out.println((int) score_d); // 98


> 정수 + 실수 연산

score = 93 + (int) 98.8; // 93 + 98
System.out.prrintln(score); // 191
score_d = (double) 93 + 98.8; // 93.0 + 98.8
System.out.println(score_d); // 191.8



> 변수에 형 변환된 데이터 집어넣기
   double convertedScoreDouble = score; // 191 -> 191.0
       !!! int convertedScoreInt = score_d; // 191.8 -> 191
           위 소스코드는 큰 단위에서 작은 단위로의 변환이기 때문에 에러남.
           int convertedScoreInt = (int) score_d;

     𖤐 int -> long -> float -> double 큰 단위에서 작은 단위는 자동 형 변환
         double -> float -> long -> int 작은 단위에서 큰 단위로는 수동 형 변환

> Class
   예약어 뒤에 .을 찍으면 예약어 클래스에서 쓸 수 있는 기능들이 있음.
     ex) String. / Integer. / Double. …

> 숫자를 문자열로
   - 정수

       𖤐String이라는 클래스가 제공하는 valueOf라는 기능을 사용해 정수를 문자열로 바꿈.

String s1 = String.valueOf(i:93); // i:-> 자동생성 됨. 
s1 = Integer.toString(i:93);
System.out.println(s1); // 93


   - 실수

String s2 = String.valueOf(d:98.8);
System.out.println(s2); // 98.8
s2 = Double.toString(d:98.8);
System.out.println(s2); // 98.8


> 문자열을 숫자로
   𖤐 “” 사이에 정수나 실수가 아닌 글자가 들어가면 에러남.

int i = Integer.parse.Int(s:”93”);
System.out.println(i); // 93
double d = Double.parseDouble(s:”98.8”);
System.out.println(d); // 98.8
728x90
반응형