자바 API 도큐먼트
- API : Application Programming Interface
- 라이브러리라고도 하며, 프로그램 개발에 자주 사용되는 클래스 및 인터페이스의 모음
- 버전별 API 도큐먼트 참
Java Platform, Standard Edition Documentation - Releases
객체 해시코드 hashCode()
- 객체를 식별하는 하나의 정수값
- Object클래스의 hashCode() 메서드는 객체의 메모리 번지를 이용해서 해시코드를 만들어 리턴하기 때문에 객체마다 다른 값을 가짐
- 우선 hashCode() 실행해서 리턴된 값이 같다면 equals()로 다시 비교 후 True라면 같은 객체
객체 문자 정보 toString()
- 객체를 문자열로 표현한 값인 문자정보를 리턴
- toString() 메서드는 ‘클래스이름@16진수해시코드’로 구성된 문자 정보 리턴
- 이를 좀 더 유용하도록 하위 클래스에서 오버라이딩하여 주로 사용
프로그램 종료 exit()
- 현재 실행 중인 프로세스 강제 종료
public class ExitExample {
public static void main(String[] args) {
for(int i=0; i<10; i++) {
if(i == 5) {
System.exit(i);
//break;
}
}
System.out.println("마무리 코드");
// 강제종료되어 출력문 실행 안됨
}
}
현재 시각 읽기 currentTimeMillis(), nanoTime()
- 컴퓨터의 시계로부터 현재 시간을 읽어서 long값을 리턴
public class SystemTimeExample {
public static void main(String[] args) {
long time1 = System.nanoTime();
int sum = 0;
for(int i=1; i<=1000000; i++) {
sum += i;
}
long time2 = System.nanoTime();
System.out.println("1~1000000까지의 합: " + sum);
System.out.println("계산에 " + (time2-time1) + " 나노초가 소요되었습니다.");
}
}
//1~1000000까지의 합: 1784293664
//계산에 2753300 나노초가 소요되었습니다.
Class 객체 얻기 getClass(), forName()
클래스로부터 얻는 방법
Class clazz = 클래스이름.class
Class clazz = Class.forName("패키지...클래스이름")
객체로부터 얻는 방법
Class clazz = 참조번수.getClass();
위의 두가지는 객체없이 클래스 이름만으로 얻는 방법
클래스로부터 객체가 이미 생성되어 있을 경우
Class clazz = String.class;
Class clazz = Class.forName("java.lang.String");
String str - "김자바";
Class clazz = str.getClass();
public class ClassExample {
public static void main(String[] args) throws Exception {
//방법1
Class clazz = Car.class;
//방법2
Class clazz = Class.forName("sec01.exam09.Car");
//방법3
Car car = new Car();
Class clazz = car.getClass();
System.out.println(clazz.getName());
System.out.println(clazz.getSimpleName());
System.out.println(clazz.getPackage().getName());
}
}
클래스 경로를 활용해서 리소스 절대 경로 얻기
- Class 객체는 해당 클래스의 파일 경로 정보를 가지고 있기 때문에 다른 리소스 파일의 경로 얻을 수 있음
public class ClassExample {
public static void main(String[] args) {
Class clazz = Car.class;
String photo1Path = clazz.getResource("photo1.jpg").getPath();
String photo2Path = clazz.getResource("images/photo2.jpg").getPath();
System.out.println(photo1Path);
System.out.println(photo2Path);
}
}
// /C:/Users/Desktop/java/SelfStudyJava/chap11/bin/sec01/exam10/photo1.jpg
// /C:/Users/Desktop/java/SelfStudyJava/chap11/bin/sec01/exam10/images/photo2.jpg
String 생성자
- 자바의 문자열은 java.lang 패키지의 String 클래스의 인스턴스로 관리
- String 클래스의 다양한 생성자를 이용해서 직접 String 객체 생성 가능
자주 사용하는 생성자
//배열 전체를 String 객체로 생성
String str = new String(byte[] bytes);
//지정한 문자셋으로 디코딩
String str = new String(byte[] bytes, String charsetName);
//배열의 offset 인덱스 위치부터 length만큼 String 객체로 생성
String str = new String(byte[] bytes, int offset, int length);
//지정한 문자셋으로 디코딩
String str = new String(byte[] bytes, int offset, int length, String charsetName)
바이트 배열을 문자열로 변환
public class KeyboardToStringExample {
public static void main(String[] args) throws IOException {
byte[] bytes = new byte[100]; // 읽은 바이트를 저장하기 위한 배열 생성
System.out.print("입력: ");
int readByteNo = System.in.read(bytes); // 배열에 읽은 바이트를 저장하고 읽은 바이트 수를 리턴
String str = new String(bytes, 0, readByteNo-2); // \r, \n 제외하기 위해 -2
System.out.println(str);
}
}
String 메서드
리턴 타입 | 메서드 이름(매개 변수) | 설명 |
---|---|---|
char | charAt(int index) | 특정 위치의 문자를 리턴 |
boolean | equals(Object anObject) | 두 문자열을 비교 |
byte[] | getBytes() | byte[]로 리턴 |
byte[] | getBytes(Charset charset) | 주어진 문자셋으로 인코딩한 byte[]로 리턴 |
int | indexOf(String str) | 문자열 내에서 주어진 문자열의 위치를 리턴 |
int | length() | 총 문자의 수를 리턴 |
String | replace(CharSequence target, CharSequence replacement) | target 부분을 replacement로 대치한 새로운 문자열을 리턴 |
String | substring(int beginIndex) | beginIndex 위치에서 끝까지 잘라낸 새로운 문자열을 리턴 |
String | substring(int beginIndex, int endIndex) | beginIndex 위치에서 endIndex 전까지 잘라낸 새로운 문자열을 리턴 |
String | toLowerCase() | 알파벳 소문자로 변환한 새로운 문자열을 리턴 |
String | toUpperCase() | 알파벳 대문자로 변환한 새로운 문자열을 리턴 |
String | trim() | 앞뒤 공백을 제거한 새로운 문자열을 리턴 |
String | valueOf(int i) , valueOf(double d) | 기본 타입 값을 문자열로 리턴 |
문자 추출 charAt()
String subject = "자바 프로그래밍";
char charValue = subject.cahrAt(3); // 프
문자열 비교 equals()
String strVar1 = new String("신민철");
String strVar2 = "신민철";
String strVar3 = "신민철";
// 참조 객체 같은지 확인
strVar1 == strVar2 // false
strVar2 == strVar3 // true
// 문자열만 같은지 비교
strVar1.equals(strVar2) // true
strVar2.equals(strVar3) // true
바이트 배열로 변환 gteBytes()
public class StringGetBytesExample {
public static void main(String[] args) {
String str = "안녕하세요";
//기본 문자셋으로 인코딩, 디코딩
byte[] bytes1 = str.getBytes();
System.out.println("bytes1.length: " + bytes1.length);
String str1 = new String(bytes1);
System.out.println("bytes1->String: " + str1);
try {
// EUC-KR로 인코딩, 디코딩
byte[] bytes2 = str.getBytes("EUC-KR");
System.out.println("bytes2.length: " + bytes2.length);
String str2 = new String(bytes2, "EUC-KR");
System.out.println("bytes2->String: " + str2);
// 잘못된 문자셋 매개값으로 주면 에러 발생
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
문자열 찾기 indexOf()
매개값으로 주어진 문자열이 시작되는 인덱스 리턴, 없으면 -1 리턴
public class StringIndexOfExample {
public static void main(String[] args) {
String subject = "자바 프로그래밍";
int location = subject.indexOf("프로그래밍");
System.out.println(location);
if(subject.indexOf("자바") != -1) {
// 포함된 경우
System.out.println("자바와 관련된 책이군요");
} else {
// 포함되지 않은 경우
System.out.println("자바와 관련없는 책이군요");
}
}
}
문자열 길이 length()
문자열 길이 리턴
String ssn = "7306241230123";
int length = ssn.length();
문자열 대치 replace()
첫번째 매개값인 문자열 찾아 두번째 매개값 문자열로 대치한 새로운 문자열 리턴
public class StringReplaceExample {
public static void main(String[] args) {
String oldStr = "자바는 객체지향언어 입니다. 자바는 풍부한 API를 지원합니다.";
String newStr = oldStr.replace("자바", "JAVA");
System.out.println(oldStr);
System.out.println(newStr);
}
}
//자바는 객체지향언어 입니다. 자바는 풍부한 API를 지원합니다.
//JAVA는 객체지향언어 입니다. JAVA는 풍부한 API를 지원합니다.
문자열 잘라내기 substring()
public class StringSubstringExample {
public static void main(String[] args) {
String ssn = "880815-1234567 ";
String firstNum = ssn.substring(0, 6);
System.out.println(firstNum); //880815
String secondNum = ssn.substring(7);
System.out.println(secondNum); //1234567
}
}
알파벳 대,소문자 변경 toLowerCase() , toUpperCase()
영어로 된 두 문자열을 대소문자 관계없이 비교할 때 주로 사용
public class StringToLowerUpperCaseExample {
public static void main(String[] args) {
String str1 = "Java Programming";
String str2 = "JAVA Programming";
System.out.println(str1.equals(str2)); //false
String lowerStr1 = str1.toLowerCase();
String lowerStr2 = str2.toLowerCase();
System.out.println(lowerStr1.equals(lowerStr2)); //true
// 대소문자 맞추지 않아도 됨
System.out.println(str1.equalsIgnoreCase(str2)); //true
}
}
문자열 앞뒤 공백 잘라내기 trim()
String oldstr = " 자바 프로그래밍 ";
String newstr = oldstr.trim();
// "자바 프로그래밍"
문자열 변환 valueOf()
public class StringValueOfExample {
public static void main(String[] args) {
String str1 = String.valueOf(10);
String str2 = String.valueOf(10.5);
String str3 = String.valueOf(true);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
기본 타입 | 포장 클래스 |
---|---|
byte | Byte |
char | Character |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
박싱과 언박싱
- 기본 타입의 값을 포장 객체로 만드는 과정을 박싱, 반대를 언박싱
- 기본타입의 값 박싱
기본 타입의 값을 줄 경우 | 문자열을 줄 경우 |
---|---|
Byte obj = new Byte(10); | Byte obj = new Byte(”10”); |
Character obj = new Character(’가’); | 없음 |
Short obj = new Short(100); | Short obj = new Short(”100”); |
Integer obj = new Integer(1000); | Integer obj = new Integer(”1000”); |
Long obj = new Long(10000); | Long obj = new Long(”10000”); |
Float obj = new Float(2.5F); | Float obj = new Float(”2.5F”); |
Double obj = new Double(3.5); | Double obj = new Double(”3.5”); |
Boolean obj = new Boolean(true); | Boolean obj = new Boolean(”true”); |
생성자 이용하지 않아도 각 포장 클래스마다 가지고 있는 정적 valueOf() 메서드 사용 가능
Interger obj = Integer.valueOf(1000);
Integer obj = Integer.valueOf("1000");
언박싱 할 때는 ‘기본 타입이름 + Value()’ 메서드 호출
num = obj.intValue();
자동 박싱과 언박싱
- 자동 박싱은 포장 클래스 타입에 기본값이 대입될 경우에 발생
- int 타입의 값을 Integer 클래스 변수에 대입하면 자동 박싱이 일어나 Integer 객체 생성
Integer obj = 100;
- 자동 언박싱은 기본 타입에 포장 객체가 대입되는 경우와 연산에서 발생
- Integer 객체를 int 타입 변수에 대입하거나, 연산하면 자동 언박싱되어 연산
Integer obj = new Integer(200);
int value1 = obj;
int value2 = obj + 100; // 자동 언박싱
문자열을 기본 타입 값으로 변환
- 포장 클래스 주요 용도는 기본 타입의 값을 박싱해서 포장 객체로 만드는 것이지만,
문자열을 기본 타입 값으로 변환할 때도 많이 사용- 정적 메서드로 문자열을 매개값으로 받아 기본 타입 값으로 변환
- ex) int
num = Integer.parseInt(”1000”);
포장 값 비교
- 포장 객체는 내부의 값을 비교할 때 ==, != 사용하지 않는 것이 좋음
타입 | 값의 범위 |
---|---|
boolean | true, false |
char | \u0000 ~ \u007f |
byte, short, int | -128 ~ 127 |
박싱된 값이 위의 표의 범위안의 값이면 ==,≠ 로 비교 가능하지만, 그 외에는 언박싱한 값 비교해야함
→ 따라서 직접 내부 값을 언박싱 후 비교하거나, equals() 메서드로 내부 값을 비교하는 것이 좋음
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(”yyyy년 MM월 dd일 hh시 mm분 ss초”);
String strNow = sdf.format(now);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR); //연도
int month = now.get(Calendar.MONTH) + 1; // 월
int dayOfMonth = now.get(Calendar.DAY_OF_MONTH); //일
String week = now.get(Calendar.DAY_OF_WEEK); //요일
String amPm = now.get(Calendar.AM_PM); //오전/오후
int hour = now.get(Calendar.HOUR); // 시
import java.text.SimpleDateFormat;
import java.util.Date;
public class DatePrintExample {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 E요일 HH시 mm분");
System.out.println(sdf.format(now));
}
}