∮explotación≒ 개발

java 연산자 에 대해서 알아보자 자바 연산자 란

파란형 2023. 2. 17.
반응형

 

연산자

 

연산자는 하나, 둘 또는 세 개의 피연산자에서 특정 작업을 수행 한 다음 결과를 반환하는 특수 기호입니다.

 

Java 프로그래밍 언어의 연산자를 탐색 할 때 어떤 연산자가 우선 순위가 가장 높은지 미리 아는 것이 도움이 될 수 있습니다. 다음 표의 연산자는 우선 순위에 따라 나열됩니다.

 

작업자가 테이블 상단에 가까울수록 우선 순위가 높아집니다.

우선 순위가 높은 연산자는 우선 순위가 상대적으로 낮은 연산자보다 먼저 평가됩니다.

같은 줄의 연산자가 우선 순위가 같습니다.

우선 순위가 같은 연산자가 동일한 표현식에 나타날 때 먼저 평가되는 규칙이 적용되어야합니다.

할당 연산자를 제외한 모든 이진 연산자는 왼쪽에서 오른쪽으로 평가됩니다. 할당 연산자는 오른쪽에서 왼쪽으로 평가됩니다.

 

postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

 

 

간단한 할당 연산자

가장 일반적인 연산자 중 하나는 간단한 할당 연산자입니다 = 입니다

이 연산자를 오른쪽의 값을 왼쪽의 피연산자에 할당합니다:

int cadence = 0;
int speed = 0;
int gear = 1;
 

이 연산자는 섹션에서 설명한대로 객체 참조를 할당하기 위해 객체에서 사용할 수도 있습니다 

 

산술 연산자

 

Java 프로그래밍 언어는 덧셈, 뺄셈, 곱셈 및 나눗셈을 수행하는 연산자를 제공합니다.

단 %는  하나의 피연산자를 다른 피연산자로 나누고 그 결과로 나머지를 반환합니다.

 

연산자
+ 문자열 연결에도 사용되는 추가 연산자 
- 빼기 연산자
* 곱셈 연산자
/ 사업부
% 나머지 연산자

다음 프로그램, ArithmeticDemo, 산술 연산자를 테스트합니다.

class ArithmeticDemo {

    public static void main (String[] args) {

        int result = 1 + 2;
        // result is now 3
        System.out.println("1 + 2 = " + result);
        int original_result = result;

        result = result - 1;
        // result is now 2
        System.out.println(original_result + " - 1 = " + result);
        original_result = result;

        result = result * 2;
        // result is now 4
        System.out.println(original_result + " * 2 = " + result);
        original_result = result;

        result = result / 2;
        // result is now 2
        System.out.println(original_result + " / 2 = " + result);
        original_result = result;

        result = result + 8;
        // result is now 10
        System.out.println(original_result + " + 8 = " + result);
        original_result = result;

        result = result % 7;
        // result is now 3
        System.out.println(original_result + " % 7 = " + result);
    }
}
 

이 프로그램은 다음을 인쇄합니다:

1 + 2 = 3
3 - 1 = 2
2 * 2 = 4
4 / 2 = 2
2 + 8 = 10
10 % 7 = 3
 

산술 연산자를 간단한 할당 연산자와 결합하여 복합 할당을 만들 수도 있습니다. 예를 들어, x += 1; 과 x = x + 1; 둘 다의 가치를 증가 x 1.

그만큼 + 연산자는 다음과 같이 ( 조인 ) 두 줄을 함께 연결하는 데 사용할 수도 있습니다 ConcatDemo 프로그램:

class ConcatDemo {
    public static void main(String[] args){
        String firstString = "This is";
        String secondString = " a concatenated string.";
        String thirdString = firstString+secondString;
        System.out.println(thirdString);
    }
}
 

이 프로그램이 끝날 무렵 변수 thirdString 포함 This is a concatenated string., 표준 출력으로 인쇄됩니다.

 

 

 

 

 

 

단항 연산자

단항 연산자는 하나의 피연산자 만 필요합니다. 그들은 값을 하나씩 증가 / 감소, 표현식 부정 또는 부울의 값 반전과 같은 다양한 작업을 수행합니다.


