TIL

TIL 241010

muerha 2024. 10. 10. 22:33

 

 

Java 문법 종합반 2주차

 


 

연산자와 피연산자

 

연산자 : 덧셈, 뺄셈 처럼 계산할 기호 
피연산자 : 연산자로 인해 계산되는 숫자

 

 

연산자의 종류

 

산술연산자 : +, -, *, /, %(나머지), <<, >>
비교연산자 : >, <, >=, =<, ==, !=
논리연산자: &&, ||, !
대입연산자 : =, ++, --
기타연산자: (type), ? :, instance of

 

 

산술연산자

 

+ (덧셈), - (뺄셈), * (곱셈), / (나눗셈/몫), % (나눗셈/나머지)

package week02;

public class W02 {
    public static void main(String[] args) {
        // 사칙연산 : +, -, *, /, %
        System.out.println(4 + 2); // 6
        System.out.println(4 - 2); // 2
        System.out.println(4 * 2); // 8
        System.out.println(4 / 2); // 2
        System.out.println(5 / 2); // 2 몫만 리턴
        System.out.println(2 / 4); // 0
        System.out.println(4 % 2); // 0
        System.out.println(5 % 4); // 1
        System.out.println("--------------------");

        // 우선순위 연산
        System.out.println(2 + 2 * 2); // 6
        System.out.println((2 + 2) * 2); // 8
        System.out.println(2 + (2 * 2)); // 6
        System.out.println("--------------------");

        // 변수를 이용한 연산
        int a = 20;
        int b = 10;
        int c;

        // 덧셈
        c = a + b;
        System.out.println(c); // 30

        // 뺼셈
        c = a - b;
        System.out.println(c); // 10

        // 나눗셈(몫)
        c = a / b;
        System.out.println(c); // 2

        // 나눗셈(나머지)
        c = a % b;
        System.out.println(c); // 0
    }
}

 

 

 

비교연산자 

 

값의 크고/작음을 비교하거나 같고/다름 을 비교하여 참(true)/거짓(false) 값인 boolean 값을 출력
> (크다) , < (작다), >= (크거나 같다), <= (작거나 같다), == (같다), != (다르다)

 

논리연산자

비교 연산의 결과값으로 받을 수 있는 boolean 값을 연결하는 연산자

조건을 연결 하였을때의 boolean 값들을 조합하여 참(true)/거짓(false) 값인 boolean 값을 출력

 
package week02;

public class W04 {
    // 논리연산자
    // 비교 연산의 결과값으로 받을 수 있는 boolean 값을 연결하는 연산자
    // 조건을 변결하였을 때 boolean 값들을 조합하여 참(true) 또는 거짓(false) 값인 boolean 값을 출력
    // &&(AND). ||(OR). !(NOT)
    public static void main(String[] args) {
        boolean flag1 = true; // boolean은 flag라는 변수명을 많이 씀
        boolean flag2 = true;
        boolean flag3 = false;

        System.out.println(flag1);
        System.out.println(flag2);
        System.out.println(flag3);

        // (2) 피 연산자 중 하나라고 true이면 true => 또는(OR : ||)
        System.out.println("_________________________");
        System.out.println(flag1 || flag2); // true
        System.out.println(flag1 || flag2 || flag3); // true

        // (2) 피 연산자가 모두 true이면 true => 그리고(AND : &&)
        System.out.println("_________________________");
        System.out.println(flag1 && flag2); // true
        System.out.println(flag1 && flag2 && flag3); // false

        // (3) AND
        System.out.println("_________________________");
        System.out.println((5 > 3) && (3 > 1)); // true && true -> true
        System.out.println((5 > 3) && (3 < 1)); //  true && false -> false

        // (4) OR
        System.out.println("_________________________");
        System.out.println((5 > 3) || (3 > 1)); // true || true -> true
        System.out.println((5 > 3) || (3 < 1)); // true || false -> true
        System.out.println((5 < 3) || (3 < 1)); // false || false -> false

        // System.out.println(1 < 3 < 5); // 불가능!

        // 논리 부정 연산자(! : NOT)
        System.out.println("NOT_________________________");
        System.out.println(!flag1); // false
        System.out.println(!flag3); // true
        System.out.println(!(5 == 5)); // false
        System.out.println(!(5 == 3)); // true
    }
}

 

 

대입연산자

 

