본문 바로가기

JAVA

1-3강 - Java Arithmetic Operator

5. Arithmetic Operators

1) Base arithmetic

2) Unary operator

3) Mathematics method

기본 연산 외에 더 다양한 수학적 연산이 필요한 경우 Math를 가져와서 쓴다.

 

Math.pow(x,y) : return x^y

Math.sqrt(x): square root of x

Math.random(): returns a random number in the range [0, 1).

추가로 min, max, PI, E 등등이 더 있다.

 

cf> method 앞에 붙는 것

1> static method

- method 앞에 오는 것 : class

- instance를 만들지 않고 사용할 수 있다.

- static 이라는 keyword를 사용해서 만든다.

2> instance method

- method 앞에 오는 것 : instance

- instance를 만들어야 method를 사용할 수 있다.

 

 

4) 형변환

5) 관계 연산자 (relational operator) & 논리 연산자 (logical operator)

1> 관계 연산자 (relational operator) 

결과는 true 혹은 false가 됩니다. (결과 값이 boolean이 된다.)

그래서 논리 연산자와 같이 쓰일 수 있습니다.

(5<3)&&(2>=1)

(false)&&(true)

(false)

 2> 논리 연산자 (logical operator)

AND : &&

OR : ||

NOT : !

 

6) Assignment operator

C언어와 유사

 

7) 조건 연산자 (conditional operator)

time < 12 ? "am" : "pm"

1> 설명

- if문을 operator로 표현하는 것

- 3항 연산자

2> 구조

{조건} ? {조건이 true일 때 실행} : {조건이 false일 때 실행}

 

8) 비트 연산자 (bit-wise operator, shift operator)

1> op1 & op2
The AND operator compares two bits and generates a result of 1 if both bits are 1;
otherwise, it returns 0.
2> op1 | op2
The OR operator compares two bits and generates a result of 1 if either or both bits
are 1; otherwise, it returns 0.
3> op1^ op2
The EXCLUSIVE-OR operator compares two bits and generates a result of 1 if the bits
are complementary; otherwise, it returns 0.
4> ~op1
The COMPLEMENT operator is used to invert all of the bits of the operand.
5> op1 >> op2
The SHIFT RIGHT operator moves the bits to the right, discards the far right bit, and
assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in
half.

(a >> 2 : a 의 bit를 오른쪽으로 2칸 이동)

(00010000 >> 2 : 00000100)  
6> op1 << op2
The SHIFT LEFT operator moves the bits to the left, discards the far left bit, and
assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1
by 2.
7> 예제 

8> bit assignment operator

&= 

|= 

^= 

<<= 

>>=

9) operator priority

'JAVA' 카테고리의 다른 글

[Java] 1-5강 - Inputs and Outputs  (0) 2020.10.06
1-4강 - String  (0) 2020.10.06
1-2강 - Java Primitive Type, Variable, Constant  (0) 2020.10.06
1-1강 - JAVA 기본기 (Hello World!)  (0) 2020.10.06
0강 - JAVA란?  (0) 2020.09.10