본문 바로가기
Language/JAVA

[JAVA] 2-5~6 연산자 == , equals 논리연산자 true , false && ||

by 아이엠제니 2022. 2. 3.

부스트코스 생활코딩 [쉽게 배우는 자바2] 공부 기록

 

 

2-5 == vs equals

primitive: 원시 데이터 타입

non primitive: 원시 데이터 타입이 아닌 것

 

 

== 동등 비교연산자는 값이 같은 곳에 위치하고 있는지를 따짐

원시 데이터 타입이 아닌 것은 equals로. 

 

 

 

2-6 논리연산자 (logical operator)

package javaChapter2_6;

public class LogicalOperatorApp {
    public static void main(String[] args) {
        System.out.println(1 == 1);

        // AND
        System.out.println(true && true); // true
        System.out.println(true && false); // false
        System.out.println(false && true); // false
        System.out.println(false && false); // false

        // OR
        System.out.println(true || true); // true
        System.out.println(true || false); // true
        System.out.println(false || true); // true
        System.out.println(false || false); // false

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

 

비밀번호가 2개인 사용자

package javaChapter2_6;

import java.util.Scanner;

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

        Scanner sc = new Scanner(System.in);

        System.out.print("Input your id: ");
        String id = "egoing";
        String inputId = sc.next();

        System.out.print("Input your password: ");
        String pass = "1111";
        String pass2 = "2222";
        String inputPass = sc.next();

        System.out.println("Hi");

        if (inputId.equals(id) && (inputPass.equals(pass) || inputPass.equals(pass2))) {
                System.out.println("Master!");
            } else {
            System.out.println("Who are you?");
        }
    }
}

조건문데 논리연산자 사용!

비밀번호를 2개 설정하면, 2개 다 사용할 수 있게 만들 수도 있다.

 

 

 

boolean isRightPass = (inputPass.equals(pass) || inputPass.equals(pass2));
if (inputId.equals(id) && isRightPass) {
        System.out.println("Master!");
    } else {
    System.out.println("Who are you?");
}

변수 활용해서 조건문 코드를 간결하게 바꿈!

300x250