기본 대입 연산자

복합 대입 연산자

package week02;

// 대입연산자
public class W05 {
    public static void main(String[] args) {
        // 변수를 바로 연산해서 그 자리에서 저장하는(대입하는) 연산자
        // =(기본 대입 연산자), +=, -=, *= ...(복합 대입 연산자)
        // ++ : += 1
        // -- : -= 1

        // 기본 대입 연산자
        int number = 10;
        number = number + 2;
        System.out.println(number); // 12

        number = number - 2;
        System.out.println(number); // 10

        number = number * 2;
        System.out.println(number); // 20

        number = number / 2;
        System.out.println(number); // 10

        number = number % 2;
        System.out.println(number); // 0

        System.out.println("_____________");
        // 복합 대입 연산자
        number = 10;

        number +=2; // number = number + 2;
        System.out.println(number); // 12

        number -=2; // number = number - 2;
        System.out.println(number); // 10

        number *=2; // number = number * 2;
        System.out.println(number); // 20

        number /=2; // number = number / 2;
        System.out.println(number); // 10

        number %=2; // number = number % 2;
        System.out.println(number); // 0

        // ++, --
//        number = number + 1;
//        number += 1;
        System.out.println("_____________");
        number++;
        System.out.println(number); // 1

        number--;
        System.out.println(number); // 0
    }
}

 

 

대입 연산자 중에 증감 연산자 쓸 때 주의할 점

피연산자 뒤에 붙이냐, 앞에 붙이냐에 따라서 연산순서가 달라진다.

package week02;

public class W06 {
    public static void main(String[] args) {
        // 대입연산자에서 주의해야 할 점!
        // ++, --
        int a = 10;
        int b = 10;
        int val = ++a + b--; // 11 + 9 = 20일 것이라고 예상
        System.out.println(a); // 11
        System.out.println(b); // 9
        System.out.println(val); // 21

        // 20이 아니라 21이 나오는 이유?
        // a 는 val 연산전에 ++ 가 수행되어서 11로 연산되었지만
        // b 는 val 연산후에 -- 가 수행되어서 기존값이 10으로 연산된 후 -- 가 수행됨
        // 따라서 연산된 a값인 11과 연산되기전 b값인 10이 더해져서 21이 된 것
    }
}

 

 

기타연산자

 

형변환 연산자

삼항 연산자

instance of 연산자

package week02;

public class W07 {
    public static void main(String[] args) {
        // 기타 연산자
        // (1) 형변환 연산자
        int intNumber = 93 + (int)98.8; // 93 + 98
        System.out.println(intNumber); // 191

        double doubleNumber = (double) 93 + 98.8; // 93.0 + 98.8
        System.out.println(doubleNumber); // 191.8

        // (2) 삼항연산자
        // 비교연산자와 항상 함께 쓰인다.
        // 비교연산자의 결과 : true or false -> 이 결과의 값에 따라 결정되는 무언가
        //조건? 참 : 거짓
        int x = 1;
        int y = 9;

        boolean b = ( x == y ) ? true : false;
        System.out.println(b); // false

        // x가 y랑 다르니? 응!
        String s = ( x!= y) ? "정답" : "오답";
        System.out.println(s); // 정답

        int max = (x > y) ? x : y;
        System.out.println(max); // 9

        int min = (x < y) ? x : y;
        System.out.println(min); // 1

        // (3) instance of(3주차 -> 클래스, 객체)
        // 피 연산자가 조건에 명시된 클래스의 객체인지 비교하여
        // 맞으면 -> true
        // 틀리면 -> false
    }
}

 

 

연산자 우선순위

package week02;

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

    // 연산자의 우선순위 : 산술 > 비교 > 논리 > 대입
    // 연산자 여러개가 함께 있는 연산을 계산할 때는 우선순위가 있다.
    // 위 우선순위에 따라서 최종적인 응답값이 결정된다.
    // 단, 괄호로 감싸주면 괄호안의 연산이 최우선순위로 계산된다.

        int x = 2;
        int y = 9;
        int z = 10;


        boolean result = x < y && y < z; // true && true
        System.out.println(result);// true
        System.out.println("----------------");

        result = x + 10 < y && y < z; // false && true
        System.out.println(result); // false
        System.out.println("----------------");

        result = x + 2 * 3 > y;
        System.out.println(result); // false
        System.out.println("----------------");

        result = (x + 2) * 3 > y;
        System.out.println(result); // true
        System.out.println("----------------");
    }
}

 

 

