728x90
반응형
프로그래머스 자바 중급 강의를 학습 목적으로 정리하여 포스팅합니다.
1. java.lang 패키지 / 오토박싱
자바는 기본적으로 다양한 패키지를 지원하는데 그 중 가장 중요한 패키지이다.
- java.lang 패키지의 클래스는 import를 하지 않고도 사용할 수 있다
- 기본형 타입을 객체로 변환시킬 때 사용하는 Wrapper 클래스, 모든 클래스의 최상위 클래스인 Object, 문자열과 관련된 String, StringBuffer, StringBuilder 그리고 화면에 값을 출력할 때 사용했던 System 클래스, 수학과 관련된 Math 클래스, Thread와 관련된 중요 클래스 외 다양한 클래스와 인터페이스가 모두 java.lang 패키지
Wrapper 클래스 중 하나인 Integer 예시
public class WrapperExam{
public static void main(String[] args){
int i = 5; // 기본형
Integer i2 = new Integer(5); // 참조형
Integer i3 = 5; // 오토박싱, new Integer(5)
int i4 = i2.intValue();
int i5 = i2; // 오토언박싱
}
}
- 오토박싱(Auto Boxing) : 숫자 5는 원래 기본형이지만 자동으로 Integer 형태로 변환된다.
- 오토 언박싱(Auto unboxing) : Integer 객체 타입의 값을 기본형 int로 자동으로 변환되어 값을 할당한다.
- 오토박싱과 오토언박싱은 JAVA5부터 지원된다. 이 때 내부적으로 Wrapper 클래스들이 사용된다.
2. 스트링버퍼
String 클래스는 자기 자신이 변하지 않는 불변 클래스인데에 반해
StringBuffer 클래스는 자기 자신이 변할 수 있는 클래스
// 아무 값도 가지고 있지 않은 StringBuffer 객체를 생성
StringBuffer sb = new StringBuffer():
// 해당 스트링 버퍼에 "hello", 공백, "world"를 차례대로 추가
sb.append("hello");
sb.append(" ");
sb.append("world");
// StringBuffer에 추가된 값을 toString() 메소드를 이용하여 반환
String str = sb.toString();
/*
출력 결과
hello world
*/
StringBuffer가 가지고 있는 메소드들은 대부분 자기 자신, this를 반환
StringBuffer sb2 = new StringBuffer();
StringBuffer sb3 = sb2.append("hello");
if(sb2 == sb3){
System.out.println("sb2 == sb3");
}
/*
출력 결과
sb2 == sb3
*/
메소드체이닝 : 자기 자신의 메소드를 호출하여 자기 자신의 값을 바꿔나가는 것
String str2 = new StringBuffer().append("hello").append(" ").append("world").toString();
System.out.println(str2);
- StringBuffer는 append 메소드 외에도 길이를 구하거나, 자르는 등의 다양한 메소드를 가지고 있다.
3. 스트링 클래스의 문제점
String 클래스는 문자열을 다룰 때 사용하는 클래스이다.
String 클래스는 불변 클래스이다.
String str1 = "hello world";
String str2 = str1.substring(5);
System.out.println(str1);
System.out.println(str2);
/*
출력 결과
hello world
world
*/
- 기존의 str1은 전혀 변화가 없다.
- substring 메소드는 5번째부터 문자열을 잘라서 새로운 문자열을 반환하는 메소드이다.
String str3 = str1 + str2;
System.out.println(str3);
/*
출력 결과
hello world world
*/
- 위 코드처럼 문자열과 문자열을 더하게 되면 내부적으로는 아래와 같은 코드가 실행된다.
String str4 = new StringBuffer().append(str1).append(st2).toString();
System.out.println(str4);
- 문자열을 반복문 안에서 더하는 것은 성능상 문제가 생길 수 있으니 반드시 피하는 것이 좋다.
// 좋지 않은 코드
String str5 = "";
for(int i = 0; i < 100; i++){
str5 = str5 + "*";
}
System.out.println(str5);
// 좋은 코드
StringBuffer sb = new StringBuffer();
for(int i = 0; i < 100; i++){
sb.append("*");
}
String str6 = sb.toString();
System.out.println(str6);
4. Math
Math 클래스는 이름 그대로 수학 계산을 위한 클래스이다.
- Math 클래스는 생성자가 private로 되어 있기 때문에 new 연산자를 이용하여 객체를 생성할 수 없다.
- 모든 메소드와 속성이 static으로 되어 있기 때문에 객체를 생성하지 않고도 사용할 수 있다.
int value1 = Math.max(5, 20); // 20
int value2 = Math.min(5, -5); // -5
int value3 = Math.abs(-10); // 10
double value4 = Math.random(); // 0 ~ 1.0 랜덤 실수값
double value5 = Math.sqrt(25); // 5.0
double value6 = Math.pow(2, 3); // 8.0
728x90
반응형
'JAVA > [프로그래머스] 자바 강의' 카테고리의 다른 글
[프로그래머스] 자바 중급 강의 part4. 날짜와 시간 (1) | 2023.02.01 |
---|---|
[프로그래머스] 자바 중급 강의 part3. java.util 패키지 (1) | 2023.02.01 |
[프로그래머스] 자바 중급 강의 part1. Object 클래스 (0) | 2023.01.29 |
[프로그래머스] 자바 입문 강의 part9. 예외처리 (0) | 2023.01.16 |
[프로그래머스] 자바 입문 강의 part8. 인터페이스와 다른 형식의 클래스 (1) | 2023.01.16 |