+ 단항 연산자; 양수 값 (이 없으면 숫자가 양수임을 나타냅니다. )
- 단항 빼기 연산자; 표현식을 무효화
++ 증분 연산자; 값을 1 씩 증가시킵니다.
-- 감소 연산자; 1만큼 값 감소
! 논리적 보완 연산자; 부울의 가치를 뒤집다

다음 프로그램, UnaryDemo, 단항 연산자를 테스트합니다:

class UnaryDemo {

    public static void main(String[] args) {

        int result = +1;
        // result is now 1
        System.out.println(result);

        result--;
        // result is now 0
        System.out.println(result);

        result++;
        // result is now 1
        System.out.println(result);

        result = -result;
        // result is now -1
        System.out.println(result);

        boolean success = false;
        // false
        System.out.println(success);
        // true
        System.out.println(!success);
    }
}
 

증분 / 감소 연산자는 ( 접두사 ) 이전 또는 ( postfix ) 이후에 적용 할 수 있습니다. 코드 result++; 과 ++result; 결과가 1 씩 증가합니다. 유일한 차이점은 접두사 버전 (입니다.++result)은 증분 값으로 평가되는 반면, 접두사 버전 (result++)은 원래 값으로 평가됩니다. 간단한 증분 / 감소를 수행하는 경우 실제로 어떤 버전을 선택하든 상관 없습니다. 그러나이 연산자를 더 큰 표현의 일부로 사용하면 선택한 연산자가 큰 차이를 만들 수 있습니다.

다음 프로그램, PrePostDemo, 접두사 / postfix 단항 증분 연산자를 보여줍니다:

class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        // prints 4
        System.out.println(i);
        ++i;               
        // prints 5
        System.out.println(i);
        // prints 6
        System.out.println(++i);
        // prints 6
        System.out.println(i++);
        // prints 7
        System.out.println(i);
    }
}
 

 

관계 운영자

등식 및 관계형 연산자는 한 피연산자가 다른 피연산자보다 크거나 작거나 같거나 같지 않은지 결정합니다. 


== 같은
!= 같지 않다
> 보다 큰
>= 이상
< 보다 작은
<= 이하

다음 프로그램, ComparisonDemo, 비교 연산자를 테스트합니다:

class ComparisonDemo {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if(value1 == value2)
            System.out.println("value1 == value2");
        if(value1 != value2)
            System.out.println("value1 != value2");
        if(value1 > value2)
            System.out.println("value1 > value2");
        if(value1 < value2)
            System.out.println("value1 < value2");
        if(value1 <= value2)
            System.out.println("value1 <= value2");
    }
}
 

이 프로그램을 실행하면 다음과 같은 출력이 발생합니다:

value1 != value2
value1 <  value2
value1 <= value2
 

 

조건부 연산자

그만큼 && 과 || 연산자는 두 부울 표현식에서 Conditional-AND 및 Conditional-OR 작업을 수행합니다. 이 연산자는 "단락"동작을 나타내며, 이는 필요한 경우에만 두 번째 피연산자가 평가됨을 의미합니다.

운영자설명
&& 조건부
|| 조건부 OR

다음 프로그램, ConditionalDemo1, 다음 연산자를 테스트합니다:

class ConditionalDemo1 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if ((value1 == 1) && (value2 == 2))
            System.out.println("value1 is 1 AND value2 is 2");
        if ((value1 == 1) || (value2 == 1))
            System.out.println("value1 is 1 OR value2 is 1");
    }
}
 

다른 조건부 연산자는 ?:, 의 속기라고 생각할 수 있습니다 if-then-else (에서 논의 된 진술 제어 흐름 설명 섹션). 이 연산자는 삼항 세 개의 피연산자를 사용하기 때문에 연산자. 다음 예제에서이 연산자는 다음과 같이 읽어야합니다. "someCondition이 true 인 경우 결과에 value1 값을 할당하십시오. 그렇지 않으면 결과에 value2 값을 할당하십시오."

다음 프로그램, ConditionalDemo2, 테스트 ?: 운영자:

class ConditionalDemo2 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        int result;
        boolean someCondition = true;
        result = someCondition ? value1 : value2;

        System.out.println(result);
    }
}
 

