급할수록도라에몽
GoodmorningSun
급할수록도라에몽
전체 방문자
오늘
어제
  • 🌏Hello World (73)
    • 👨🏻‍💻Computer Science (28)
      • 🙂Java (6)
      • 😊Spring (0)
      • 💻Algorithm (22)
      • 😉JavaScript (0)
      • 😀CSS (0)
      • 😌HTML (0)
    • 📄TIL (3)
    • 📈오늘의 경제 (17)
    • 🌎MyEnglish (18)
      • 😎Lexicon (18)
    • 💻AI (1)
      • 👨🏻‍💻chatGPT (1)
    • ✈️Prague(프라하) (5)
    • 👨🏻‍💻Apple (1)
    • WorldQuant (0)

블로그 메뉴

  • 🔑Github
  • 🔑Tistory

인기 글

태그

  • 딥시크
  • PLTR
  • 혼자공부하는자바
  • 프라하
  • Java
  • Til
  • eft
  • Prague
  • English
  • cardio
  • 알고리즘
  • 팔란티어
  • FOMC
  • 프로그래머스
  • TMF
  • ChatGPT
  • 체코
  • ai
  • 생활코딩
  • 미국채권
  • 피보나치 되돌림
  • metabolism
  • 실리콘밸리 은행
  • Cardiovascular
  • 인플레이션 감축법
  • INTC
  • 영어
  • 경제
  • SVB
  • ptp

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
급할수록도라에몽

GoodmorningSun

[Java] 연산자(Operator) 한 번에 정리하기(+-=:><*%!==?/)
👨🏻‍💻Computer Science/🙂Java

[Java] 연산자(Operator) 한 번에 정리하기(+-=:><*%!==?/)

2022. 12. 5. 23:55
728x90

연산에 사용되는 표시나 기호를 연산자(Operator)라고 한다!

정말 다양한 연산자가 있는데

더하기 빼기 곱하기 나누기와 같은 산술 연산자부터 비교 연산자 논리 연산자 등이 있다.

연산자 목록

헷갈렸던 것들 그리고 추가로 알면 좋은 것들을 위주로 정리를 해보려고 한다.

% 와  / 

% 은 나머지를 보여주는 연산자

/ 은 진짜 나눠주는 연산자

int v1 = 5;
int v2 = 2;

int result01 = v1 / v2;
// result01의 값은 2
// 나누기를 해주는 연산자 int타입이여서 정수만 보여주기 때문에 원래는 2.5가 나와야되지만 2가 나옴.

int result02 = v1 % v2;
// result02의 값은 1
// %는 나머지를 보여주는 연산자

double result03 = (double) v1 / v2;
// result03의 값은 2.5
// result01 에서는 int타입이여서 2가 나왔지만 double타입으로 해주어서 정확한 값인 2.5가 나옴.

: Colon

What does a colon mean in Java Programming라고 구글형한테 물어봤더니 다음과 같이 대답해주셨다.

According to Oracle docs, When you see the colon(:) read it as "in".

class Solution {
    public int solution(int[] numbers) {
        int answer = 45;
       for(int num : numbers){
           answer-=num;
       }
        return answer;
    }
}

프로그래머스에서 알고리즘 문제를 풀다가 : colon을 보게 되었는데 

위 코드에서는 : colon이 in이라는 의미를 가지고 있으니까 numbers 안에 있는 숫자를 num으로 하나씩 받아서 answer에서 계속해서 빼주는 의미로 해석할 수 있다. 저기서 numbers는 {1,2,3,4,5} 이런 배열 형태였다.

 

비교 연산자(==,!=, >, <, <=, >=)

>, <, <=, >=와 같은 크기를 비교하는 연산자는  boolean 타입을 제외한 모든 타입에서 사용 가능!

나중에 배울 조건문(if) 반복문(for, while)에서 주로 이용되며 정말 정말 정말 정말 많이 사용한다.

 

헷갈리는 것은 문자열을 비교할 때는 대소 연산자는 사용할 수 없고 ==,!= 과 같은 연산자는 사용할 수 있지만

