API : 자바에서 제공하는 라이브러리 (자주 사용되는 클래스, 인터페이스 모음)
Object 클래스
: 자바의 최상위 부모 클래스
=> 별도 표시 없이 메소드들 바로 오버라이드 가능
- equals() : 동등한 객체인지 비교
public class StringEx6 {
public static void main(String[] args) {
String name1 = new String("홍길동");
String name2 = new String("홍길동");
if (name1==name2) { //참조값=주소번지
System.out.println("같은 이름입니다.");
}else {
System.out.println("다른 이름입니다.");
}
}
}
//
다른 이름입니다.
public static void main(String[] args) {
String name1 = new String("홍길동");
String name2 = new String("홍길동");
if (name1.equals(name2)) { //값내용
System.out.println("같은 이름입니다.");
}else {
System.out.println("다른 이름입니다.");
}
}
}
//
같은 이름입니다.
=> String 클래스의 equals()는 Object 클래스의 equals()를 오버라이딩해 내용값 정보 가져옴
=> Object의 equals() => 직접 사용되지 않고 하위클래스에서 재정의해 논리적으로 동등 비교할 때 사용됨
public class Member{
public String id;
public Member(String id){
this.id=id;
}
@Override
public boolean equals(Object obj){
if(obj instanceof Member) {
Member member = (Member) obj;
if (id.equals(member.id)){
return true;
}
}
return false;
}
}
=> equals() 재정의할 때 매개값(비교 객체)이 기준 객체와 동일 타입인지 먼저 확인해야 함 (instanceof() 사용)
https://mangkyu.tistory.com/101
- hashCode() : 객체를 식별하는 하나의 정수값
hashCode() 리턴값 true -> equals() 리턴값 true -> 동등 객체
- hashCode() 재정의 X
public class Key {
public int number;
public Key(int number) {
this.number=number;
}
@Override
public boolean equals (Object obj) {
if (obj instanceof Key) { //객체타입 확인
Key compareKey = (Key)obj;
if (this.number==compareKey.number) {
return true;
}
}
return false;
}
}
//기존 객체 사용
public class KeyEx1 {
public static void main(String[] args) {
HashMap<Key, String> hashMap = new HashMap<Key, String>();
Key key1 = new Key(1);
Key key2 = new Key(2);
hashMap.put(key1, "김철수");
hashMap.put(key2, "홍길동");
String value1 = hashMap.get(key1);
String value2 = hashMap.get(key2);
System.out.println(value1); //김철수
System.out.println(value2); //홍길동
}
}
//새 객체 생성 후 사용
public class KeyEx1 {
public static void main(String[] args) {
HashMap<Key, String> hashMap = new HashMap<Key, String>();
Key key1 = new Key(1);
Key key2 = new Key(2);
hashMap.put(new Key(1), "김철수"); //새 객체
hashMap.put(new Key(2), "홍길동");
String value1 = hashMap.get(new Key(1)); //새 객체
String value2 = hashMap.get(new Key(2));
System.out.println(value1); //null
System.out.println(value2); //null
}
}
- hashCode() 재정의
public class Key {
public int number;
public Key(int number) {
this.number=number;
}
@Override
public boolean equals (Object obj) {
if (obj instanceof Key) {
Key compareKey = (Key)obj; //강제타입변환
if (this.number==compareKey.number) {
return true;
}
}
return false;
}
@Override
public int hashCode() { //hashCode 재정의
return number;
}
}
public class KeyEx1 {
public static void main(String[] args) {
HashMap<Key, String> hashMap = new HashMap<Key, String>();
Key key1 = new Key(1);
Key key2 = new Key(2);
hashMap.put(new Key(1), "김철수");
hashMap.put(new Key(2), "홍길동");
String value1 = hashMap.get(new Key(1));
String value2 = hashMap.get(new Key(2));
System.out.println(value1);
System.out.println(value2);
}
}
//
김철수
홍길동
=> hashCode() 메소드 오버라이드하여 hashCode, 즉 주소번지에 대한 일치 조건 만듦
※ HashMap
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("김철수", 90);
map.put("이영희", 80);
sysout~ (map.get("김철수"));
sysout~ (map.get("이영희"));
//
90
80
=> key: "김철수", value: 90
- toString : 객체 문자 정보
클래스명@16진수해시코드 리턴
=> 값어치없는 정보이므로 보통 하위 클래스에서 toString() 메소드 오버라이딩 -> 유익한 정보 리턴함
=> 개발자가 만든 클래스에서 toString() 재정의해 유용한 정보 리턴하는 경우도 있음
- Date 클래스의 재정의된 toString()
Date obj = new Date();
System.out.println(obj.toString());
//
Wed Nov 13 09:33:33 KST 2022
- clone() : 객체 복제
- 얕은 복제
단순 필드값 복사 -> 객체 복제
필드가 참조값일 경우 객체의 번지만 복사됨
//얕은 복제 시 기본타입
public class Member implements Cloneable { //복제할 수 있다는 표시
public String id;
public String name;
public String password;
public int age;
public boolean adult;
public Member(String id, String name, String password, int age, boolean adult) {
this.id=id;
this.name=name;
this.password=password;
this.age=age;
this.adult=adult;
}
public Member getMember() { //리턴형 메소드 => Member클래스 리턴
Member cloned = null;
try {
cloned=(Member) clone(); //clone 메소드 리턴 타입은 Object 이므로 강제 형변환
}catch(CloneNotSupportedException e) { //Cloneable 인터페이스 implement해야 함
}
return cloned;
}
}
public class MemberEx1 {
public static void main(String[] args) {
//Member 인스턴스 객체 생성
Member original = new Member("hong","홍길동","12345",50,true);
Member cloned = original.getMember(); //복제된 객체
cloned.password="56789";
//원본 객체 출력
System.out.println("아이디 : "+original.id);
System.out.println("이름 : "+original.name);
System.out.println("비밀번호 : "+original.password);
System.out.println("나이 : "+original.age);
System.out.println("어른인가요? "+original.adult);
//복제 객체 출력
System.out.println("아이디 : "+cloned.id);
System.out.println("이름 : "+cloned.name);
System.out.println("비밀번호 : "+cloned.password);
System.out.println("나이 : "+cloned.age);
System.out.println("어른인가요? "+cloned.adult);
}
}
//
아이디 : hong
이름 : 홍길동
비밀번호 : 12345
나이 : 50
어른인가요? true
아이디 : hong
이름 : 홍길동
비밀번호 : 56789
나이 : 50
어른인가요? true
//얕은 복사 시 참조타입
public class Member2 implements Cloneable{
public String name;
public int age;
public int[] scores; //참조타입
public Car car; //참조타입
public Member2(String name, int age, int[] scores, Car car) {
this.name=name;
this.age=age;
this.scores=scores;
this.car=car;
}
public Member2 getMember() {
Member2 cloned = null;
try {
cloned=(Member2) clone();
}catch(CloneNotSupportedException e) {
}
return cloned;
}
}
public class Member2Ex1 {
public static void main(String[] args) {
//Member2 인스턴스 객체 생성
Member2 original = new Member2("홍길동",50,new int[] {80,90,100},new Car("소나타"));
Member2 cloned = original.getMember();
cloned.scores[1]=76; //
cloned.car.model="그랜저"; //
cloned.age=30;
//원본 객체 출력
System.out.println("[원본 객체]");
System.out.println("이름 : "+original.name);
System.out.println("나이 : "+original.age);
System.out.println("국어 : "+original.scores[0]);
System.out.println("영어 : "+original.scores[1]);
System.out.println("수학 : "+original.scores[2]);
System.out.println("모델 : "+original.car.model);
//복제 객체 출력
System.out.println("[복제 객체]");
System.out.println("이름 : "+cloned.name);
System.out.println("나이 : "+cloned.age);
System.out.println("국어 : "+cloned.scores[0]);
System.out.println("영어 : "+cloned.scores[1]);
System.out.println("수학 : "+cloned.scores[2]);
System.out.println("모델 : "+cloned.car.model);
}
}
//
[원본 객체]
이름 : 홍길동
나이 : 50
국어 : 80
영어 : 76
수학 : 100
모델 : 그랜저
[복제 객체]
이름 : 홍길동
나이 : 30
국어 : 80
영어 : 76
수학 : 100
모델 : 그랜저
=> 얕은 복제 시 참조타입은 원본도 변형됨 => 생성자에서 주소값 넘어가서
- 깊은 복제 (참조타입)
: 참조 객체도 새로 복제
clone() 메소드 오버라이드 & 참조객체 복제하는 코드 직접 작성 필수
public class Member2 implements Cloneable{
public String name;
public int age;
public int[] scores; //참조타입
public Car car; //참조타입
public Member2(String name, int age, int[] scores, Car car) {
this.name=name;
this.age=age;
this.scores=scores;
this.car=car;
}
@Override
protected Object clone() throws CloneNotSupportedException{
//기본타입 얕은 복제 (name, age)
Member2 cloned = (Member2)super.clone(); //복제된 객체 참조 얻어옴
//scores 깊은 복제
cloned.scores=Arrays.copyOf(this.scores, this.scores.length);
//car 깊은 복제
cloned.car=new Car(this.car.model);
return cloned;
}
public Member2 getMember() {
Member2 cloned = null;
try {
cloned=(Member2) clone();
}catch(CloneNotSupportedException e) {
}
return cloned;
}
}
public class Member2Ex1 {
public static void main(String[] args) {
//Member2 인스턴스 객체 생성
Member2 original = new Member2("홍길동",50,new int[] {80,90,100},new Car("소나타"));
Member2 cloned = original.getMember();
cloned.scores[1]=76;
cloned.car.model="그랜저";
cloned.age=30;
//원본 객체 출력
System.out.println("[원본 객체]");
System.out.println("이름 : "+original.name);
System.out.println("나이 : "+original.age);
System.out.println("국어 : "+original.scores[0]);
System.out.println("영어 : "+original.scores[1]);
System.out.println("수학 : "+original.scores[2]);
System.out.println("모델 : "+original.car.model);
//복제 객체 출력
System.out.println("[복제 객체]");
System.out.println("이름 : "+cloned.name);
System.out.println("나이 : "+cloned.age);
System.out.println("국어 : "+cloned.scores[0]);
System.out.println("영어 : "+cloned.scores[1]);
System.out.println("수학 : "+cloned.scores[2]);
System.out.println("모델 : "+cloned.car.model);
}
}
//
[원본 객체]
이름 : 홍길동
나이 : 50
국어 : 80
영어 : 90
수학 : 100
모델 : 소나타
[복제 객체]
이름 : 홍길동
나이 : 30
국어 : 80
영어 : 76
수학 : 100
모델 : 그랜저
String 클래스
- charAt : 입력한 숫자 위치의 String값을 char로 변환
공백도 숫자에 포함됨
public static void main(String[] args) {
//String str = new String("자바프로그래밍");
String str = "자바프로그래밍";
char ch = str.charAt(5); //다섯번째 문자
System.out.println(ch);
}
//
래
public static void main(String[] args) {
String ssn = "980101-1234567";
char a = ssn.charAt(7);
if (a=='1'||a=='3') {
System.out.println("남");
}else if (a=='2'||a=='4') {
System.out.println("여");
}else {
System.out.println("주민번호 오류");
}
}
//남
- indexof : 입력한 문자열이 시작하는 위치 반환
찾는 문자열이 존재하지 않으면 -1 반환
public static void main(String[] args) {
String str = "자바 프로그래밍";
int index = str.indexOf("자바");
System.out.println(index);
}
//
0
- length : 공백 포함된 문자열의 길이
String str = "오늘 코로나 확진자 명단";
System.out.println(str.length());
//
13
- getBytes : 바이트 크기 구함
public static void main(String[] args) {
String str = "korea";
System.out.println(str.length());
byte[] bytes = str.getBytes(); //
System.out.println(bytes.length);
}
//
5
5
public static void main(String[] args) {
String str = "안녕하세요";
System.out.println(str.length());
byte[] bytes = str.getBytes(); //
System.out.println(bytes.length);
}
//
5
10
※
영문 1글자 1byte
한글 1글자 2byte
(length에 반영 X)
- replace : 입력 문자열 a를 입력 문자열 b로 바꿈
String str = "지금은 자바의 API에 대해 배우고 있습니다. 자바는 풍부한 라이브러리를 제공합니다.";
String newStr = str.replace("자바", "Java");
System.out.println(str);
System.out.println(newStr);
//
지금은 자바의API에 대해 배우고 있습니다. 자바는 풍부한 라이브러리를 제공합니다.
지금은 Java의 API에 대해 배우고 있습니다. Java는 풍부한 라이브러리를 제공합니다.
- substring(x) : 인덱스 x부터 문자열 출력 / substring(x,y) : 인덱스 x부터 y-1까지 출력
String str = "computer";
String sub1=str.substring(5);
String sub2=str.substring(2, 5);
System.out.println(sub1);
System.out.println(sub2);
//
ter
mpu
String ssn="920812-1234567";
String ssn2=ssn.replace(ssn.substring(7), "*******");
System.out.println(ssn2);
//
920812-*******
- toLowerCase : 영어를 전체 소문자로 변환 (cf. toUpperCase)
String original = "Java Programming";
String lower = original.toLowerCase();
System.out.println(lower);
//
java programming
String upper = original.toUpperCase();
System.out.println(upper);
//
JAVA PROGRAMMING
- trim : 문자 옆 공백 삭제
String str = " 자바 프로그래밍 ";
String newStr = str.trim();
System.out.println(newStr);
//
자바 프로그래밍
- valueOf : 숫자를 문자열로 변환
String str2 = String.valueOf(10);
System.out.println(str2);
//
10
StringTokenizer 클래스
: 특정 구분자(문자) 기준으로 문자열 분리
cf. String 클래스 split() => 정규 표현식으로 구분
public class StringTokenizerEx1 {
public static void main(String[] args) {
String str = "홍길동*김철수*이영희";
StringTokenizer st = new StringTokenizer(str, "*");
int countTokens = st.countTokens(); //남아있는 토큰 수
for(int i=0;i<countTokens;i++) {
String name=st.nextToken(); //토큰 하나씩 꺼냄
System.out.println(name);
}
}
}
//
홍길동
김철수
이영희
public class StringTokenizerEx1 {
public static void main(String[] args) {
String str = "홍길동*김철수*이영희";
StringTokenizer st = new StringTokenizer(str, "*");
while(st.hasMoreTokens()) { //남아있는 토큰이 있는지 여부
String name = st.nextToken();
System.out.println(name);
}
}
}
//
홍길동
김철수
이영희
public class StringTokenizerEx1 {
public static void main(String[] args) {
String str = "홍길동#김철수*이영희";
StringTokenizer st = new StringTokenizer(str, "#|*");
int countTokens = st.countTokens();
for(int i=0;i<countTokens;i++) {
String name=st.nextToken();
System.out.println(name);
}
}
}
- String 클래스 split()
public class SplitEx1 {
public static void main(String[] args) {
String text = "김철수,이영희,홍길동,박찬호,이영표";
String[] names = text.split(",");
System.out.println(names[1]);
}
}
//
이영희
public class SplitEx1 {
public static void main(String[] args) {
String text = "김철수,이영희,홍길동,박찬호,이영표";
String[] names = text.split(",");
for (String na:names) {
System.out.println(na);
}
}
}
//
김철수
이영희
홍길동
박찬호
이영표
StringBuilder 클래스 (멀티스레드 환경 => StringBuffer 클래스)
: 문자열 변경
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("java ");
sb.append("Pregram Study");
System.out.println(sb);
sb.insert(12, "ming"); //12번째 위치에 문자열 대입
System.out.println(sb);
sb.setCharAt(7, 'o'); //7번째 위치 문자 변경
System.out.println(sb); //묵시적 호출(Object 클래스는 내부적으로 오버라이딩하고 있음)
sb.replace(5, 16, "API"); //5~15번째 문자열 대체
System.out.println(sb.toString());
sb.delete(4, 8);
System.out.println(sb.toString());
System.out.println("총 글자수 : "+sb.length());
String result = sb.toString(); //명시적 호출, 버퍼에 있는 것을 String타입으로 변환
System.out.println(result);
}
//
java Pregram Study
java Pregramming Study
java Programming Study
java API Study
java Study
총 글자수 : 10
java Study
정규 표현식
[] : 한 개의 문자 ([abc]: abc 중 하나 / [^abc]: abc 제외한 하나 / [a-zA-Z]: a~z, A~Z 중 하나)
\d : 한 개의 숫자 (=[0-9])
\s : 공백
\w : 한 개의 알파벳 또는 한개의 숫자 (=[a-zA-Z_0-9])
? : 없음 또는 한개
* : 없음 또는 한개 이상
+ : 한개 이상
{n} : 정확히 n개
{n,} : 최소한 n개
{n,m} : n개에서부터 m개까지
() : 그룹핑 ex. (010|02) : 010 또는 02
\. : .
. : 한 개의 문자
Pattern 클래스
- matches() : 문자열을 정규표현식으로 검증
Pattern.matches(정규식, 검증할 문자열);
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String regExp="(02|010)-\\d{3,4}-\\d{4}";
System.out.print("전화번호 입력>> ");
String tel = sc.next();
boolean result = Pattern.matches(regExp, tel); //(정규식,검증할 문자열)
if (result) {
System.out.println("올바른 전화번호");
}else {
System.out.println("전화번호 형식이 틀림");
}
System.out.print("이메일 입력>> ");
String email = sc.next();
regExp = "\\w+@\\w+\\.\\w+";
boolean result2 = Pattern.matches(regExp, email);
if (result2) {
System.out.println("올바른 이메일");
}else {
System.out.println("이메일 형식이 틀림");
}
}
※ replaceAll() : 정규표현식 검사 후 대체
String intro ="내 나이는 25세이다.";
String newintro = intro.replaceAll("[0-9]", "*");
System.out.println(newintro);
//
내 나이는 **세이다.
String hello="안녕하세요. 반가워요. 잘 가세요.";
String newHello=hello.replaceAll(".", "^^"); //정규표현식으로 인식
System.out.println(newHello);
//
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
String hello="안녕하세요. 반가워요. 잘 가세요.";
String newHello=hello.replace(".", "^^"); //문자로 인식
System.out.println(newHello);
//
안녕하세요^^ 반가워요^^ 잘 가세요^^
Arrays 클래스
- sort() : 배열 정렬
public static void main(String[] args) {
int[] scores = {50,90,70,80,88};
Arrays.sort(scores); //
for (int i=0;i<scores.length;i++) {
System.out.println(scores[i]);
}
String[] names = {"다","티","공"};
Arrays.sort(names); //
for (int i=0;i<names.length;i++) {
System.out.println(names[i]);
}
}
//
50
70
80
88
90
공
다
티
- binarySearch() : 배열 내 입력문자 위치 찾아줌
public static void main(String[] args) {
int[] scores = {96,80,90,60,70};
int index=Arrays.binarySearch(scores, 60);
System.out.println(index);
}
//
-1 => sort 메소드 실행 안 할 때 오류
public static void main(String[] args) {
int[] scores = {96,80,90,60,70};
Arrays.sort(scores); //sort() 필수
int index=Arrays.binarySearch(scores, 60);
System.out.println(index);
}
//
0
Wrapper 클래스 (포장 클래스)
: 기본타입 값을 가지는 객체 생성 (기본타입 값을 내부에 두고 포장)
내부 기본타입 값 변경하려면 외부에서 변경 X 새로운 포장 객체 생성해야 함
- 박싱, 언박싱
박싱 : 기본타입 값을 포장 객체로 만듦 => 생성자 매개값으로 값 넘김
언박싱 : 포장 객체에서 기본타입 값 가져옴 => 기본타입명+Value() 메소드
//박싱
Integer obj1 = new Integer(10);
Integer obj2 = new Integer("20");
Integer obj3 = Integer.valueOf("30");
//언박싱
int value1 = obj1.intValue();
int value2 = obj2.intValue();
int value3 = obj3.intValue();
- 자동 박싱, 언박싱
자동 박싱 : 포장클래스 타입에 기본값 대입
자동 언박싱 : 기본 타입에 포장 객체 대입
Integer obj1 = new Integer(10);
int value = obj1; //자동 unboxing
Integer obj2=20; //자동 Boxing
System.out.println(obj2.intValue());
//
20
- 문자열 -> 기본타입 값 변환
String str1 = "20";
int value2 = Integer.parseInt(str1); //String -> int
System.out.println(value2);
String str2 = "2.54";
double value3 = Double.parseDouble(str2); //String -> double
System.out.println(value3);
//
20
2.54
- 내부 값 비교
==, != 연산자로 내부 값 비교 불가 (boolean, char, byte, short, int(-128~127)는 가능)
-> 내부값 아닌 포장 객체 참조값 비교하게 되기 때문
-> equals() 메소드 사용
Math 클래스
int value1=Math.abs(-5); //절대값
System.out.println(Math.sqrt(16)); //루트값
double dvalue1=Math.round(-5.5); //반올림값
System.out.println("반올림 "+dvalue1);
double dvalue2=Math.ceil(-5.5); //올림값
System.out.println("올림 "+dvalue2);
double dvalue3=Math.floor(-5.5); //내림값
System.out.println("내림 "+dvalue3);
double dvalue4=Math.rint(-5.5); //가까운 정수의 실수값
System.out.println("가까운 정수의 실수값 "+dvalue4);
//
5
4.0
반올림 -5.0 //음수 .5 => 더 큰 값으로 올림
올림 -5.0
내림 -6.0
가까운 정수의 실수값 -6.0 //가까운 값으로
int max = Math.max(30, 15);
System.out.println(max);
//
30
Random 클래스
boolean, int, long, float, double 난수 얻을 수 있음
종자값(seed) 설정 가능 => 같은 종자값이면 같은 난수 고정적으로 가짐
cf. Math.random() => 0.0~1 사이의 double 난수만 얻기 가능, 종자값 無
Random rand = new Random();
for (int i=1;i<=6;i++) {
System.out.println(rand.nextInt(45)+1); //난수 리턴
}
//
32
16
31
25
21
26
Random rand = new Random(8); //괄호 안 숫자=종자값 => 같은 난수 계속 얻음
for (int i=1;i<=6;i++) {
System.out.println(rand.nextInt(45)+1);
}
//
20
17
11
17
43
24
=> 고정된 난수값
- 로또 번호-내 번호 비교 후 결과 리턴 ex (Random 클래스, 종자값 사용)
public class MathEx2 {
public static void main(String[] args) {
int[] lotto=new int[6]; //배열 6슬롯 생성
int[] myNum=new int[6];
Random rand;
rand=new Random(10); //종자값
System.out.print("추첨 번호 : ");
for (int i=0;i<lotto.length;i++) {
lotto[i]=rand.nextInt(45)+1; //1~45 랜덤 리턴
System.out.print(lotto[i]+" ");
}
rand=new Random(5); //종자값 일치시키면 동일 난수값 출력됨
System.out.print("\n내 번호 : ");
for (int i=0;i<myNum.length;i++) {
myNum[i]=rand.nextInt(45)+1;
System.out.print(myNum[i]+" ");
}
Arrays.sort(lotto);
Arrays.sort(myNum);
boolean result = Arrays.equals(lotto, myNum);
System.out.println("\n\n***추첨 결과***\n");
if (result) {
System.out.println("1등에 당첨되셨습니다");
}else {
System.out.println("꽝");
}
}
}
Date 클래스
public static void main(String[] args) {
Date now = new Date(); //인스턴스 객체 생성
System.out.println(now);
SimpleDateFormat sdf; //Format 클래스
sdf=new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(now));
sdf=new SimpleDateFormat("yyyy년 MM월 dd일 (E요일)");
System.out.println(sdf.format(now));
sdf=new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초(S)");
System.out.println(sdf.format(now));
sdf=new SimpleDateFormat("yyyy년 MM월 dd일 a HH시 mm분 ss초");
System.out.println(sdf.format(now));
sdf=new SimpleDateFormat("yyyy년 D일째 W주차");
System.out.println(sdf.format(now));
sdf=new SimpleDateFormat("yyyy년 w주차");
System.out.println(sdf.format(now));
}
//
Fri May 13 17:38:08 KST 2022
2022-05-13
2022년 05월 13일 (금요일)
2022년 05월 13일 05시 38분 08초(232) // S : 1/1000초
2022년 05월 13일 오후 17시 38분 08초
2022년 133일째 2주차 //W : 해당 월의 현재 주차 //w : 올해년도 중 현재 주차
2022년 20주차
Calendar 클래스
추상 클래스 => 직접 객체 생성 불가 => getInstance() 메소드 사용 (싱글톤과 유사)
public static void main(String[] args) {
Calendar now = Calendar.getInstance();
//Calendar: 싱글톤& getinstance: static 메소드 (클래스로 바로 접근)
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH)+1; //월은 0부터 시작
int day = now.get(Calendar.DAY_OF_MONTH);
int week=now.get(Calendar.DAY_OF_WEEK); //일요일: 1
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
int second= now.get(Calendar.SECOND);
switch(week) {
case Calendar.SUNDAY:
System.out.println("오늘은 일요일");
break;
case Calendar.MONDAY:
System.out.println("오늘은 월요일");
break;
case Calendar.TUESDAY:
System.out.println("오늘은 화요일");
break;
case Calendar.WEDNESDAY:
System.out.println("오늘은 수요일");
break;
case Calendar.THURSDAY:
System.out.println("오늘은 목요일");
break;
case Calendar.FRIDAY:
System.out.println("오늘은 금요일");
break;
case Calendar.SATURDAY:
System.out.println("오늘은 토요일");
break;
}
System.out.println(year+"년 "+month+"월 "+day+"일");
int amPm = now.get(Calendar.AM_PM); //0:am 1:pm
String strAmPm;
if (amPm==0) { //(amPm==Calendar.AM) 도 가능 //AM은 상수
strAmPm="오전 ";
}else {
strAmPm="오후 ";
}
System.out.println(strAmPm+hour+"시 "+minute+"분 "+second+"초");
Calendar calNow = Calendar.getInstance();
year=now.get(Calendar.YEAR);
month = now.get(Calendar.MONTH)+1;
day = now.get(Calendar.DAY_OF_MONTH);
hour = now.get(Calendar.HOUR);
minute = now.get(Calendar.MINUTE);
System.out.println(calNow);
System.out.println(year+"년 "+month+"월 "+day+"일 "+hour+"시 "+minute+"분 ");
}
//
오늘은 금요일
2022년 5월 13일
오후 6시 8분 43초
java.util.GregorianCalendar[time=1652440061077,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Seoul",offset=32400000,dstSavings=0,useDaylight=false,transitions=30,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=4,WEEK_OF_YEAR=20,WEEK_OF_MONTH=2,DAY_OF_MONTH=13,DAY_OF_YEAR=133,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=7,SECOND=41,MILLISECOND=77,ZONE_OFFSET=32400000,DST_OFFSET=0]
2022년 5월 13일 8시 7분
- Timezone
public static void main(String[] args) {
String[] timeZoneID = TimeZone.getAvailableIDs(); //timezone id 다 가져옴
for (String id: timeZoneID) {
System.out.println(id);
}
}
//
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
~
public static void main(String[] args) {
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
Calendar calNow = Calendar.getInstance(tz);
year=calNow.get(Calendar.YEAR);
month = calNow.get(Calendar.MONTH)+1;
day = calNow.get(Calendar.DAY_OF_MONTH);
hour = calNow.get(Calendar.HOUR);
minute = calNow.get(Calendar.MINUTE);
amPm = calNow.get(Calendar.AM_PM);
if (amPm==Calendar.AM) {
strAmPm="오전 ";
}else {
strAmPm="오후 ";
}
System.out.println(year+"년 "+month+"월 "+day+"일 "+strAmPm+hour+"시 "+minute+"분 ");
}
//
2022년 5월 13일 오전 4시 11분
※상수 AM
class Calendar {
static final int AM=0;
}
Format 클래스
1. DecimalFormat (숫자형식 클래스)
0 | 10진수 (빈자리 0으로 채움) | 0 0.0 0000000000.00000 |
1234568 1234567.9 0001234567.89000 |
# | 10진수 (빈자리 채우지 않음) | # #.# ##########.##### |
1234568 1234567.9 1234567.89 |
. | 소수점 | #.0 | 1234567.9 |
- | 음수 | +#.0 -#.0 |
+1234567.9 -1234567.9 |
, | 단위 구분 | #,###.0 | 1,234,567.0 |
E | 지수 | 0.0E0 | 1.2E6 |
; | 양수, 음수 구분 | +#,###;-#,### | +1,234,568 -1,234,568 |
public static void main(String[] args) {
double dnum = 5123.2634;
DecimalFormat df;
df = new DecimalFormat("0.00");
// 0 : 지정된 자리수만 적용됨 (입력값이 더 크면 앞자리에 0 채워짐, 강제성 있음)
System.out.println(df.format(dnum));
int num1=7560000;
df=new DecimalFormat("#,###원");
//# : 유동적 (네자리 넘으면 패턴 반복시키고, 네자리 보다 작으면 형식 미지정)
System.out.println(df.format(num1));
double dnum2=0.1;
df=new DecimalFormat("##.0%");
System.out.println(df.format(dnum2));
}
//
5123.26
7,560,000원
10.0%
2. SimpleDateFormat (날짜형식 클래스)
=> Date 클래스 예제 참고
3. MessageFormat (문자열형식 클래스)
public static void main(String[] args) {
String id = "hong";
String name = "홍길동";
String tel = "010-1234-5678";
String text = "회원ID : {0} \n회원이름 : {1} \n전화번호 : {2}";
String result = MessageFormat.format(text, id,name,tel,text); //출력할 문자열,0,1,2
System.out.println(result);
text="{0}회원님 오늘 부탁하신 제품은 {0}회원님이 원하신 제품이 아니라";
result=MessageFormat.format(text, name);
System.out.println(result);
}
//
회원ID : hong
회원이름 : 홍길동
전화번호 : 010-1234-5678
홍길동회원님 오늘 부탁하신 제품은 홍길동회원님이 원하신 제품이 아니라
Java.time 패키지
public class DateTimeEx1 {
public static void main(String[] args) {
//날짜
LocalDate currentDate = LocalDate.now(); //현재
System.out.println("오늘은 "+currentDate);
LocalDate EndDate = LocalDate.of(2022, 12, 5); //특정 년월일
System.out.println("수료일자: "+EndDate);
int year = currentDate.getYear();
int month = currentDate.getMonthValue();
int day = currentDate.getDayOfMonth();
if (currentDate.isLeapYear()) { //윤년 여부 판단
System.out.println("올해는 윤년: 2월 29일까지");
}else {
System.out.println("올해는 평년: 2월 30일까지");
}
System.out.println(year+"년 "+month+"월 "+day+"일");
//시간
LocalTime currentTime = LocalTime.now();
System.out.println("지금 시간은 "+currentTime);
LocalTime endTime = LocalTime.of(21, 40);
System.out.println("수업 종료 시간: "+endTime);
//날짜와 시간
LocalDateTime currentDT = LocalDateTime.now();
System.out.println("현재 날짜와 시간 : "+currentDT);
LocalDateTime endDT = LocalDateTime.of(2022,12,5,21,40); //특정 날짜와 시간
System.out.println("수료 날짜와 시간 : "+endDT);
ZonedDateTime zdate = ZonedDateTime.now(ZoneId.of("Canada/Eastern"));
System.out.println("캐나다 시간존 : "+zdate);
}
}
//
오늘은 2022-05-13
수료일자: 2022-12-05
올해는 평년: 2월 30일까지
2022년 5월 13일
지금 시간은 19:45:32.244469300
수업 종료 시간: 21:40
현재 날짜와 시간 : 2022-05-13T20:24:16.500247500
수료 날짜와 시간 : 2022-12-05T21:40
캐나다 시간존 : 2022-05-13T07:26:39.113367900-04:00[Canada/Eastern]
'Programming > 자바' 카테고리의 다른 글
자바 재정리 - 제네릭 (0) | 2022.09.08 |
---|---|
자바 재정리 - 멀티 스레드 (0) | 2022.09.07 |
자바 재정리 - 예외 처리 (0) | 2022.08.26 |
자바 재정리 - 중첩 클래스, 중첩 인터페이스 (0) | 2022.08.26 |
자바 재정리 - 인터페이스 (0) | 2022.08.25 |