<aside> <img src="https://prod-files-secure.s3.us-west-2.amazonaws.com/83c75a39-3aba-4ba4-a792-7aefe4b07895/94dbaed9-349c-449d-bc43-25de3ae5a780/SpartaIconScale9.png" alt="https://prod-files-secure.s3.us-west-2.amazonaws.com/83c75a39-3aba-4ba4-a792-7aefe4b07895/94dbaed9-349c-449d-bc43-25de3ae5a780/SpartaIconScale9.png" width="40px" /> 수업 목표
Optional 을 사용하는 이유와 개념을 학습합니다.
</aside><aside> <img src="https://prod-files-secure.s3.us-west-2.amazonaws.com/83c75a39-3aba-4ba4-a792-7aefe4b07895/393cd135-1603-4797-8fa6-42abcfedd782/SpartaIconS24.png" alt="https://prod-files-secure.s3.us-west-2.amazonaws.com/83c75a39-3aba-4ba4-a792-7aefe4b07895/393cd135-1603-4797-8fa6-42abcfedd782/SpartaIconS24.png" width="40px" />
목차
</aside>
<aside> <img src="https://prod-files-secure.s3.us-west-2.amazonaws.com/83c75a39-3aba-4ba4-a792-7aefe4b07895/11965e36-5cde-4d10-b470-06dfbe247327/scc캐릭터_아하_280x280.png" alt="https://prod-files-secure.s3.us-west-2.amazonaws.com/83c75a39-3aba-4ba4-a792-7aefe4b07895/11965e36-5cde-4d10-b470-06dfbe247327/scc캐릭터_아하_280x280.png" width="40px" /> 필수 프로그램 설치
프로그램 설치가이드를 따라 천천히 설치를 진행해주세요.
✅ OpenJDK 8버전 이상
✅ IntelliJ (Community)
✅ Google Chrome
</aside>
<aside> 📚
Optional 이 무엇인지 학습해 봅시다.
Optional 객체는 null 을 안전하게 다루게 해주는 객체입니다.
<aside> 💡
null 이란?
null은 프로그래밍에서 값이 없음 또는 참조하지 않음 을 나타내는 키워드null 을 직접 다루는 대신 Optional 을 사용하면 NullPointerException 을 방지할 수 있습니다.
</aside>
<aside> 📚
Optional 이 왜 필요한지 Student 와 Camp 예시를 통해 학습해 봅시다.
camp.getStudent() 는 null 을 반환할 수 있는 메서드입니다.null을 반환하면 NPE(NullPointerException)가 발생합니다.null인 객체에서 student.getName()을 호출하는 것은 존재하지 않는 객체의 메서드를 실행하려는 것입니다.<aside> ⚠️
NullPointerException 을 방지해야 하는 이유
NPE 예외는 런타임 예외이고 컴파일러가 잡아주지 못합니다.public class Student {
// 속성
private String name;
// 생성자
// 기능
public String getName() {
return this.name;
}
}
public class Camp {
// 속성
private Student student;
// 생성자
// 기능: ⚠️ null 을 반환할 수 있는 메서드
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
public class Main {
public static void main(String[] args) {
Camp camp = new Camp();
Student student = camp.getStudent(); // ⚠️ student 에는 null 이 담김
// ⚠️ 아래 코드에서 NPE 발생! 컴파일러가 잡아주지 않음
**String studentName = student.getName(); // 🔥** NPE 발생 -> 프로그램 종료
**** System.out.println("studentName = " + studentName);
}
}
</aside>
<aside> 📚
NULL을 직접 처리할 때의 한계에 대해 학습해 봅시다.
if문을 활용해서 null 처리를 할 수 있지만 모든 코드에서 null 이 발생할 가능성을 미리 예측하고 처리하는 것은 현실적으로 어렵습니다.public class Main {
public static void main(String[] args) {
Camp camp = new Camp();
Student student = camp.getStudent();
String studentName;
if (student != null) { // ⚠️ 가능은하지만 현실적으로 어려움
studentName = student.getName();
} else {
studentName = "등록된 학생 없음"; // 기본값 제공
}
System.out.println("studentName = " + studentName);
}
}
</aside>