산술변환

 

연산 전에 피연산자의 타입을 일치시키는 것
두 피연산자의 타입을 같게 일치시킨다. (둘중에 저장공간 크기가 더 큰 타입으로 일치)

피연산자의 타입이 int 보다 작은 short 타입이면 int 로 변환
피연산자의 타입이 long 보다 작은 int , short 타입이면 Long 으로 변환
피연산자의 타입이 float 보다 작은 long , int , short 타입이면 float 으로 변환
피연산자의 타입이 double 보다 작은 float , long , int , short 타입이면 double 으로 변환

package week02;

public class W09 {
    public static void main(String[] args) {
        short x = 10;
        int y = 20;

        int z = x + y;

        long lx = 30L;
        long lz = z +lx;

        float fx = x;
        float fy = y;
        float fz = z;

        System.out.println(lz);
        System.out.println(fx);
        System.out.println(fy);
        System.out.println(fz);
    }
}

 

 

비트연산

 

 Bit의 자리수를 옮기는 것

<< (왼쪽으로 자리수 옮기기), >> (오른쪽으로 자리수 옮기기)

 

0,1 은 2진수 값이기 때문에,
자리수를 왼쪽으로 옮기는 횟수만큼 2의 배수로 곱셈이 연산되는 것과 동일
자리수를 오른쪽으로 옮기는 횟수만큼 2의 배수로 나눗셈이 연산되는 것과 동일

package week02;

public class W10 {
    public static void main(String[] args) {
        System.out.println(3 << 2); //12
        // 3의 이진수값은 11(2), 12의 이진수값은 1100(2)
        // (2) 표기는 이 숫자가 이진수값이라는 표식
        // 3의 이진수값인 11(2) 에서 왼쪽으로 2번 옮겨져서 1100(2) 인 12값이 됨
        System.out.println(3 << 1); //6
        // 3의 이진수값인 11(2) 에서 오른쪽으로 1번 옮겨져서 1(2) 인 1 값이 됨
    }
}

 

 

조건문

package week02;

public class W11 {
    public static void main(String[] args) {
        boolean flag = true;

        if(flag) {
            // true인 경우
            System.out.println("값이 true입니다."); // 값이 true입니다.
        }
    }
}
package week02;

public class W11 {
    public static void main(String[] args) {
        boolean flag = false;

        if(flag) {
            // true인 경우
            System.out.println("값이 true입니다.");
        }else{
            // false인 경우
            System.out.println("값이 false입니다."); // 값이 false입니다.
        }
    }
}

 

 

if문

package week02;

public class W11 {
    public static void main(String[] args) {
        boolean flag = false;

//        if(flag) {
//            // true인 경우
//            System.out.println("값이 true입니다.");
//        }else{
//            // false인 경우
//            System.out.println("값이 false입니다."); // 값이 false입니다.
//        }

        // 조건문
        int number = 999;

        if(number == 1){
            System.out.println("number값은 1입니다.");
        }else if(number == 2){
            System.out.println("number값은 2입니다.");
        }else{
            System.out.println("number값은 모르는 값입니다.");
        }
    }
}

 

 

중첩 if

package week02;

public class W12 {
    public static void main(String[] args) {
        // 중첩 if문
        boolean flag = true;
        int number = 2;

        if(flag){
            if(number == 1){
                System.out.println("flag값은 true고, number값은 1입니다.");
            }else if(number == 2){
                System.out.println("flag값은 true고, number값은 2입니다.");
            }else{
                System.out.println("flag값은 true고, number값은 모르겠습니다.");
            }
        }else{
            if(number == 1){
                System.out.println("flag값은 flase고, number값은 1입니다.");
            }else if(number == 2){
                System.out.println("flag값은 flase고, number값은 2입니다.");
            }else{
                System.out.println("flag값은 flase고, number값은 모르겠습니다.");
            }
        }
    }
}

 

 

조건문으로 가위바위보 만들기

package week02;

import java.util.Objects;
import java.util.Scanner;

