Java

[2024-2 Java 스터디] #2주차

디지몬진화 2024. 10. 15. 18:26
 

[2024-2 Java 스터디] #1주차

01. 자바란 무엇인가?01-1 자바란?- 객체 지향 프로그래밍 언어- 웹과 모바일 앱 개발에서 가장 많이 사용하는 언어 01-2 자바로 무엇을 할 수 있을까?- 웹 프로그래밍- 안드로이드 애플리케이션 개

taei1.tistory.com

※앞 내용은 위 티스토리를 참고!


03-8 맵

- 키와 값을 한 쌍으로 갖는 자료형

 

1.맵 자료형 중 하나인 HashMap의 메서드, 예제코드 살펴보기

import java.util.HashMap; //HashMap클래스가 있는 자바 패키지 불러오기
메서드 설명 예제 코드
put key와 value 추가 HashMap<String, String> map = new HashMap<>();
map.put(
"people", "사람");
map.put(
"baseball", "야구");
get key에 해당하는 value 추출
(key에 해당하는 value가 없다면 null 리턴)
HashMap<String, String> map = new HashMap<>();
map.put(
"people", "사람");
map.put(
"baseball", "야구");
System.out.println(map.get("people")); // "사람" 출력
getOrDefault key에 해당하는 value가 있을때는 value 추출, 있다면 기본값 추출 System.out.println(map.getOrDefault("java", "자바"));
// java에 대한 value가 없을때 자바 출력
containsKey 맵에 해당 key가 있는지를 참, 거짓으로 리턴 HashMap<String, String> map = new HashMap<>();
map.put(
"people", "사람");
map.put(
"baseball", "야구");
System.out.println(map.containsKey(
"people")); // true 출력
remove 해당 key의 항목을 삭제한 후 value 값 리턴 HashMap<String, String> map = new HashMap<>();
map.put(
"people", "사람");
map.put(
"baseball", "야구");
System.out.println(map.remove(
"people")); // "사람" 출력
size 맵 요소의 개수 리턴 HashMap<String, String> map = new HashMap<>();
map.put(
"people", "사람");
map.put(
"baseball", "야구");
System.out.println(map.size()); // 2출력
keySet 맵의 모든 key를 모아서 리턴 HashMap<String, String> map = new HashMap<>();
map.put(
"people", "사람");
map.put(
"baseball", "야구");
System.out.println(map.keySet()); // [baseball, people] 출력

 

03-9 집합

- 집합과 관련된 것을 쉽게 처리하기 위해 만듦

 

1. 집합 자료형 중 가장 많이 사용하는 HashSet (기본 예제 코드)

import java.util.Arrays;  // 배열을 만들기 위해 Arrays 클래스 불러오기
import java.util HashSet; // HashSet 클래스 불러오기
HashSet<String> set = new HashSet<>(Arrays.asList("H", "e", "l", "l", "o"));
System.out.println(set); // [e, H, l, o] 출력

 

 

2. 집합 자료형의 특징

  • 중복을 허용하지 않음
  • 순서가 없음 --> 인덱싱 지원 X

 

3. 교집합, 합집합, 차집합 구하기 + 이 외의 메서드

메서드 (집합 종류) 설명 예제 코드
intersection (교집합)

HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 =
new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
HashSet<Integer> intersection =
new HashSet<>(s1); // s1으로 intersection 생성
union.retainAll(s2); // 교집합 수행
System.out.println(intersection);
// [4, 5, 6] 출력
addAll (합집합)
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 = 
new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
HashSet<Integer> union = 
new HashSet<>(s1); // s1으로 union 생성
union.addAll(s2); // 합집합 수행
System.out.println(union); 
// [1, 2, 3, 4, 5, 6, 7, 8, 9] 출력
removeAll (차집합)
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 =
new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
HashSet<Integer> substract =
new HashSet<>(s1);// s1으로 substract 생성 substract.removeAll(s2); // 차집합 수행
System.out.println(substract);
// [1, 2, 3] 출력
add 집합에 값을 추가할 때 사용 HashSet<String> set = new HashSet<>();
set.add(
"Jump");
set.add(
"To");
set.add(
"Java");
System.out.println(set);
// [Java, To, Jump] 출력
remove 특정 값을 제거할 때 사용 HashSet<String> set = new HashSet<>(Arrays.asList("Jump", "To", "Java"));
set.remove(
"To");
System.out.println(set);
// [Java, Jump] 출력

 

 

