Post

내일배움캠프 사전캠프 JAVA 핵심 기본 개념

🚀 Java 기본 구조

1
2
3
4
5
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}
  • class: 클래스(설계도)
  • main(): 프로그램의 시작점 (자바는 반드시 main() 에서 시작)
  • System.out.println(): 콘솔에 출력

🚀 변수와 자료형

1
2
3
4
5
int age = 20;           // 정수
double height = 175.5;  // 실수
char gender = 'M';      // 문자 하나
boolean isAdult = true; // 참/거짓
String name = "홍길동";    // 문자열

🚀 참조 vs 기본 자료형

1
2
int a = 10;           // 기본형 (primitive)
String name = "홍길동"; // 참조형 (reference)
  • 기본형: int, double, boolean 등 → 값 자체를 저장
  • 참조형: String, Array, Scanner, 사용자 정의 클래스 등 → 객체를 가리키는 주소 저장

자바에서 모든 객체는 참조형이라는 걸 기억!

🚀 조건문

1
2
3
4
5
if (age >= 20) {
    System.out.println("성인입니다.");
} else {
    System.out.println("미성년자입니다.");
}

🚀 반복문

1
2
3
4
5
6
7
8
9
for (int i = 1; i <= 5; i++) {
    System.out.println("i: " + i);
}

int j = 0;
while (j < 3) {
    System.out.println("j: " + j);
    j++;
}

🚀 배열

1
2
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]);  // 1 출력

🚀 컬렉션

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.*;

public class CollectionExample {
    public static void main(String[] args) {
        // List
        List<String> fruits = new ArrayList<>();
        fruits.add("사과");
        fruits.add("바나나");

        for (String f : fruits) {
            System.out.println("과일: " + f);
        }

        // Map
        Map<String, Integer> scores = new HashMap<>();
        scores.put("길동", 90);
        scores.put("민수", 85);

        System.out.println("길동의 점수: " + scores.get("길동"));
    }
}
  • List: 순서 있는 데이터
  • Set: 중복 허용 안함
  • Map: 키-값 쌍 저장

배열보다 훨씬 유연하고 자주 씀

🚀 클래스와 객체

1
2
3
4
5
6
7
8
9
10
11
12
public class Person {
    String name;
    int age;

    public void sayHello() {
        System.out.println("안녕하세요, 저는 " + name + "입니다.");
    }
}

Person p = new Person();
p.name = "홍길동";
p.sayHello();

🚀 static

1
2
3
4
5
6
7
class MathUtil {
    public static int square(int n) {
        return n * n;
    }
}

MathUtil.square(5); // 객체 없이도 호출 가능!
  • static: 클래스에 귀속 → 객체 없이도 사용 가능

🚀 생성자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Person {
    String name; // 멤버 변수

    public Person(String name) { // 매개 변수
        this.name = name; // 멤버 변수와 매개 변수를 구분
    }

    public void greet() {
        System.out.println("안녕하세요, 저는 " + name + "입니다.");
    }

    public static void main(String[] args) {
        Person p = new Person("홍길동");
        p.greet();
    }
}

  • 생성자(Constructor)는 객체를 만들 때 자동으로 호출됨

🚀 접근 제어자

  • public: 어디서든 접근 가능
  • private: 클래스 내부에서만 접근 가능
  • protected: 같은 패키지 + 상속받은 클래스에서 접근 가능
  • 아무것도 안 쓰면(default): 같은 패키지에서만 접근 가능

🚀 캡슐화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BankAccount {
    private int balance = 0;

    public void deposit(int amount) {
        if (amount > 0) balance += amount;
    }

    public int getBalance() {
        return balance;
    }

    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.deposit(1000);
        System.out.println("잔액: " + acc.getBalance());
    }
}

  • private: 외부에서 직접 접근 못하게 막음
  • public: 메서드를 통해 간접적으로 조작 (캡슐화)

🚀 상속

1
2
3
4
5
6
7
8
9
10
11
class Animal {
    void sound() {
        System.out.println("동물 소리");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("멍멍");
    }
}
  • extends: 상속받을 때 사용
  • 다형성: 같은 메서드 이름이어도 객체에 따라 동작 다르게 가능

🚀 인터페이스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface Drawable {
    void draw();
}

class Circle implements Drawable {
    public void draw() {
        System.out.println("원을 그립니다.");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        Drawable d = new Circle();
        d.draw(); // 원을 그립니다.
    }
}
  • 인터페이스는 기능만 정의 (구현은 클래스가 함)
  • implements: 인터페이스 구현

다형성과 연결됨. 자바에서 유지보수, 확장성에 매우 중요

🚀 예외 처리

1
2
3
4
5
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("0으로 나눌 수 없습니다.");
}
  • 다양한 예외 종류

    예외 클래스설명
    ArithmeticException0으로 나누기 등 수학 오류
    NullPointerExceptionnull 값 사용 시
    ArrayIndexOutOfBoundsException배열 인덱스 범위 초과
    NumberFormatException숫자 변환 실패