문자열이 같은지 다른지를 비교하는 데에는 사용하지 않는다.

👉문자열 비교는 equals() 메소드를 사용!

 

논리 연산자(&&, ||, &, |, ^,!)

값을 부정해버리는 중요한 놈(!)

👉 논리 부정 연산자는 true를 false로 false를 true로 변경하기 때문에 boolean타입에만 사용 가능!

boolean play = true;
System.out.println(play);
//ture

play = !play;
System.out.println(play);
//false
//ture 값을 가진 play를 논리 부정 연산자 !로 상태 변경

play = !play;
System.out.println(play);
//true
//false 값을 가진 play를 !로 상태 변경

 

AND의 의미(&&, &)

👉 둘이 같은 의미이지만 &&는 앞의 피연산자가 false이면 바로 산출 결과를 내놓는데

&는 앞 뒤 둘 다 확인 후 결과를 산출하기 때문에 &&가 더 효율적!

 

OR의 의미(||, |)

👉 || 는 앞의 피연산자가 ture라면 뒤의 피연산자를 평가하지 않고 바로 true라는 산출 결과를 내놓는데

|는 두 피연산자를 모두 평가해서 결과를 내놓기 때문에 ||가 더 효율적!

 

삼항 연산자 (score > 90)? 'A' : 'B'

연산자를 공부하면서 아주 재미있는 친구라고 생각하고 한동안 알고리즘 문제를 풀 때도

이 친구에 꽂혀서 맨날 삼항 연산자를 사용해서 풀려고 노력했던 기억이 있다.

코드로 보는게 훨씬 이해가 잘 되기 때문에 바로 코드로 고고

int score = 99;
char grade = (score > 90) ? 'A' : 'B';

//점수가 90점이 넘는다면 A 그렇지 않으면 B 이렇게 해석된다.
//char 타입이기 때문에 ''을 사용한 모오습

뒤에서 배울 if 문을 통해서 작성할 수도 있지만 한 줄 에 간단하게 작성하려면 삼항 연산자를 사용하는 것이 더 효율적이다!

int socre = 99;
char grade;
 if(score > 90) {
  grade = 'A';
  } else { 
  grade = 'B';
  } //삼항 연산자를 if문으로 풀어 쓴 모오습

추가적인 연산자 설명

증감 연산자(++,--)

++i는 i=i+1과 동일

--i는 i=i-1과 동일

int x = 1;
int y = 1;
int result01 = ++x + 10;
int result02 = y++ + 10;
//result01은 12
//result02는 11 어라?

헷갈렸던 포인트!

👉 다른 연산자와 함께 사용된다면 증감 연산자의 위치에 따라 연산식의 결과가 다르게 나옴!

증감 연산자가 변수 앞에 있으면 우선 변수값을 1 증가 또는 1 감소시킨 후에 다른 연산자를 처리한다.

But 증감 연산자가 변수 뒤에 있으면 다른 연산자를 먼저 처리한 후 변수 값을 1 증가 또는 1 감소시킨다.

 

그래서 result01는 x의 값이 1 증가되어 2가 된 후 10과 합해져 12가 되고

result02는 y의 값인 1과 10이 합해져 11이 되고 그 후에 y의 값이 증가해 2가 된다.

 

 

연산자 - 생활코딩

연산자란 연산자(演펴다연 算계산산 子, operator)란 특정한 작업을 하기 위해서 사용하는 기호를 의미한다. 작업의 종류에 따라서 대입 연산자, 산술 연산자, 비교 연산자, 논리 연산자 등이 있다.

opentutorials.org

 

비교와 Boolean - 생활코딩

프로그래밍의 비교나 불린은 이것만으로는 효용이 크지 않다. 후속 수업인 반복문과 조건문에서 그 효용이 드러나기 때문에 조금 지루하더라도 조건문까지만 인내하자. Boolean 불린(Boolean)은 참

opentutorials.org

colon 추가 자료

더보기

colon : 에 대하여

According to Oracle docs, When you see the colon(:) read it as "in".

Let's dive deep into more detail:

