자바 공부중. . .(2) (형변환, 연산자, 비교와 Boolean, 조건문)

Reobivy·2023년 5월 20일
0

이 로딩바, 생각보다 재미있다...!


형변환

자동 형 변환

double a = 3.0F;
이는 오류가 발생하지 않는다. 왜냐하면 double 타입이 float 타입보다 더 많은 수를 표현할 수 있기 때문이다. <타입을 변경해도 정보의 손실이 일어나지 않는 경우>에는 자동 형 변환이 일어난다.
float a = 3.0;
이는 오류가 발생한다. double형인 상수를 더 번위가 좁은 float에 넣기 때문이다.

자동 형 변환이 일어나는 규칙

결국 더 큰 범위로 간다고 생각하면 편하다.

명시적 형 변환

float a = 100.0;
int b = 100.0F;
이는 오류가 발생한다. 상대적으로 작은 범위의 변수에 큰 상수를 넣었기 때문이다.
float a = (float)100.0;
int b = (int)100.0F;
이와 같이 괄호 안에 데이터 타입을 지정해 버리면 오류가 발생하지 않는다. 이를 <명시적 형 변환>이라고 한다.

연산자

산술 연산자

기호역할
+더하기
-빼기
*곱하기
/나누기(몫)
%나머지
package org.opentutorials.javatutorials.operator;
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);
    }
}
+연산자는 문자열끼리 결합할 때에도 사용된다.

단항 연산자

기호역할
+양수를 표현한다. 실제로는 사용할 필요가 없다.
-음수를 표현한다.
++증가(increment) 연산자로 항의 값을 1씩 증가 시킨다.
--감소(Decrement) 연산자
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 출력
        System.out.println(i++); // 6 출력
        System.out.println(i); // 7 출력
    }
}
예시 코드. 여기서 주목할 부분은 4행과 6행이다. ++i는 i의 값에 1이 더해진 값을 출력하는 것이고, i++는 이것이 속해있는 println에 일단 i의 값을 출력하고, 실행이 끝난 뒤에 i값을 증가시킨다.

연산의 우선순위

우선순위연산자결합방향
1[ ], ( ), .
2++, --, +(양수), -(음수), ~, !, (type), new
3*, /, %
4+(더하기), -(빼기), +(문자 결합 연산자)
5<<, >>, >>>
6< <=, > >=, instanceof
7==, !=
8&
9^
10|
11&&
12| |
13? :
14=, *=, /=, +=, -=, %=, <<=, >>=, >>>=, &=, ^=, |=
int a = 4-3*6;
위의 예시를 통해 연산자의 순서를 익혀 보자. 기본적인 사칙연산의 순서를 알고 있다면 어렵지 않다. 표는 헷갈릴 때 보는 것만으로 충분하다.

비교와 Boolean

Boolean은 참(true)과 거짓(false)를 가지는 데이터 타입이다.

==

좌항과 우항을 비교해 값이 같다면 true, 다르다면 false가 된다. =와 헷갈리지 않도록 주의할 것.

!=

!는 부정을 의미한다. =에 !가 붙은 !=는 '같지 않다'를 의미한다.

>

좌항이 우항보다 크다면 true, 아니라면 false가 된다.

<

>=

<=

.equals

package org.opentutorials.javatutorials.compare; 
public class EqualStringDemo { 
    public static void main(String[] args) {
        String a = "Hello world";
        String b = new String("Hello world");
        System.out.println(a == b);
        System.out.println(a.equals(b));
    }
}
결과는 false와 true이다. ==은 두 개의 데이터 타입이 동일한 객체인지를 알아내기 위해서 사용하는 연산자이기 때문에 false라는 결과가 나온다. .equals를 이용하면 서로 다른 객체들간의 값이 같은지를 비교할 수 있다.

조건문

if

package org.opentutorials.javatutorials.condition;
public class Condition1Demo {
    public static void main(String[] args) {
        if(true){
            System.out.println("result : true");
        }
    }
}
if절의 예시. If 뒤의 괄호의 안이 true라면 안의 코드를 실행한다.

else

package org.opentutorials.javatutorials.condition;
public class Condition3Demo {
    public static void main(String[] args) {
        if (true) {
            System.out.println(1);
        } else {
            System.out.println(2);
        }
    }
}
if가 false면 else 안의 코드가 실행된다.

else if

package org.opentutorials.javatutorials.condition;
public class ElseDemo {
    public static void main(String[] args) {
        if (false) {
            System.out.println(1);
        } else if (true) {
            System.out.println(2);
        } else if (true) {
            System.out.println(3);
        } else {
            System.out.println(4);
        }
    }
}
if가 false라면 else if가, else if가 false라면 그 다음 else if가……결국 else로 끝난다.

변수와 비교연산자, 그리고 조건문.

package org.opentutorials.javatutorials.condition; 
public class LoginDemo {
    public static void main(String[] args) {
        String id = args[0];
        if(id.equals("egoing")){
            System.out.println("right");
        } else {
            System.out.println("wrong");
        }
    }
}
변수와 비교연산자, 조건문을 이용한 예시 코드.

조건문의 중첩

package org.opentutorials.javatutorials.condition;
public class LoginDemo2 {
    public static void main(String[] args) {
        String id = args[0];
        String password = args[1];
        if (id.equals("egoing")) {
            if (password.equals("111111")) {
                System.out.println("right");
            } else {
                System.out.println("wrong");
            }
        } else {
            System.out.println("wrong");
        }
    }
}
조건문의 중첩을 이용한 예시 코드. if 안에 if을 또 넣을 수 있다.

switch 문

조건이 많다면 if보다 switch가 로직을 더 명료하게 보여줄 수 있다.
package org.opentutorials.javatutorials.condition; 
public class SwitchDemo {
    public static void main(String[] args) {
        System.out.println("switch(1)");
        switch(1){
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }    
        System.out.println("switch(2)");
        switch(2){
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }
        System.out.println("switch(3)");
        switch(3){
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }
    }
}
결과는 다음과 같다.
switch(1)
one
two
three
switch(2)
two
three
switch(3)
three
이와 같이 switch는 뒤의 괄호를 포함한 이후의 케이스를 실행시킨다.
switch는 몇가지 제한된 데이터 타입만을 사용할 수 있다. byte, short, char, int, enum, String, Character, Byte, Short, Integer
default는 switch문에서 else의 역할을 한다.
이 포스트는 <생활코딩>의 자바 강의를 요약한 포스트입니다.

0개의 댓글