IT 공부용
[07/25] 9_JAVA_java.lang패키지와 유용한 클래스 본문
ch9-1) Object 클래스
- 모든 클래스의 최고 조상. 오직 11개의 메서드만을 가지고 있다.
- notify(), wait() 등은 쓰레드와 관련된 메서드 이다.

ch9-1) equals(Object obj)
- 객체 자신(this)과 주어진 객체(obj)를 비교한다. 같으면 true 다르면 false
- Object클래스의 equals()는 객체의 주소를 비교(참조변수 값 비교)
public class ch09_2 {
public static void main(String[] args) {
Value v1 = new Value(10);
Value v2 = new Value(10);
System.out.println(v1.equals(v2)); //false
}
}
class Value {
int value;
Value(int value) {
this.value = value;
}
}
false 나오는 이유는 "주소값"을 비교 했기 때문에.
public class ch09_2 {
public static void main(String[] args) {
Value v1 = new Value(10);
Value v2 = new Value(10);
System.out.println(v1.equals(v2));
}
}
class Value {
int value;
Value(int value) {
this.value = value;
}
public boolean equals(Object obj) {
Value v = (Value) obj; //형변환 해줘야 밑에꺼 실행가능
return this.value == v.value;
}
}
이래야 true 나옴
ch9-3) equals(Object obj)의 오버라이딩
- 인스턴스 변수(iv)의 값을 비교하도록 equals()를 오버라이딩 해야 한다.
class Person {
long id;
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
return id == ((Person) obj).id;
}
Person(long id) {
this.id = id;
}
}
public class ch09_4 {
public static void main(String[] args) {
Person p1 = new Person(8011081111222L);
Person p2 = new Person(8011081111222L);
if(p1.equals(p2))
System.out.println("참");
else
System.out.println("거짓");
}
}
결과값 : 참
ch9-7) String 클래스
- 문자열을 다루는 클래스
- String 클래스 = 데이터(char[]) + 메서드(문자열 관련)
- 내용을 변경할 수 없는 불변(immutable) 클래스
- 덧셈 연산자(+)를 이용한 문자열 결합은 성능이 떨어짐
문자열의 결합이나 변경이 잦다면, 내용을 변경가능한 StringBuffer를 사용
ch9-8) 문자열의 비교
- String str = "abc"와 String str = new String("abc"); 의 비교
String str1 = "abc"; // 문자열 리터럴
String str2 = "abc"; // 문자열 리터럴
String str3 = new String("abc"); // 새로운 String 인스턴스를 생성, 항상 새로운 문자열이 만들어짐
String str4 = new String("abc");
str1 == str2 ? true
str1 equals(str2) ? true
str3 == str4 ? false
str3 equals(str4) ? true 0x200 ==? 0x300
ch9-9) 문자열 리터럴
- 문자열 리터럴은 프로그램 실행시 자동으로 생성된다.(constant pool=상수저장소 에 저장)
String s1 = "AAA"; // 문자열 리터럴
String s2 = "AAA"; // 문자열 리터럴
String s3 = "AAA"; // 문자열 리터럴
- 같은 내용의 문자열 리터럴은 하나만 만들어진다.
s1 = ox100 ->
s2 = ox100 -> AAA(0x100)
s3 = ox100 ->
ch9-10) 빈 문자열 (" ", empty string)
- 내용이 없는 문자열. 크기가 0인 char형 배열을 저장하는 문자열
String str = ""; // str을 빈 문자열로 초기화
- 크기가 0인 배열을 생성하는 것은 어느 타입이나 가능
char [] chArr = new char[0]; // 길이가 0인 char배열
int [] iArr = {}; // 길이가 0인 int배열
-문자(char)와 문자열(String)의 초기화
String s = ""; //빈 문자열로 초기화
char c = ' '; // 공백으로 초기화
String str1 = "";
String str2 = "";
ch9-11) String 클래스의 생성자와 메서드(1/5)

String(char[] value) = char[] 를 -> string으로 바꿀때
반대는
tocharArray()
String(StringBuffer buf) = 내용변경 가능
ch9-11) String 클래스의 생성자와 메서드(2/5)

ch9-11) String 클래스의 생성자와 메서드(3/5)