1. Enhanced for loops (for-each loop)

The enhanced for loop was introduced in Java 5. It was mainly introduced to traverse the collection of elements including arrays. The main advantage of using for each loop is that it makes the code more readable and eliminates the possibility of bugs.

Syntax:

For-each loop syntax consists of datatype with the variable followed by a colon(:) then collection or array.

for(dataType variable : collection | array)
{
  // statements
}

Example:

1. Array

Suppose we have givenArray, then we can traverse it using conventional for loop or using new enhanced for loop(for-each loop) as shown below in the image:

https://blogger.googleusercontent.com/img/a/AVvXsEg5b9_j_HL6n_x8S9He8QCgCYNc2rr-Rxfu0v1cyp1jQwutzYWVsqiZxWfpHCJXwD6FyVtf55vAij3zDm9OGPoLQFGUuogea56sl_CpjYfYwKMS7NFsFWrmxJRHCPLU4lCbRJ-edvcxQ2asb06GvfGuDOYlDNFKro9E9NifvIUsknpe4WQRJXpCbDOi_Q=w640-h256

public class ColonJava {
    public static void main(String args[]) {
        // Declaring the Array
        int[] givenArray = {11, 7, 45, 19};
        // Traversing the array using for-each loop
        for (int val : givenArray)
        {
            System.out.println(val);
        }
    }
}

Output:

11

7

45

19

One of the downsides of the for-each loop is that you can not traverse elements in reverse order. Also, you can not skip any number of elements.

2. Ternary expression

As the name suggests, the ternary operator takes three terms and its syntax is:

Syntax:

BooleanExpression ? Expression1 : Expression2

The value of the BooleanExpression is determined. If it is true, then the value of the whole expression is Expression1, else, if it is false then the value of the whole expression is Expression2.

Example:

public class ColonJava2 {
    public static void main(String args[]) {
        boolean val = true;
        int x = val ? 9 : 2;
        System.out.println(x);
    }
}

Output:9

3. Labeling of the loops

In Java, a label is a valid variable name. The label denotes the name of the loop to where the control of execution should jump. It is simple to label a loop, place the label before the loop with a colon at the end as shown below in the example:

public class ColonJava3 {
    public static void main(String args[]) {
        int i, j=0;
        //outer label
        outerloop:
        for(i=0; i < 3; i++) {
            System.out.print(i+" ");
            // inner label
            innerloop:
            for(j=0; j < 4;j++) {
                System.out.print(j + " ");
                if (j==1)
                    break innerloop;
            }
        }
    }
}

Output:0 0 1 1 0 1 2 0 1

4. Switch statements after case or default

The simple syntax of the switch statement is given below:

switch(expression){
case a:
    // statements
    break;
case b:
    // statements
    break;
default:
    //statements
}

You can see that we have used colon(:) after the case and default keywords. You can find in detail the switch statements

here

.

That's all for today, please mention in the comments in case you have any questions related to what does a colon means in Java programming.

About The Author

Subham Mittal has worked in Oracle for 3 years.Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

저작자표시

'👨🏻‍💻Computer Science > 🙂Java' 카테고리의 다른 글

[Java] ArrayList 한바탕 휩쓸고가기  (0) 2022.12.11
[Java] 조건문과 반복문 if for  (0) 2022.12.09
[Java] substirng 문자열 자르기 대작전  (1) 2022.12.07
[Java] 자동 타입변환(Promotion) vs 강제 타입변환(Casting)  (0) 2022.12.04
[Java] 변수 (variable) & 기본 타입 (primitive type)  (0) 2022.12.03
    '👨🏻‍💻Computer Science/🙂Java' 카테고리의 다른 글
    • [Java] 조건문과 반복문 if for
    • [Java] substirng 문자열 자르기 대작전
    • [Java] 자동 타입변환(Promotion) vs 강제 타입변환(Casting)
    • [Java] 변수 (variable) & 기본 타입 (primitive type)
    급할수록도라에몽
    급할수록도라에몽
    안녕하세요, 반갑습니다:D

    티스토리툴바