1.4. Arithmetic Operators
-
값 복사 : (=)
x = expression -
기본 연산자 : (+, -, *, /, %)
정수로 정수 나누면 정수, 실수를 정수로 나누면 실수 -
단항 연산자(Unary Operators)
후위 증감 : n++ , n--
전위 증감 : ++n , --n
ex>
class opPlus{
public static void main(String[] args){
int x=1;
System.out.println("x: "+x);
// 이렇게 하면 x가 추가로 찍혀서 나옴
for(int i=1;i<=3;i++)
System.out.print("x: "+x++ +" ");
// x++ : x 증가
}
}
Mathmatics methods
Math.pow(x, y) : return x^y
Math.sqrt(x) : square root of x
Math.min
Math.max
Math.PI
Math.E
Math.random() : (0 to 1) 에서 랜덤한 값을 반환
그런데 왜 Math는 클래스인데 객체를 안만들고 사용할까?
- static methods
바로 static methods 이기 떄문 static methods는 클래스 자체에 속한거고 그렇지 않은 것을 instance methods라고 부른다.
static methods일 경우 Calling format : class_name.method_name 형식으로 static methods를 불러야 하며 instance method와 다르게 instance 없이도 호출 가능
-
Type Conversion
한쪽 피연산자가double
이면, 다른쪽 피연산자는double
한쪽 피연산자가float
이면, 다른쪽 피연산자는float
한쪽 피연산자가long
이면, 다른쪽 피연산자는long
그거 아니면 두 피연산자는int
임 -
Typecasting
프로그래머가 직접 타입을 변경해 주고 싶은 경우 사용double x = 3.75; int n = (int) x;
-
automatic conversion
byte -> short -> int -> long -> float -> double
이 방향으로 typecasting 해주는 것은 괜찮음 하지만 그 반대방향은 가능 하지 않음
ex>
byte b = (byte) 100000;
short s = (short) 100000;
System.out.println("b : " + b);
System.out.println("s : " + s);
short s = 100 + 1
위와 같은 코드를 예로 들어 보면 자바는 기본 자료형이 int이기 때문에 int to short 형태를 띄고 있음. 따라서 위의 코드는 에러가 남
- Relational operators and logical operators
-
Relational operators
== != > < >= <=
반환값은 true or false
-
Logical operators
&& (AND) || (OR) ! (NOT)
논리 연산자는 왼->오 순으로 논리를 따지기 때문에 && 연산자는 왼쪽이 false이면 오른쪽을 보지 않음 마찬가지로 || 연산자는 오른쪽이 true이면 오른쪽을 보지 않음
- Assignment operators(대입 연산자)
Arithmetic Assignment : +=, -=, *=, /=, %=
Bit Assignment : <<= , >>= , |= (bit or) , &= (bit and) , ^= (bit xor)
특이하게도 대인 연산자의 연산 방향은 오->왼
'CS(Computer Science) > 20) 자바' 카테고리의 다른 글
자바를 자바 07 (0) | 2020.11.16 |
---|---|
자바를 자바 06 (0) | 2020.11.16 |
자바를 자바 05(String/input,output/Control Flow) (0) | 2020.11.16 |
자바를 자바 04 (0) | 2020.11.16 |
자바를 자바 01/02 (0) | 2020.11.16 |