public class W13 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // A에게 값 입력받기
        System.out.println("A 입력 : ");
        String aHand = sc.nextLine();

        // B에게 값 입력받기
        System.out.println("B 입력 : ");
        String bHand = sc.nextLine();

        // 두 개의 값을 비교하는 메서드 -> Object.equals(좌, 우) : 좌우가 같은 경우 true, 다른 경우 false
        if(Objects.equals(aHand, "가위")){
            if(Objects.equals(bHand, "가위")){
                System.out.println("A와 B는 비겼습니다.");
            }else if(Objects.equals(bHand, "바위")){
                System.out.println("B가 이겼습니다.");
            }else if(Objects.equals(bHand, "보")){
                System.out.println("A가 이겼습니다.");
            }else{
                System.out.println("B가 이상한 값을 입력했습니다.");
            }
        }else if(Objects.equals(aHand, "바위")){
            if(Objects.equals(bHand, "가위")){
                System.out.println("A가 이겼습니다.");
            }else if(Objects.equals(bHand, "바위")){
                System.out.println("A와 B는 비겼습니다.");
            }else if(Objects.equals(bHand, "보")){
                System.out.println("B가 이겼습니다.");
            }else{
                System.out.println("B가 이상한 값을 입력했습니다.");
            }
        }else if(Objects.equals(aHand, "보")){
            if(Objects.equals(bHand, "가위")){
                System.out.println("B가 이겼습니다.");
            }else if(Objects.equals(bHand, "바위")){
                System.out.println("A가 이겼습니다.");
            }else if(Objects.equals(bHand, "보")){
                System.out.println("A와 B는 비겼습니다.");
            }else{
                System.out.println("B가 이상한 값을 입력했습니다.");
            }
        }else{
            System.out.println("A가 이상한 값을 입력했습니다.");
        }
    }
}
A 입력 : 
바위
B 입력 : 
보자기
B가 이상한 값을 입력했습니다.

 

 

switch(피연산자) / case(조건)

 

switch문은 case문과 함께 사용하며 if문 보다 좀더 가독성이 좋은 조건문 표현식

switch(피연산자) { case(조건): (연산) } 형태

switch 피연산자 가 case 조건 을 만족하면 case: 뒤에 명시되어 있는 연산을 수행한다.

case의 연산문 마지막에는 break; 를 꼭 넣어줘야 한다!

switch문 중괄호 안의 제일 마지막에 default: (연산) 을 명시해주어 case 조건 들이 모두 만족하지 않을때 수행할 연
산을 정해주어야 한다. 아무것도 만족하지 않을때 수행하는 것이라, 없다면 생략해도 됨.

package week02;

public class W14 {
    public static void main(String[] args) {
        int month = 8;
        String monthString = "";

        // switch문
        switch (month){
            // case~~~ 연산
            case 1:
                monthString = "1월";
                break;
            case 2:
                monthString = "2월";
                break;
            case 3:
                monthString = "3월";
                break;
            case 4:
                monthString = "4월";
                break;
            case 5:
                monthString = "5월";
                break;
            case 6:
                monthString = "6월";
                break;
            case 7:
                monthString = "7월";
                break;
            case 8:
                monthString = "8월";
                break;
            case 9:
                monthString = "9월";
                break;
            case 10:
                monthString = "10월";
                break;
            case 11:
                monthString = "11월";
                break;
            case 12:
                monthString = "12월";
                break;
            default:
                monthString = "알 수 없음";
        }
        System.out.println(monthString);
    }
}

 

 

for문

package week02;

public class W15 {
    public static void main(String[] args) {
        // for문
        // (초기값 ; 조건문 ; 증가연산)
        for ( int i=0; i <  4 ; i++ ) {
            System.out.println(i + " 번째 출력!");
        }
    }
}
더보기

0 번째 출력!
1 번째 출력!
2 번째 출력!
3 번째 출력!

 

향상된 for문

package week02;

public class W15 {
    public static void main(String[] args) {
        // 향상된 for문
        // 기존 : for문 안에 3개의 조건이 들어감 -> (초기값 ; 조건문 ; 증가연산)
        // 향상된 for문 : 2개로 줄여줌
        int[] numbers = {3, 6, 9, 12, 15};
        for (int number: numbers){
            System.out.println(number + " ");
        }
    }
}
3
6
9
12
15

기존 for문으로 구현

int[] numbers = {3,6,9,12,15};
for(int i = 0; i < numbers.length; i++) {
	System.out.println(numbers[i]);
}
3 6 9 12 15

 

