* 산술 변환
연산 전 피 연산자의 타입을 일치시키는 것.
int형 - float형 --> float형 - float형
float형 - double형 --> double형 - double형
으로 자동 변환된다.
결과값도 이를 반영해 리턴되므로 조심하자!
* int보다 작은 크기의 타입은 int형으로 변환됨.
ex) char형 - char형 --> int형 - int형
반올림 - Math.round()
// 소수점 첫 째 자리에서 반올림 후 정수 반환
long result = Math.round(4.52);
System.out.println(result); // 5
// 원하는 자리에서 반올림
double pi = 3.141592;
double shortPi = Math.round(pi * 1000) / 1000.0;
double shortPi2 = Math.round(pi * 1000) / 1000;
System.out.println(shortPi); // 3.142
System.out.println(shortPi2); // 3.0
문자열을 비교할 때 '==' 연산자 보단 .equals() 를 사용하자.
String 객체 생성시 == 연산자는 오류가 발생할 수 있음.
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2); // true
System.out.println(str1.equals(str2)); // true
String str3 = new String("abc");
String str4 = new String("abc");
System.out.println(str3 == str4); // false
System.out.println(str3.equals(str4)); // true
논리 연산자
// || (or 결합) && (and 결합)
int x = 15;
System.out.println(10 < x && x < 20); // true
System.out.println(x % 2 == 0 || x % 3 == 0); // true
// 2의 배수 또는 3의 배수지만, 6의 배수는 아니다.
System.out.println((x%2 == 0 || x%3 == 0)&& x%6 != 0); // true
// 문자 ch는 '0' ~ '9' 이다
char ch = '7';
System.out.println('0' <= ch && ch <= '9'); // true
조건 연산자 (간단한 if구문)
// 조건식 ? 식1 : 식2 조건식이 true면 식1, false면 식2 반환
int results1 = (5<3) ? 5 : 3;
int results2 = (5>3) ? 5 : 3;
System.out.println(results1); // 3
System.out.println(results2); // 5'코딩 > JAVA 공부' 카테고리의 다른 글
| [JAVA] 자바의 정석 _ 제어문 for, while/ continue, 반복문 이름 붙이기 (0) | 2022.10.06 |
|---|---|
| [JAVA] 자바의 정석 _ 제어문 if, switch / 임의의 정수 (0) | 2022.10.06 |
| [JAVA] 자바의 정석 _ printf() 의 지시자, Scanner (0) | 2022.10.04 |
| [JAVA] 자바의 정석 _ 기본형 & 참조형 (1) | 2022.10.03 |
| [JAVA] 자바의 정석 _ 문자형 & 문자열 (0) | 2022.10.03 |