[JAVA]/JAVA 기본

[JAVA] 형변환 총정리

팡펑퐁 2022. 9. 12. 20:52
728x90

String to int (문자열에서 인트로)

String str = "123";
int i = Integer.palseInt(str);

int to String(인트에서 문자열)

int i = 123;
String str = Integer.toString(i);

String to char(문자열에서 문자 추출)

String str = "abc";
char c = str.chatAt(0); //str의 index값 입력

char to String(문자형에서 문자열로)

char a = 'a';
String str = String.valueOf(a);

int to float (정수형에서 실수형으로)

int a = 1;
int b = 2;
int c = 5;
float f1 = (a+b+c)/3; // 2.0
float f2 = (float) (a+b+c)/3; // 2.6666667
float f3 = (1+2+5)/3; //2.0
float f4 = (float) (1+2+5)/3; //2.6666667

float to int (실수형에서 정수형으로)

float a = 1;
float b = 2;
float c = 5;
int f1 = (a+b+c)/3; // 오류
int f2 = (int) (a+b+c)/3; // 2

 

 

728x90