배열에 .length 를 붙이면 길이값이 응답됨

 

 

while 문, do-while 문

 

while문

package week02;

public class W16 {
    public static void main(String[] args) {
        int number = 0;
        while (number < 3) { // number < 3인 동안~~
            number++;
            System.out.println(number + "출력!");
        }
    }
}
1출력!
2출력!
3출력!

 

do-while문

int number = 4;
do{
   // 이 로직을 먼저 수행하겠다!
   System.out.println(number + " 출력!");
}while(number < 3);
4출력!

 

 

break 명령

 

가장 가까운 블록의 for문 또는 while, whitch문을 중단

int number = 0;
while (number < 3) {
	number++;
	if ( number == 2) {
        break;
    }
    System.out.println(number + " 출력!");
}
 
1 출력!

 

 

break 명령 범위

for (int i=0; i<10; i++){
    System.out.println("i: " + i);
    if (i == 2) {
        break; // i가 2일 때, 가장 바깥 반복문이 종료
    }
    for (int j=0; j < 10 ; j++) {
        System.out.println("j: " + j);
        if(j == 2) {
            break; // j가 2일 때, 안쪽 반복문이 종료
        }
    }
}
i: 0 // 바깥 반복문 부터 수행 시작
j: 0 // 안쪽 반복문 1회차 수행
j: 1
j: 2 // j 가 2일때 안쪽 반복문 break;
i: 1 // 바깥 반복문은 아직 break; 호출이 안됬으므로 다음 반복수행
j: 0 // 안쪽 반복문 2회차 수행
j: 1
j: 2 // j 가 2일때 안쪽 반복문 두번째 break;
i: 2 // i 가 2일때 바깥 반복문도 break; 호출되어 종료

 

 

continue 명령

int number = 0;
while ( number < 3 ) {
    number++;
    if( number == 2 ){
        continue;
    }
    System.out.println(number + " 출력!");
}
1 출력!
3 출력!

 

 

구구단 생성기