때문에 someCondition 이 프로그램은 "1"을 화면에 인쇄합니다. 사용하다 ?: 대신 연산자 if-then-else 코드를 더 읽기 쉽게 만들 수 있는지 명시하십시오. 예를 들어 표현식이 작고 과제가 (과 같은 부작용이없는 경우.

 

유형 비교 연산자 인스턴스

그만큼 instanceof 연산자는 객체를 지정된 유형과 비교합니다. 객체가 클래스의 인스턴스인지, 서브 클래스의 인스턴스인지 또는 특정 인터페이스를 구현하는 클래스의 인스턴스인지 테스트하는 데 사용할 수 있습니다.

다음 프로그램, InstanceofDemo, 부모 클래스 ( 이름을 정의합니다 Parent), 간단한 인터페이스 ( 이름 MyInterface) 및 아동 클래스 ( 이름 Child부모로부터 물려 받아 인터페이스를 구현하는 ).

class InstanceofDemo {
    public static void main(String[] args) {

        Parent obj1 = new Parent();
        Parent obj2 = new Child();

        System.out.println("obj1 instanceof Parent: "
            + (obj1 instanceof Parent));
        System.out.println("obj1 instanceof Child: "
            + (obj1 instanceof Child));
        System.out.println("obj1 instanceof MyInterface: "
            + (obj1 instanceof MyInterface));
        System.out.println("obj2 instanceof Parent: "
            + (obj2 instanceof Parent));
        System.out.println("obj2 instanceof Child: "
            + (obj2 instanceof Child));
        System.out.println("obj2 instanceof MyInterface: "
            + (obj2 instanceof MyInterface));
    }
}

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
 

다음 프로그램은 다음과 같은 출력을 생성합니다:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
 

사용할 때 instanceof 운영자, 명심하십시오 null 아무것도 아닙니다.

 

비트 및 비트 시프트 연산자

Java 프로그래밍 언어는 또한 통합 유형에서 비트 단위 및 비트 시프트 작업을 수행하는 연산자를 제공합니다. 이 섹션에서 논의 된 운영자는 덜 일반적으로 사용됩니다. 따라서 적용 범위는 간단합니다. 의도는 이러한 운영자가 존재한다는 것을 단순히 인식하게하는 것입니다.

단항 비트 단위 보완 연산자 ~ 비트 패턴을 반전시킵니다. 모든 "0"을 "1"로 만들고 모든 "1"을 "0"으로 만드는 모든 적분 유형에 적용 할 수 있습니다". 예를 들어, 바이트에는 8 비트가 포함됩니다. 비트 패턴이있는 값에이 연산자를 적용 00000000 패턴을 11111111.

서명 된 왼쪽 교대 운영자 << 비트 패턴을 왼쪽으로 이동하고 서명 된 오른쪽 이동 연산자 >> 비트 패턴을 오른쪽으로 이동합니다. 비트 패턴은 왼쪽 피연산자에 의해 제공되며 오른쪽 피연산자에 의해 이동할 위치 수입니다. 서명되지 않은 오른쪽 이동 연산자 >>> 가장 왼쪽 위치로 0을 이동하고 가장 왼쪽 위치는 >> 부호 확장에 따라 다릅니다.

비트 단위 & 연산자는 비트 단위로 AND 작업을 수행합니다.

비트 단위 ^ 연산자는 비트 배타적 OR 작업을 수행합니다.

비트 단위 & 연산자는 비트 단위로 포함 OR 작업을 수행합니다.

다음 프로그램, BitDemo, 비트 단위 AND 연산자를 사용하여 숫자 "2"를 표준 출력에 인쇄합니다.

class BitDemo {
    public static void main(String[] args) {
        int bitmask = 0x000F;
        int val = 0x2222;
        // prints "2"
        System.out.println(val & bitmask);
    }
}
 
 

 

 

 

 

자바 Var

Var Java SE 10부터는 var 로컬 변수를 선언하기위한 유형 식별자. 이렇게하면 컴파일러가 생성 한 변수의 실제 유형을 결정하게합니다. 일단 생성되면이 유형을 변경할 수 없습니다. 다음 예를 고려

tipoazul.tistory.com

 

 

 


 

 

※ 쿠팡 파트너스 활동을 통해 일정액의 수수료를 제공 받을 수 있습니다 

 

 

 

 

 

 

 

https://tipoazul.tistory.com/
홈으로

반응형

댓글