6.1 패키지
- 패키지의 개념과 필요성
- 패키지: 서로 관련 있는 클래스나 인터페이스의 컴파일된 클래스(.class) 파일들을 하나의 디렉터리에 모아 놓은 것
- 자바의 모듈과 패키지, 클래스 경로명
- 패키지 사용하기, import 문
6.2 패키지 만들기
- 패키지 선언
6.3 모듈 개념
- 모듈: 여러 개의 패키지들을 모은 것
- 자바 플랫폼의 모듈화
- 모듈 기반의 자바 실행 환경
- 자바 모듈화의 목적
6.4 자바 JDK에서 제공하는 패키지
JDK의 주요 패키지
- JDK(Java Development Kit): 자바 API
: 화면 출력, 키 입력, 네트워킹 등 프로그램 개발에 필요한 기본적인 기능과 다양한 응용 기능을 구현한 많은 클래스와 인터페이스들을 포함하는 표준 패키지를 제공한다.
6.5 Object 클래스
Object 클래스의 특징
: Object는 java.lang 패키지에 속한 클래스이며, 모든 클래스는 강제로 Object를 상속받는다.
객체 속성
: Object 클래스는 객체의 속성을 나타내는 메소드 제공
// 예제 6-1: Object 클래스를 이용하여 객체의 클래스명, 해시코드값, 문자열을 출력해보자.
class Point{
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class ObjectPropertyEx {
public static void main(String[] args) {
Point p = new Point(2,3);
System.out.println(p.getClass().getName()); // 클래스 이름
System.out.println(p.hashCode()); // 해시코드 값
System.out.println(p.toString()); // 객체의 문자열
}
}
toString() 메소드, 객체를 문자열로 변환
- toString(): 객체를 문자열로 변환한다.
// 예제 6-2: Point 클래스에 Point 객체를 문자열로 리턴하는 toString() 메소드를 작성하라.
class Point{
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() { // toString: Point 객체를 문자열로 리턴함
return "Point(" + x + ", " + y + ")";
}
}
public class ToStringEx {
public static void main(String[] args) {
Point a = new Point(2,3);
System.out.println(a.toString());
System.out.println(a);
}
}
객체 비교와 equals() 메소드
// 예제 6-3: Point 클래스의 equals() 작성
class Point{
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object obj) {
Point p = (Point)obj;
if(x==p.x && y==p.y)
return true;
else
return false;
}
}
public class EqualsEx {
public static void main(String[] args) {
Point a = new Point(2,3);
Point b = new Point(2,3);
Point c = new Point(3,4);
if(a==b)
System.out.println("a==b");
// a.equals(x)
if(a.equals(b))
System.out.println("a is equal to b");
if(a.equals(c))
System.out.println("a is equal to c");
}
}
/*
* 예제 6-4
* int 타입의 width(너비), height(높이) 필드를 가지는 Rect 클래스를 작성하고,
* 면적이 같으면 두 Rect 객체가 같은 것으로 판별하는 equals()
*/
class Rect{
private int width, height;
public Rect(int width, int height) {
this.width = width;
this.height = height;
}
public boolean equals(Object obj) {
Rect p = (Rect)obj; // obj를 Rect로 다운캐스팅
if(width*height == p.width*p.height)
return true;
else
return false;
}
}
public class RectEx {
public static void main(String[] args) {
Rect a = new Rect(2,3);
Rect b = new Rect(3,2);
if(a.equals(b))
System.out.println("a is equals to b");
}
}
6.6 Wrapper 클래스
Wrapper 클래스 개념
Wrapper 클래스의 객체 생성
Wrapper 클래스의 활용
박싱(boxing)과 언박싱(unboxing)
- 박싱(boxing): 기본 타입의 값을 Wrapper 객체로 변환하는 것
- 언박싱(unboxing): Wrapper 객체에 들어있는 기본 타입의 값을 빼내는 것
- 자동 박싱과 자동 언박싱
6.7 String과 StringBuffer 클래스
String 생성과 특징
- 스트링 리터럴과 new String()
String 활용
- 스트링 비교, equals()와 compareTo()
- 공백 제거, trim()
StringBuffer 클래스
: 스트링을 다루는 클래스
- 내부에 가변 크기의 버퍼를 가지고 문자의 개수에 따라 버퍼 크기를 자동 조절한다.
그러므로 String 객체와 달리, 생성된 스트링의 수정이 가능하다.
StringBuffer sb = new StringBuffer("This"); // StringBuffer 객체 생성
sb.append(" is pencil."); // append: "This is pencil"
sb.insert(7, " my"); // insert 7: "This is my pencil."
sb.replace(8, 10, "your"); // replace 8~10: "This is your pencil."
6.8 StringTokenizer 클래스
: 문자열을 분리하기 위해 사용된다.
- 구분 문자(delimiter): 문자열을 분리할 때 사용되는 기준 문자
- 토큰(token): 구분 문자로 분리된 문자열
// 예제 6-7
import java.util.StringTokenizer;
public class StringTokenizerEx {
public static void main(String[] args) {
String query = "name=kitae&addr=seoul&age=21"; // query
StringTokenizer st = new StringTokenizer(query, "&"); // 구분문자 &
int n = st.countTokens(); // 분리된 토큰 개수
System.out.println("토큰 개수 = " + n);
while(st.hasMoreTokens()) {
String token = st.nextToken(); // 토큰 얻기
System.out.println(token); // 토큰 출력
}
}
}
6.9 Math 클래스
: 기본적인 산술 연산을 수행하는 메소드를 제공하는 클래스
// 예제 6-8: Math 클래스 활용
public class MathEx {
public static void main(String[] args) {
System.out.println(Math.abs(-3.14)); // 절댓값
System.out.println(Math.sqrt(9.0)); // 제곱근
System.out.println(Math.exp(2)); // e^2
System.out.println(Math.round(3.14)); // 반올림
// [1, 45] 사이의 정수형 난수 5개 발생
System.out.print("이번주 행운의 번호는 ");
for(int i=0; i<5; i++)
System.out.print((int)(Math.random()*45 + 1) + " "); // 난수 발생
}
}
'Programming > Java프로그래밍및실습' 카테고리의 다른 글
[자프실] 8. 자바 GUI 스윙 기초 (1) | 2024.01.10 |
---|---|
[자프실] 7. 컬렉션과 제네릭 (0) | 2024.01.07 |
[자프실] 5. 상속 (1) | 2024.01.05 |
[자프실] 4. 클래스와 객체 (1) | 2024.01.04 |
[자프실] 3. 반복문과 배열 그리고 예외 처리 (1) | 2024.01.02 |