for (int i = 2; i <= 9; i++) { // 구구단 첫번째 수 i
	for (int j = 2; j <= 9; j++) { // 구구단 두번째 수 j
		System.out.println(i + "곱하기 " + j + "는 " + (i * j) + "입니다.");
}

 

선택적 구구단 생성기

package week02;

import java.util.Scanner;

public class W17 {
    public static void main(String[] args) {
        // 입력받는 단을 제외하고 출력
        Scanner sc= new Scanner(System.in);
        int passNum=sc.nextInt(); // 출력을 제외할 구구단수 값

        // 구구단
        for(int i=2; i <= 9; i++){ // 구구단의 첫 번째 수
            if( i == passNum){
                continue;
            }
            for (int j=2; j <= 9; j++){ // 구구단의 두 번째 수
                System.out.println(i + "곱하기 " + j +"는 " + (i*j) + "입니다.");
            }
        }
    }
}
// 2 입력
3곱하기 2는 6입니다.
.
.
.
9곱하기 9는 81입니다.

 

 

배열

 

여러개의 변수를 분류통 같은 곳에 모아서 저장하고 싶을 때 기본적으로는 “배열”이라는 변수에 저장(표현)

한번에 많은 양의 데이터를 다루거나 계산할때 사용, Array

 

선언 방법

 

타입[] 변수; 

int[] intArray; // 정수 배열
long[] longArray;
double[] doubleArray; // 실수 배열
char[] charArray; // 문자 배열
String[] stringArray; // 문자열 배열


타입 변수[]; 

int intArray[]; // 정수 배열
long longArray[];
double doubleArray[]; // 실수 배열
char charArray[]; // 문자 배열
String stringArray[]; // 문자열 배열

 

배열 변수를 선언한다고 해서 아직 사용할 수 있는 배열이 만들어진 것은 아님

 

생성 ( new  [] )

 

배열을 사용하려면 배열을 생성해야 한다.

배열은 참조형 변수들처럼 new 명령을 통해서 생성하며, 대괄호 [] 안에 크기를 지정

 

 

new int[8]라고 하면 총 8개의 int형 변수가 만들어진다.

배열은 생성될때 각 타입별 초기값으로 초기화된다.

=> 숫자는 0, boolean은 false, String은 null(없다는 뜻)

 

생성, 순회

package week02.array;

public class Arr01 {
    public static void main(String[] args) {
        // 배열 생성
        int[] intArray = new int[3]; //{0, 0, 0}
        boolean[] boolArray = new boolean[3]; // {false, false, false}
        String[] stringArray = new String[3]; // {"", "", ""}

        // 배열 선언 먼저 -> 나중에 초기화
        int[] intArray2;
        intArray2 = new int[3]; // {0, 0, 0}

        // 생성한 배열을 '순회' -> 배열의 값을 하나씩 뽑아서 조회
        // (1) 단건 조회
        System.out.println(intArray[1]);
        System.out.println("---------------");

        // (2) 다건 조회(중요!)
        // length : 길이를 구하는 메서드
        for(int i=0; i<intArray2.length; i++){
            System.out.println(intArray2[i]);
        }

    }
}

 

package week02.array;

public class Arr02 {
    public static void main(String[] args) {
        // 초기화

        // 1. 배열의 특정값 대입해서 선언
        int[] intArr = {1, 2, 3, 4, 5};
        String[] stringArray = {"a", "b", "c", "d"};

        // 2. for문을 통해서 대입
        for(int i=0;i<intArr.length; i++){
            intArr[i] = i;
        }
        System.out.println("---------------");

        // 다건출력
        for(int i=0; i<intArr.length; i++){
            System.out.println(intArr[i]);
        }
    }
}

 

 

향상된 for문을 통한 배열 출력

int[] intArr = {10, 20, 30, 40, 50};

for(int item: intArr){
    System.out.println(item);
}
10
20
30
40
50

 

 

배열의 주소를 모두 같은 값으로 초기화

int[] intArr = {10, 20, 30, 40, 50};
Arrays.fill(intArr, 1);

for(int item: intArr){
    System.out.println(item);
}
1
1
1
1
1

 

 

복사

 

얕은 복사

int[] a = { 1, 2, 3, 4 };
int[] b = a; // 얕은 복사

b[0] = 3; // b 배열의 0번째 순번값을 3으로 수정 (1 -> 3)

System.out.println(a[0]); // 출력 3 <- a 배열의 0번째 순번값도 3으로 조회된다.

 

깊은 복사

int[] a = { 1, 2, 3, 4 };
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
    b[i] = a[i]; // 깊은 복사
}
b[0] = 3; // b 배열의 0번째 순번값을 3으로 수정 (1 -> 3)
System.out.println(a[0]); // 출력 1 <- 깊은 복사를 했기때문에 a 배열은 그대로
// 2. Arrays.copyOf() 메서드
int[] a = { 1, 2, 3, 4 };
int[] b = Arrays.copyOf(a, a.length); // 배열과 함께 length값도 같이 넣어줌

a[3] = 0;
System.out.println(a[3]); // 0
System.out.println(b[3]); // 4

 

 

String 기능 활용(= char 배열)

package week02.array;

public class Arr05 {
    public static void main(String[] args) {
        // 문자(char / 1byte), 문자열(String)
        // String = char[]

        // 기본형 변수 vs 참조형 변수
        // 1. 기본형 변수는 '소문자로 시작함' 반면, 참조형 변수는 '대문자로 시작함'
        //   - Wrapper class에서 기본형 변수를 감싸줄 때(boxing), int -> Integer
        // 2. 기본형 변수는 값 자체를 저장, 참조형 변수는 별도의 공간에 값을 저장 후 그 주소를 저장함(= 주소형 변수)

        // char < String(훨씬 더!)
        // String이 가지고 있는 기능이 너무 많아서..!!
        // Wrapper class와도 상당히 비슷..! -> 기본형 변수가 가지고 있는 기능이 제한 -> 다양한 기능을 제공하는 Wrapper를 감쌈으로써, 추가기능을 더함

        // String 기능 활용 예시
        String str = "ABCD";

        // (1) length
        int strLength = str.length();
        System.out.println(strLength); // 4

        // (2) charAt(int index)
        char strChar = str.charAt(1);
        System.out.println(strChar); // B

        // (3) substring(int fromIdx, int toIdx)
        String strSub = str.substring(0,3); // 0번째부터 3번째 전까지
        System.out.println(strSub); // ABC

        // (4) equals(String str)
        String newStr = "ABCD";
        boolean strEqual = newStr.equals(str);
        System.out.println(strEqual); // true

        // (5) toCharArray() : String -> char[]
        char[] srtCharArray = str.toCharArray();

        // (6) 반대로 char[] -> String
        char[] charArray = {'A', 'B', 'C'};
        String charArrayString = new String(charArray);
        System.out.println(charArrayString); // ABC
    }
}

 

