2주차 JAVA API
발표자 : 자바카페 이기승
목차
1. java.lang.*
2. java.util.*
3. Exception Handling
1. java.lang.*
- 자바 프로그래밍할 때, 가장 기본이 되는 클래스들이 모여있다.
- Import문 선언 없이 사용 가능하다.
- 컴파일 단계에서 포함한다. - java.lang 패키지
Object 클래스
- Object 클래스는 클래스 계층 구조의 최상위에 위치.
- Object 클래스는 멤버 변수는 없고 11개의 메서드만 가지고 있다.
- 모든 클래스에는 Object 클래스가 가지고 있는 메서드를 모두 사용 가능하다.
- Object (Java Platform SE 8 ) (oracle.com)
Object (Java Platform SE 8 )
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup. The general contract of fi
docs.oracle.com
equals(Object obj) 메서드
- 매개변수로 객체의 참조 변수를 받아서 비교하여 그 결과를 boolean 값으로 알려주는 역할을 한다.
- 같은 객체를 참조하고 있는지 판단할 수 있으며 객체가 가지고 있는 값으로 동일 여부를 판단해야 할 경우 오버라이딩 하여 사용한다.
hashCode() 메서드
- HashCode 객체의 메모리 주소를 바탕으로 하여 HashCode를 반환
- 메모리 주소가 다른 객체는 같은 해시 코드 값을 가질 수 없음
- HashCode는 HashMap 같은 해싱 알고리즘을 사용하는 자료구조에 주로 사용함
- equals를 오버라이딩 할 경우, hashCode도 오버라이딩 해야함
💡 equals를 오버라이딩 할 경우, hashcode도 오버라이딩 해야되는 이유
Why do I need to override the equals and hashCode methods in Java? - Stack Overflow
Why do I need to override the equals and hashCode methods in Java?
Recently I read through this Developer Works Document. The document is all about defining hashCode() and equals() effectively and correctly, however I am not able to figure out why we need to ov...
stackoverflow.com
equals 비교했을 경우 hashcode가 같아야 되는 규약이 있다.
equals만 오버라이딩 했을경우 값이 같기 때문에 같다고, 나오며 hashcode값은 다르므로
HashMap, HashSet 및 Hashtable을 포함한 모든 해시 기반 컬렉션과 해시 알고리즘을 사용할 때 문제가 발생한다.
toString() 메서드
- 인스턴스에 대한 정보를 문자열(String)로 제공할 목적으로 정의한 것이다.
- 의도에 맞게 오버라이딩 해서 사용해야 함
String 클래스
- 문자열 처리를 위해 자바에서 제공하는 기본 클래스
- String이 가지고 있는 문자열은 읽어올 수 있으나 변경할 수 없다.(immutable)
- +’ 연산자를 이용해서 문자열을 결합하는 경우 인스턴스 내의 문자열이 바뀌는 것이 아니라 새로운 문자열이 담긴 String 인스턴스가 생성된다.
- 문자열을 만들 때는 문자열 리터럴을 지정하는 방법과 String 클래스의 생성자를 사용해서 만드는 방법이 있다.
- 생성자로 문자열을 만들면 Heap 메모리에 객체가 만들어진다.
- 리터럴로 문자열을 만들면 String Constant Pool에 객체가 만들어진다.
s1과 s2는 같은 참조를 받고 있고 같은 해시 코드 값을 가지고 있다.(같은 메모리이다)
StringBuffer 클래스와 StringBuilder 클래스
- StringBuffer와 StringBuilder클래스는 문자열이 변경 가능하다.
- 내부적으로 문자열 편집을 위한 버퍼(buffer)를 가지고 있으며, 인스턴스를 생성할 때 크기를 지정할 수 있다.
- String 클래스에서는 equals메서드를 오버라이딩해서 문자열의 내용을 비교하도록 구현되어 있지만
- StringBuffer, StringBuilder 클래스는 equals메서드를 오버라이딩하지 않아서 equals메서드를 사용해도 ==로 비교한 것과 같은 결과를 얻는다.
StringBuffer 클래스와 StringBuilder 클래스 차이
- StringBuffer는 멀티쓰레드에 안전(thread safe)하도록 동기화되어 있다.
- StringBuilder는 StringBuffer에서 쓰레드 동기화 기능만 제거되어있다.
래퍼(wrapper) 클래스
기본형(Primitive type) 변수를 객체로 변환할 수 있도록 도와주는 클래스
Integer클래스는 유효 범위의 숫자에 대해서 캐싱이 되어 있어 캐시를 반환한다..
(Long클래스도 마찬가지이며 다른 wrapper클래스도 그럴 것 같다.)
오토박싱 & 언박싱
- 오토박싱: 기본형에서 래퍼 클래스의 객체로 변환해주는 것
- 언박싱 : 래퍼 클래스에서 기본형으로 변환해주는 것
2. java.util.*
자바 프로그래밍할 때, 자주 사용하는 자료 구조와 유틸리티 클래스를 모아둠
Java Collection Framework
Objects 클래스 (java.lang.*은 Object 클래스)
객체 비교, 해시 코드 생성, null 여부, 객체 문자열 리턴 등의 연산을 수행하는 정적 메소드들로 구성된 Object의 유틸리티 클래스
Objects (Java Platform SE 8 ) (oracle.com)
Objects (Java Platform SE 8 )
Generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]). This method is useful for implementing Object.hashCode()
docs.oracle.com
compare 메소드
Date 클래스
- 자바에서 기본으로 제공해주는 날짜 클래스
- 지역화를 제공하지 않아 대다수의 메서드가 Deprecated 되었다.
- Date (Java Platform SE 8 ) (oracle.com)
Date (Java Platform SE 8 )
The class Date represents a specific instant in time, with millisecond precision. Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed t
docs.oracle.com
Calendar 클래스
- Date 클래스의 단점을 보강하여 만들어졌다.
- 지역화 기능을 제공한다.
- 불변 객체(immutable object)가 아니라서 값이 수정될 수 있다.
- 윤년 같은 특별한 상황을 고려하지 않는다.
- 월(month)을 나타낼 때 1월부터 12월을 0부터 11까지로 표현해야 하는 불편함이 있다.
- Calendar (Java Platform SE 8 ) (oracle.com)
Calendar (Java Platform SE 8 )
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. For example, to roll the current date up by one day, you can achieve it by calling: roll(Calendar.DATE, true). When rolling on the year or Calendar.YE
docs.oracle.com
LocalDateTime 클래스
- Date, Calendar 클래스가 가지고 있는 단점을 해소하기 위해 1.8 버전에 추가되었다.
- java.time 패키지에 위치
- java.time (Java Platform SE 8 ) (oracle.com)
java.time (Java Platform SE 8 )
Class Summary Class Description Clock A clock providing access to the current instant, date and time using a time-zone. Duration A time-based amount of time, such as '34.5 seconds'. Instant An instantaneous point on the time-line. LocalDate A date withou
docs.oracle.com
Random 클래스
- Random 클래스는 난수를 만들어준다.
- 컴퓨터는 난수를 간단히 만들 수 없다.
- seed값을 기준으로 난수 알고리즘을 통해 난수가 만들어진다.
- 서로 다른 Random 인스턴스에 같은 seed 값을 설정하면 같은 패턴으로 난수가 발생한다.
- Random (Java Platform SE 8 ) (oracle.com)
Random (Java Platform SE 8 )
An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.) If two instan
docs.oracle.com
Optional 클래스
- 프로그래밍 할때 가장 많이 발생하는 예외는 NullPointException
- null을 쉽게 처리할 수 있도록 도와준다.
- Java 1.8 부터 사용 가능
- Optional (Java Platform SE 8 ) (oracle.com)
Optional (Java Platform SE 8 )
A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orEl
docs.oracle.com
3. Exception Handling
오류(Error)
시스템에 비정상적인 상황이 생겼을 때 발생한다.
시스템 레벨에서 발생하기 때문에 심각한 수준의 오류이다.
예외(Exception)
개발자가 만든 어플리케이션 코드의 작성 중 예외상황이 발생한 경우.
개발자가 처리할 수 있기 때문에 예외를 구분하고 그에 따른 처리 방법을 명확히 알고 적용하는 것이 중요하다.
Checked Exception & Unchecked Exception
Runtime Exception을 상속받는 것은 Unchecked Exception이다.