03-10 상수 집합

- enum 자료형 : 서로 연관 있는 여러 개의 상수 집합을 정의할 때 사용

 

1. 예제코드

enum CoffeeType {
	AMERICANO,
    ICE_AMERICANO,
    CAFE_LATTE
};

public static void main(String[] args) {
    System.out.println(CoffeeType.AMERICANO);  // AMERICANO 출력
    System.out.println(CoffeeType.ICE_AMERICANO);  // ICE_AMERICANO 출력
    System.out.println(CoffeeType.CAFE_LATTE);  // CAFE_LATTE 출력
for(CoffeeType type: CoffeeType.values()) {
	System.out.println(type);  //순서대로 AMERICANO, ICE_AMERICANO, CAFE_LATTE 출력

 

2. enum이 필요한 이유

  • 매직 넘버를 사용할 때보다 코드가 명확하다 (의미없는 숫자 대신 명확한 이름을 인수로 사용할 수 있다)
  • 잘못된 값을 사용해 생길 수 있는 오류를 막을 수 있다

 

03-11 형 변환과 final

1. 형 변환

- 자료형을 다른 자료형으로 바꾸는 것

형 변환 방식 변형 코드 예제 코드
문자열 --> 정수 Integer.parseInt String num = "123";
int n = Integer.parseInt(num);   //integer클래스를 사용
System.out.println(n); // 123 출력
정수 --> 문자열 빈문자열("") 더해주기 int n = 123;
String num = "" + n;   //문자열로 변환
System.out.println(n); // 123 출력
String.valueOf(정수) String num1 = String.valueOf(n);
Integer.toString(정수) String num2 = Integer.toString(n);
문자열 --> 실수 Double.parseDouble double d = Double.parseDouble(num);
Float.parseFloat double d = Float.parseFloat(num);
실수 --> 정수 (int) 변수; double d2 = 123.456;
int
n2 = (int) d2;  // 123 출력
정수 --> 실수 캐스팅 필요 X int n1 = 123;
double d1 = n1;

실수 형태 문자열을 정수로 바꿀 때 NumberFormatException이 발생하므로 주의

 

2. final

- 자료형에 값을 단 한 번만 설정할 수 있게 강제하는 키워드

final int n = 123;  // final로 설정하면 값을 바꿀 수 없다.
n = 456;  // 컴파일 오류 발생

 

 

04. 제어문 이해하기

 

04-1 if문

 

1. 기본 구조

if (조건문) {
    <수행할 문장1>;
    <수행할 문장2>;
    ...
} else {
    <수행할 문장A>;
    <수행할 문장B>;
    ...
}

 

2. 예제 코드

boolean money = true;
if (money) {
    System.out.println("택시를 타고 가라");
}else {
    System.out.println("걸어가라");
}

 

3. 비교연산자

x < y x가 y보다 작다
x > y x가 y보다 크다
x == y x와 y가 같다
x != y x와 y가 같지 않다
x >= y x가 y보다 크거나 같다
x <= y x가 y보다 작거나 같다

 

4. and, or, not 연산자

x && y x와 y 모두 참이어야 참이다
x || y x와 y 둘 중 적어도 하나가 참이면 참이다
!x x가 거짓이면 참이다

 

▼ 3,4의 비교연산자와 and, or, not 연산자의 자세한 설명은 아래 자바연산자 티스토리를 통해 확인

 

[Java] 자바 연산자

연산자(operator)- 연산에 사용되는 표시나 기호- 피연산자 : 연산이 되는 데이터종류연산자우선순위증감 연산자++, --1순위산술 연산자+, -, *, /, %2순위시프트 연산자>>, >>3순위비교 연산자>, =, 4순위

taei1.tistory.com

 

04-5. else if

- 판단을 해야할 조건문이 여러개 있을 때 사용

- 개수의 제한 없이 사용 가능

 

1. 기본 구조

if (조건문) {
    <수행할 문장1> 
    <수행할 문장2>
    ...
}else if (조건문) {
    <수행할 문장1>
    <수행할 문장2>
    ...
}else if (조건문) {
    <수행할 문장1>
    <수행할 문장2>
    ...
...
} else {
   <수행할 문장1>
   <수행할 문장2>
   ... 
}

 

 

04-2 switch / case 문

- 일정한 형식이 있는 조건, 판단문

 

1. 기본 구조

switch(입력변수) {
    case 입력값1: ...
         break;
    case 입력값2: ...
         break;
    ...
    default: ...
         break;
}

입력값이 정형화되어 있는 경우 if 문보다는 switch / case 문을 쓰는 것이 가독성이 좋다

 

2. 예제 코드

public class Sample {
    public static void main(String[] args) {
        int month = 8;
        String monthString = "";
        switch (month) {  // 입력 변수의 자료형은 byte, short, char, int, enum, String만 가능하다.
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);  // case8인 August 출력
    }
}

 

 

04-3 while문

 

1. 기본 구조

while (조건문) {
    <수행할 문장1>;
    <수행할 문장2>;
    <수행할 문장3>;
    ...
}

 

2. 무한 루프란?

- 조건문을 항상 참으로 만들어 while문 안의 내용이 무한히 반복되는것

while (true) {    
    <수행할 문장1>;
    <수행할 문장2>;
    ...
}

 

3. while문 빠져나가기 - break

- break : while문을 강제로 멈춰야 할 때 사용

▼아래 코드와 같이 조건문을 통해 조건문이 참이 되면 break를 호출하는 식으로 사용 가능

int coffee = 10;
int money = 300;

while (money > 0) {
    System.out.println("돈을 받았으니 커피를 줍니다.");
    coffee--;
    System.out.println("남은 커피의 양은 " + coffee + "입니다.");
    if (coffee == 0) {
        System.out.println("커피가 다 떨어졌습니다. 판매를 중지합니다.");
        break;
    }
}

 

4. while문으로 돌아가기 - continue

- continue : 조건이 참인 경우 while문으로 돌아가게 함

int a = 0;
while (a < 10) {
    a++;           // a가 10보다 작은 동안 a는 1씩 증가
    if (a % 2 == 0) {
        continue;  // 짝수인 경우 조건문으로 돌아간다.
    }
    System.out.println(a);  // 홀수만 출력된다.
}

 

 

04-4 for문

 

1. 기본 구조

for (초기치; 조건문; 증가치) {
    ...
}

 

2. for문으로 돌아가기 - continue

- continue : 조건문으로 돌아감 (while문에서의 continue와 동일)

int[] marks = {90, 25, 67, 45, 80};
for(int i=0; i<marks.length; i++) {
    if (marks[i] < 60) {
        continue;  // 조건문으로 돌아간다.
    }
    System.out.println((i+1)+"번 학생 축하합니다. 합격입니다.");
}

 

3. 이중 for문

- for문 안에 for문 넣기

for(int i=2; i<10; i++) {
    for(int j=1; j<10; j++) {
        System.out.print(i*j+" ");
    }
    System.out.println("");  // 줄을 바꾸어 출력하는 역할을 한다.
}

 

04-5 for each 문

- 객체를 루프에 돌려 순차적으로 대입

for (type 변수명: iterate) {  // iterate: 루프를 돌릴 객체
    body-of-loop
}

for each 문은 따로 반복 횟수를 명시적으로 주는 것이 불가능, 한 단계씩 순차적으로 반복할 때만 사용이 가능


참고문헌 : https://wikidocs.net/book/31

 

점프 투 자바

이 책은 프로그래머를 꿈꾸며 자바 입문서를 찾는 사람들을 위한 책이다. 이 책은 자바의 문법을 하나하나 자세히 알기 보단 어렵게 느껴지는 자바를 쉽고 재미있게 이해하는 것을 목표…

wikidocs.net