반복문을 통한 초기화

int[][] array = new int[2][3]; // 최초 선언

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
        System.out.println("출력값 => " + i +", " + j);
        array[i][j] = 0; // i, j 인덱스
    }
}

 

 

가변배열

int [][] array = new int[3][];

// 배열 원소마다 각기 다른 크기로 지정
array[0] = new int[2];
array[1] = new int[4];
array[2] = new int[1];

// 중괄호로 초기화를 아예 해버릴 때도 원소배열들의 크기를 각기 다르게 생성 가능
int[][] array2 = {
        {10, 20},
        {10, 20, 30, 40},
        {10}
};

 

 

최대값 구하기

int[] arr = {3, 2, 1, 5, 1};

// 최대값 초기화 세팅
int max = arr[0];

// 최대값 구하기 로직
for(int num: arr){
    if(num > max){
        max = num;
    }
}
System.out.println("최대값은 => " + max); // 최대값은 => 5

 

 

최소값 구하기

int[] arr = {3, 2, 0, 5, 1};

// 최소값 초기화 세팅
int min = arr[0];

// 최소값 구하기 로직
for(int num: arr){
    if(num < min){
        min = num;
    }
}
System.out.println("최소값은 => " + min); // 최소값은 => 0

 

 

컬렉션

Java 프로그래밍 에서는 배열을 더 고도화 시켜서 컬렉션이라는 이름으로 참조형 분류통(자료구조)를 제공한다.

배열보다 다수의 참조형 데이터를 더 쉽고 효과적으로 처리할 수 있는 기능이 많음

크기 자동조정/ 추가/ 수정/ 삭제/ 반복/ 순회/ 필터/ 포함확인 등….

 

 

컬렉션의 종류

 

List : 순서가 있는 데이터의 집합 (데이터 중복 허용) - 배열과 비슷
Queue : 빨대처럼 한쪽에서 데이터를 넣고 반대쪽에서 데이터를 뺄 수 있는 집합.

              FIFO(First In First Out : 먼저들어간 순서대로 값을 조회) 구조
Set : 순서가 없는 데이터의 집합 (데이터 중복 허용 안함) - 순서없고 중복없는 배열
Map : 순서가 없는 (Key,Value) 쌍으로 이루어진 데이터의 집합 (Key값 중복 허용 안함)

 

기본형 변수가 아닌 참조형 변수를 저장

 

int 의 참조형 변수 = Integer
long 의 참조형 변수 = Long
double 의 참조형 변수 = Double
String 은 원래부터 참조형 변수

 

 

 

리스트

package week02.collection;

import java.util.ArrayList;

public class Col1 {
    public static void main(String[] args) {
        // List
        // 순서가 있는 데이터의 집합 => Array(최초 길이를 알아야 함)
        // 처음에 길이를 몰라도 만들 수 있음
        // 1) Array -> 정적배열
        // 2) List(ArrayList) -> 동적배열(크기가 가변적으로 늘어난다)
        //    - 생성 시점에 작은 연속된 공간을 요청해서 참조형 변수들을 담아놓는다.
        //    - 값이 추가될 때 더 큰 공간이 필요하면 더 큰 공간을 받아서 저장하니까 상관없다.

        ArrayList<Integer> intList = new ArrayList<Integer>(); // 선언+생성

        intList.add(99);
        intList.add(15);
        intList.add(3);

        System.out.println(intList.get(0)); // 99
        System.out.println(intList.get(2)); // 3

        System.out.println(intList.get(1)); // 15

        // 2번째 있는 값(15)를 바꿔보자
        intList.set(1, 10);
        System.out.println(intList.get(1)); // 10
    }
}

 

삭제

        ArrayList<Integer> intList = new ArrayList<Integer>(); // 선언+생성

        intList.add(99);
        intList.add(15);
        intList.add(3);

        System.out.println(intList.get(0)); //99
        
        // 삭제
        intList.remove(0);
        System.out.println(intList.get(0)); //15

 

Linked list

package week02.collection;

import java.util.LinkedList;