ch9-11) String 클래스의 생성자와 메서드(4/5)

ch9-11) String 클래스의 생성자와 메서드(5/5)

ch9-12) join()과 StringJoiner
- join()은 여러 문자열 사이에 구분자를 넣어서 결합한다.
String animals = "dog,cat,bear";
String[] arr = animals.split(","); //문자열을 ','를 구분자로 나눠서 배열에 저장
String str = String.join("-", arr); // 배열의 문자열을 '-'로 구분해서 결합
System.out.println(str); //dog-cat-bear
ch9-13) 문자열과 기본형 간의 변환
// << 숫자열 -> 문자열 >>
int i = 100;
String str1 = i + ""; // ok!
String str2 = String.valueOf(i); //속도 빠름
// << 문자열 -> 숫자열 >>
int j = Integer.parseInt("100"); // 문자 "100" -> 숫자 100
int j2 = Integer.valueOf("100");
ch9-15) StringBuffer 클래스(문자열을 저장하기위한 클래스)
- String 처럼 문자형 배열(char[])을 내부적으로 갖고있다.
- 그러나, String(immutable)과 달리 내용을 변경할 수 있다(mutable).
StringBuffer sb = new StringBuffer("abc");
sb.append("123") //sb 내용 뒤에 "123"을 추가 가능
ch9-16) StringBuffer의 생성자
- 배열은 길이 변경 불가. 공간이 부족하면 새로운 배열 생성해야
- StringBuffer는 저장할 문자열의 길이를 고려해서 적절한 크기로 생성해야
0x100 -> 1 2 3 4 5
0x200 -> 0 0 0 0 0 0 0 0
해결책
1. 새로운 배열 생성 한 후 내용 복사
ch9-17) StringBuffer의 변경
- StringBuffer는 String과 달리 내용변경이 가능하다.
- append() : 끝에 문자열 추가
- delete() : 삭제
- insert() : 삽입
반환타입이 StringBuffer -> 즉 추가, 삭제, 삽입 한 후 참조를 반환
ch9-18) StringBuffer의 비교
- String 은 내용비교 이지만.
- StringBuffer는 equals()가 오버라이딩 되어있지 않다. 즉 주소비교 함
StringBuffer sb = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb == sb2); // false 주소값비교됨
System.out.println(sb.equals(sb2)); // false 주소값비교됨
// << 그래서 문자열로 비교하기 위해 문자로 바꿈 >>
String s = sb.toString(); // sb를 String 으로 변환
String s2 = sb2.toString();
System.out.println(s.equals(s2)); //true
ch9-19) StringBuffer의 생성자와 메서드(1/4)

ch9-19) StringBuffer의 생성자와 메서드(2/4)

ch9-19) StringBuffer의 생성자와 메서드(3/4)

ch9-19) StringBuffer의 생성자와 메서드(4/4)

ch9-19) StringBuffer의 생성자와 메서드 - 예제
StringBuffer sb = new StringBuffer("01");
StringBuffer sb2 = sb.append(23);
sb.append('4').append(56); // 메서드 체이닝
StringBuffer sb3 = sb.append(78);
sb3.append(9.0);
System.out.println("sb = "+ sb); // sb = 0123456789.0
System.out.println("sb2 = "+ sb2); // sb2 = 0123456789.0
System.out.println("sb3 = "+ sb3); // sb3 = 0123456789.0
System.out.println("sb = "+ sb.deleteCharAt(10)); // sb = 01234567890
System.out.println("sb3 = "+ sb.delete(3, 6)); // sb3 = 01267890
System.out.println("sb3 = "+ sb.insert(3, "abc")); // sb3 = 012abc67890
System.out.println("sb3 = "+ sb.replace(6, sb.length(), "END")); // sb3 = 012abcEND
System.out.println("capacity = "+ sb.capacity()); // capacity = 18
System.out.println("length = "+ sb.length()); // length = 9
ch9-21) StringBuilder - 동기화x
- StringBuffer은 동기화가 되어 있다. -> 멀티 쓰레드에 안전 (Thread - safe)
- 동기화는 데이터 보호
- 멀티 쓰레드 프로그램이 아닌 경우, 동기화는 불필요한 성능 저하
이럴 땐 StringBuffer대신 StringBuilder를 사용하면 성능 향상
StringBuffer sb; - > StringBuilder sb;
sb = new StringBuffer(); - > sb = new StringBuilder();
sb.append("abc") - > sb.append("abc")
지금까지 작성해온 프로그램은 전부 싱글 쓰레드(한번에 한 작업) 으로 작성된 것이고, 멀티 쓰레드(한번에 여러개)로 프로그램을 작성하는 방법은 쓰레드에서 ㄱㄱ
ch9-22) Math 클래스
- 수학관련 static메서드의 집합
- round() = 반올림 함수로 원하는 소수점 아래 세 번째 자리에서 반올림하기.
1. 원래 값에 100 곱한다.
90.7552 * 100 -> 9075.52
2. 위의 결과에 Math.round()를 사용한다.
Math.round(9075.52) -> 9076
3. 위의 결과를 다시 100.0으로 나눈다.
9076 / 100.0 -> 90.76 // 소수점 아래 반올림은 실수로 나눈다.
ch9-23) Math클래스의 메서드(1/2)

