본문 바로가기

Programming/자바

생활코딩 자바 - 연산자

연산자

특정 작업 하기 위한 기호

ex. 대입, 산술(+, -, *, /, %(나머지)), 비교, 논리 연산자 등

 

형변환

package org.opentutorials.javatutorials.operator;

public class DivisonDemo {

public static void main(String[] args) {
int a = 10;
int b= 3;

float c = 10.0F;
float d = 3.0F;

System.out.println(a/b); // 정수/정수= 3.333 => 소수점 없앰 -> 3
System.out.println(c/d); // 3.3333..
System.out.println(a/d); // 10/3.0F -> 10.0F/3.0F로 자동 형변환 -> 3.3333..

 

}}

 

단항 연산자

하나의 항 대상으로 연산 이루어짐

 

cf) 1 + 2 => + 는 이항 연산자 (1은 좌항, 2는 우항)

 

+ : 양수

- : 음수

++ : 증가 연산자, 1씩 증가

-- : 감소 연산자

 

package org.opentutorials.javatutorials.operator;

public class PrePostDemo {

public static void main(String[] args) {
int i = 3;
i ++; 
System.out.println(i); //4
++ i;
System.out.println(i); //5
System.out.println(++i); // 6 => 바로 i + 1 결과 보여줌
System.out.println(i++); // 6 => 다음 행부터 i + 1 값 반영
System.out.println(i); //7
}
}

 

우선순위

연산자에는 우선순위가 있음

 

1 - [] () .

2 - ++ -- +(양수) -(음수) ~ ! (type) new

3 - * / %

4 - +(더하기) -(빼기) +(문자 결합용)

...

 

외우지 않아도 됨, 헷갈릴 때만 참고