public class Col2 {
    public static void main(String[] args) {
        // Linked list
        // 메모리에 남는 공간을 요청해서 여기저기 나누어서 실제 값을 담아놓는다.
        // 실제 값이 있는 주소값으로 목록을 구성하고 저장하는 자료구조

        // 기본적 기능은 -> ArrayList와 동일
        // LinkedList는 값 -> 여기저기 나누어서 : 조회하는 속도가 "느리다.."
        // 값을 추가하거나, 삭제할 때는 빠르다.

        LinkedList<Integer> linkedList = new LinkedList<Integer>();

        linkedList.add(5);
        linkedList.add(10);
        linkedList.add(3);

        System.out.println(linkedList.get(0));
        System.out.println(linkedList.get(1));
        System.out.println(linkedList.get(2));

        System.out.println(linkedList.toString()); // 이렇듯 조회할 때는 arrayList보다 속도가 현저히 느리다.

        linkedList.add(200);
        System.out.println(linkedList.toString());

        linkedList.add(2, 4);
        System.out.println(linkedList.toString());

        linkedList.set(1, 30);
        System.out.println(linkedList.toString());

        linkedList.remove(1);
        System.out.println(linkedList.toString());

        linkedList.clear();
        System.out.println(linkedList.toString());
    }
}

 

 

Stack

package week02.collection;

import java.util.Stack;

public class Col3 {
    // Stack
    // 수직으로 값을 쌓아놓고, 넣었다가 뺀다. FILO(Basket)
    // push, peek, pop
    // 최근 저장된 데이터를 나열하고 싶거나, 데이터의 중복 처리를 막고 싶을 때 사용
    public static void main(String[] args) {
        Stack<Integer> intStack = new Stack<Integer>(); // 선언 및 생성

        intStack.push(10);
        intStack.push(15);
        intStack.push(1);

        // 다 지워질 때 까지 출력
        while(!intStack.isEmpty()){
            System.out.println(intStack.pop()); // 1 15 10
        }

        // 다시 츠가
        intStack.push(10);
        intStack.push(15);
        intStack.push(1);

        // peak
        System.out.println(intStack.peek()); // 1
        System.out.println(intStack.size()); // 3
    }
}

 

 

Queue

package week02.collection;

import java.util.LinkedList;
import java.util.Queue;

public class Col4 {
    public static void main(String[] args) {
        // Queue : FIFO
        // add, peek, poll
        // Queue : 생성자가 없는 인터페이스

        Queue<Integer> intQueue = new LinkedList<>(); // queue를 선언, 생성

        intQueue.add(1);
        intQueue.add(5);
        intQueue.add(9);

        while(!intQueue.isEmpty()){
            System.out.println(intQueue.poll()); // 1 5 9
        }

        // 추가
        intQueue.add(1);
        intQueue.add(5);
        intQueue.add(9);
        intQueue.add(10);

        //peak
        System.out.println(intQueue.peek()); // 1
        System.out.println(intQueue.size()); // 4
    }
}

 

 

Set

package week02.collection;

import java.util.HashSet;
import java.util.Set;

public class Col5 {
    public static void main(String[] args) {
        // [Set(집합) : 순서 없고, 중복 없음!]
        // 순서가 보장되지 않는 대신 중복을 허용하지 않도록 하는 프로그램에서 사용할 수 있는 자료구조
        // Set -> 그냥 쓸 수도 있음. 그러나 HashSet, TreeSet 등으로 응용해서 같이 사용 가능
        // Set은 생성자가 없는 껍데기라서 바로 생성할 수 없음!
        // 생성자가 존재하는 HashSet을 이용해서 -> Set을 구현해 볼 수 있다!

        Set<Integer> intSet = new HashSet<>(); // 선언 및 생성

        intSet.add(1);
        intSet.add(12);
        intSet.add(5);
        intSet.add(9);
        intSet.add(1);
        intSet.add(12);

        for(Integer value: intSet){
            System.out.println(value); // 1 5 9 12
        }

        // contains
        System.out.println(intSet.contains(2)); // false
        System.out.println(intSet.contains(5)); // true
    }
}

 

Map

'TIL' 카테고리의 다른 글

TIL 241014  (0) 2024.10.14
TIL 241011  (0) 2024.10.11
TIL 241008  (0) 2024.10.08
TIL 241007  (0) 2024.10.07
TIL 241005  (0) 2024.10.05