ch9-23) Math클래스의 메서드(2/2)

ch9-25) 래퍼(wrapper) 클래스
- 기본형 값을 감싸는 클래스
- 8개의 기본형을 객체로 다뤄야할 때 사용하는 클래스

기본형 첫글자를 대문자로만 바꾸면 래퍼 클래스가 됨
ch9-25) 래퍼(wrapper) 클래스 - 예제
public class ch09_26 {
public static void main(String[] args) {
Integer i = new Integer(100);
Integer i2 = new Integer(100);
System.out.println("i==i2 = "+ (i==i2)); // 주소값 false
System.out.println("i.equals(i2) = " + i.equals(i2)); // 오버라이딩 되어있음 true
System.out.println("i.compareTo(i2) = "+ i.compareTo(i2));
System.out.println("i.toString() = " + i.toString());
System.out.println("Max_Value = "+ Integer.MAX_VALUE);
System.out.println("MIN_VALUE = " + Integer.MIN_VALUE);
System.out.println("SIZE = "+Integer.SIZE+" bits");
System.out.println("BYTES = " + Integer.BYTES + " bytes" );
System.out.println("TYPE = "+ Integer.TYPE);
}
}
<<결과>>
i==i2 = false
i.equals(i2) = true
i.compareTo(i2) = 0
i.toString() = 100
Max_Value = 2147483647
MIN_VALUE = -2147483648
SIZE = 32 bits
BYTES = 4 bytes
TYPE = int
ch9-27) Number 클래스
- 모든 숫자 래퍼 클래스의 조상

ch9-28) 문자열을 숫자로 변환하기
- 문자열을 숫자로 변환하는 다양한 방법
int i = new Integer("100").intValue(); // floatValue(), longValue(), ........
int i2 = Integer.parseInt("100");
int i3 = Integer.valueOf("100");
valueOf를 사용하면 래퍼클래스로 변환 가능
- n진법의 문자열을 숫자로 변환하는 방법
int i4 = Integer.parseInt("100",2); // 100(2) -> 4
int i5 = Integer.parseInt("100",8); // 100(8) -> 64
int i6 = Integer.parseInt("100",16); // 100(16) -> 256
int i7 = Integer.parseInt("FF",16); // FF(16) -> 255
ch9-30) 오토박싱 & 언박싱
int -> Integer = 오토박싱
Integer -> int = 언박싱
public class ch09_30 {
public static void main(String[] args) {
int i = 5;
Integer j = new Integer(7);
int sum = i + j; // 기본형 + 참조형 이지만 쌉가능
System.out.println(sum); // 12 컴파일러가 자동으로 sum = i + j.intValue()로 바꾸어줌
}
}'▶ JAVA' 카테고리의 다른 글
| [07/27] 11.1_JAVA_컬렉션 프레임웍(Collections framework) (0) | 2021.07.27 |
|---|---|
| [07/26] 10_JAVA_날짜와 시간 & 형식화 (0) | 2021.07.26 |
| [07/24] 8_JAVA_예외처리 (0) | 2021.07.24 |
| [07/24] 7.3_JAVA_상속 (0) | 2021.07.24 |
| [07/23] 7.2_JAVA_상속 (0) | 2021.07.23 |