nme.kr

문서의 이전 판입니다!


Ch.12 기본 API

java.lang 패키지

Object 클래스

:wr:equals() 메서드

public boolean equals(Object obj){
      return (this == obj);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package chapter12;
 
public class EqualsEx {
 
    public static void main(String[] args) {
        Obj obj1 = new Obj(100);
        Obj obj2 = new Obj(100);
         
        if (obj1.equals(obj2)) {
            System.out.println("obj1 객체와 obj2 객체는 같음");
        } else {
            System.out.println("obj1 객체와 obj2 객체는 다름");
        }
         
        Obj obj3 = obj1;
         
        if (obj1.equals(obj3)) {
            System.out.println("obj1 객체와 obj3 객체는 같음");
        } else {
            System.out.println("obj1 객체와 obj3 객체는 다름");
        }
         
        ObjOverride objo1 = new ObjOverride(100);
        ObjOverride objo2 = new ObjOverride(100);
         
        if (objo1.equals(objo2)) {
            System.out.println("objo1 객체와 objo2 객체는 같음");
        } else {
            System.out.println("objo1 객체와 objo2 객체는 다름");
        }
    }
}
 
class Obj {
    int obj_var;
     
    Obj(int obj_var) {
        this.obj_var = obj_var;
    }
}
 
class ObjOverride {
    int obj_var;
     
    ObjOverride(int obj_var) {
        this.obj_var = obj_var;
    }
     
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof ObjOverride) {
            return true;
        } else {
            return false;
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package chapter12;
 
public class EqualsEx2 {
 
    public static void main(String[] args) {
         
        String str1 = new String("abc");
        String str2 = new String("abc");
         
        if(str1 == str2) {
            System.out.println("str1 객체와 str2 객체는 같음");
        } else {
            System.out.println("str1 객체와 str2 객체는 다름");
        }
         
        if(str1.equals(str2)) {
            System.out.println("str1 문자열과 str2 문자열은 같음");
        } else {
            System.out.println("str1문자열과  str2 문자열은 다름");
        }
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter12;
 
public class HahsCodeEx {
 
    public static void main(String[] args) {
         
        String str1 = new String( "abc");
        String str2 = new String( "abc");
        System.out.println("str1.hashCode():"+str1.hashCode()) ;
        System.out.println("str2.hashCode():"+str2.hashCode()) ;
        System.out.println("System.identityHashCode(str1):"+
                            System.identityHashCode(str1)) ;
        System.out.println("System.identityHashCode(str2):"+
                            System.identityHashCode(str2)) ;
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package chapter12;
 
public class HashCodeEx2 {
 
    public static void main(String[] args) {
         
        Hash v1 = new Hash(20);
        Hash v2 = new Hash(20);
        System.out.println(v1.hashCode());
        System.out.println(v2.hashCode());
        System.out.println ("v1 객체 진짜 해쉬값 :"+System.identityHashCode(v1));
        System.out.println ("v2 객체 진짜 해쉬값 :"+System.identityHashCode(v2));
 
    }
 
}
 
class Hash {
    int value;
    Hash(int value) {
        this.value = value;
    }
    @Override
    public boolean equals(Object obj) {
        if(obj instanceof Hash) {
            Hash v = (Hash)obj;
            return value == v.value;
        } else {
            return false;
        }
    }
    @Override
    public int hashCode() {
        return value;
    }
}

public String toString(){
     return getClass().getName()+ "@" + integer.toHexString(hashCode));
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter12;
 
public class ToStringEx {
 
    public static void main(String[] args) {
        Fruit f = new Fruit("사과", "빨강");
        System.out.println(f);
    }
}
 
class Fruit {
    String name;
    String color;
    public Fruit(String name, String color) {
        this.name = name;
        this.color = color;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chapter12;
 
public class ToStringEx2 {
 
    public static void main(String[] args) {
        Fruit2 f = new Fruit2("사과", "빨강");
        System.out.println(f);
    }
}
 
class Fruit2 {
    String name;
    String color;
    public Fruit2(String name, String color) {
        this.name = name;
        this.color = color;
    }
     
    @Override
    public String toString() {
        return "과일 이름 : "+this.name+"\n과일 색상 : "+this.color;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package chapter12;
 
import java.util.Date;
 
public class ToStringDateEx {
 
    public static void main(String[] args) {
         
        Date now = new Date();
        System.out.println(now);
 
    }
 
}

:wr:clone() 메서드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package chapter12;
 
public class ClonEx {
 
    public static void main(String[] args) {
         
        String[] arr = {"홍길동", "이순신", "김유신", "안중근"};
        String[] arr2 = arr.clone();
         
        System.out.println(arr == arr2);
        for (String v : arr2) {
            System.out.println(v);
        }
         
        String[] arr3 = new String[arr.length];
        System.arraycopy(arr, 0, arr3, 0, arr.length);
         
        System.out.println(arr == arr3);
        for (String v : arr3) {
            System.out.println(v);
        }
 
    }
 
}

System 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
package chapter12;
 
public class PropertyEx {
 
    public static void main(String[] args) {
         
        for (String var : System.getenv().keySet()) {
            System.out.println(var + "=" + System.getenv(var));
        }
 
    }
 
}

Class 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chapter12;
 
public class ClassEx {
 
    public static void main(String[] args) {
         
        EnvEx env = new EnvEx();
         
        // 객체를 이용해서 생성
        Class c1 = env.getClass();
        System.out.println(c1.getName());
         
        // 문자열 주소로 생성
        try {
            Class c2 = Class.forName("chapter12.PropertyEx");
            System.out.println(c2.getName());
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
 
    }
 
}

String 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter12.string;
 
public class StringEx {
 
    public static void main(String[] args) {
         
        int score = 90;
        System.out.println("당신의 점수는 " + score + "입니다."); // 자동형변환
         
        //String s = score; // 데이터타입이 달라 에러
        String s = String.valueOf(score); // String으로 형변환
         
        String s2 = score + ""; // 문자열을 + 연산하여 String으로 형변환
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package chapter12.string;
 
public class StringEx3 {
 
    public static void main(String[] args) {
         
        String sum = "";
         
        for (int i=1; i<=5; i++) {
            sum += i;
        }
        System.out.println(sum);
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package chapter12.string;
 
public class StringEx2 {
 
    public static void main(String[] args) {
         
        String name1 = "홍길동";
        String name2 = "홍길동";
         
        if (name1 == name2) {
            System.out.println("name1 == name2");
        } else {
            System.out.println("name1 != name2");
        }
         
        if (name1.equals(name2)) {
            System.out.println("name1.equals(name2)");
        } else {
            System.out.println("!name1.equals(name2");
        }
         
        String name3 = new String("홍길동");
        String name4 = new String("홍길동");
         
        if (name3 == name4) {
            System.out.println("name3 == name4");
        } else {
            System.out.println("name3 != name4");
        }
         
        if (name3.equals(name4)) {
            System.out.println("name3.equals(name4)");
        } else {
            System.out.println("!name3.equals(name4");
        }
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter12.string;
 
public class StringEx4 {
 
    public static void main(String[] args) {
         
        String text = "Hello My Name is Hong Gil Dong";
         
        System.out.println("0번 인덱스 : "+text.charAt(0));
         
        for (int i=0; i<text.length(); i++) {
            System.out.println(text.charAt(i));
        }
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package chapter12.string;
 
public class StringEx5 {
     
    static String s1;
    static String s2 = "";
 
    public static void main(String[] args) {
         
        System.out.println(s1);
        System.out.println(s2);
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package chapter12.string;
 
public class StringEx6 {
     
    public static void main(String[] args) {
         
        String s1 = "";
         
        System.out.println("s1.length():"+s1.length());
        System.out.println("".equals(s1));
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package chapter12.string;
 
public class StringEx7 {
     
    public static void main(String[] args) {
         
        String str = "Hello My Name is Hong Gil Dong";
         
        System.out.println(str.charAt(6)); // 6번 인덱스의 문자
        System.out.println(str.equals("Hello My Name is Hong Gil Dong")); // 문자열값 비교
        System.out.println(str.indexOf("Hong")); // "Hong" 문자열의 위치
        System.out.println(str.indexOf('H')); // 'H'문자의 위치
        System.out.println(str.substring(17)); // 17번 인덱스부터 끝까지 잘라냄
        System.out.println(str.substring(6, 13)); // 6번 인덱스부터 13전(12번 인덱스)까지 문자열
        System.out.println(str.toLowerCase()); // 소문자로 변경
        System.out.println(str.toUpperCase()); // 대문자로 변경
        System.out.println(str.length()); // 문자열의 길이
        System.out.println(str.startsWith("Hello")); // "Hello"으로 시작하는지 여부
        System.out.println(str.endsWith("Dong")); // "Dong"으로 끝나는지 여부
        System.out.println(str.replace("Hong", "Kim")); // "Hong"을 "Kim"으로 치환
        System.out.println(str.replaceAll("Name", "NickName")); // "Name"을 "NickName"으로 치환
        System.out.println(str.toString());
         
        str = "   안녕 하세요,     반갑습니다.      ";
        System.out.println(str.trim()); // 앞뒤 공백 제거
        // 모든 공백을 제거하는 방법
        System.out.println(str.replace(" ", ""));
         
        str = String.valueOf(10); // 기본자료형 int를 문자열로 변환
        str = String.valueOf(10.5); // 기본자료형 double을 문자열로 변환
         
        str = "홍길동,이순신,유관순,안중근";
        String[] arr = str.split(","); // ,를 구분자로 나눠서 배열로 리턴
        for (int i=0; i<arr.length; i++) {
            System.out.println(i+"번 인덱스 값 = "+arr[i]);
        }
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package chapter12.string;
 
public class StringEx8 {
     
    public static void main(String[] args) {
         
        String[] str = {"1", "2", "3", "4"};
         
        int sum1 = 0;
        for (int i=0; i<str.length; i++) {
            sum1 += Integer.parseInt(str[i]);
        }
        System.out.println("sum1 = "+sum1);
         
        long sum2 = 0;
        for (int i=0; i<str.length; i++) {
            sum2 += Long.parseLong(str[i]);
        }
        System.out.println("sum2 = "+sum2);
         
        double sum3 = 0;
        for (int i=0; i<str.length; i++) {
            sum3 += Double.parseDouble(str[i]);
        }
        System.out.println("sum3 = "+sum3);
 
    }
 
}

String Buffer, StringBuilder 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter12.stringbuffer;
 
public class StringEx9 {
     
    public static void main(String[] args) {
         
        String str1 = "abcd";
        String str2 = "abcd";
        System.out.println("str1 = "+System.identityHashCode(str1));
        System.out.println("str2 = "+System.identityHashCode(str2));
         
        // 기본 객체에 + 연산 후 다시 대입
        str1 = str1 + "efg";
        System.out.println("str1 = "+System.identityHashCode(str1));
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter12.stringbuffer;
 
public class StringBufferEx {
 
    public static void main(String[] args) {
         
        StringBuffer sb1 = new StringBuffer("abcd");
        System.out.println("문자열 연결전 sb1 = "+System.identityHashCode(sb1));
        sb1.append("efgh");
        System.out.println("문자열 연결후 sb1 = "+System.identityHashCode(sb1));
         
        System.out.println(sb1.toString().equals("abcdefgh"));
         
         
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package chapter12.stringbuffer;
 
public class StringBufferEx2 {
 
    public static void main(String[] args) {
         
        StringBuffer sb = new StringBuffer();
         
        // 메서드 체이닝으로 여러 타입의 매개변수값을 StringBuffer 객체의 문자열값에 추가
        sb.append("abc").append(123).append('A').append(false);
        System.out.println(sb);
         
        // 2~3번 인덱스값 삭제
        sb.delete(2, 4);
        System.out.println(sb);
         
        // 4번 인덱스값 삭제
        sb.deleteCharAt(4);
        System.out.println(sb);
         
        // 5번 인덱스에 == 추가
        sb.insert(5,"==");
        System.out.println(sb);
         
        // 6번 인덱스에 1.23 추가(문자열로 변환)
        sb.insert(6,1.23);
        System. out.println(sb);
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package chapter12.stringbuffer;
 
public class StringBufferEx3 {
 
    public static void main(String[] args) {
 
        // 시작
        long start = System.currentTimeMillis();
 
        String str = "";
        for (int i=0; i<1000000; i++) {
            str += i;
        }
         
        // 끝
        long end = System.currentTimeMillis();
        System.out.println( "실행 시간 : " + ( end - start )/1000);
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chapter12.stringbuffer;
 
public class StringBufferEx4 {
 
    public static void main(String[] args) {
 
        // 시작
        long start = System.currentTimeMillis();
 
         
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<1000000; i++) {
            sb.append(i);
        }
         
         
        // 끝
        long end = System.currentTimeMillis();
        System.out.println( "실행 시간 : " + ( end - start )/1000);
 
    }
 
}

Math 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package chapter12;
 
public class MathEx {
 
    public static void main(String[] args) {
         
        System.out.println("Math.abs(10)=" + Math.abs(10));
        System.out.println("Math.abs(-10)=" + Math.abs(-10));
        System.out.println("Math.abs(3.1415)=" + Math.abs(3.1415));
        System.out.println("Math.abs(-3.1415)=" + Math.abs( 3.1415));
        System.out.println("Math.ceil(5.4)=" + Math.ceil(5.4));
        System.out.println("Math.ceil(-5.4)=" + Math.ceil(-5.4));
        System.out.println("Math.floor(5.4)=" + Math.floor(5.4));
        System.out.println("Math.floor(-5.4)=" + Math.floor(-5.4));
        System.out.println("Math.max(5,4)=" + Math.max(5,4));
        System.out.println("Math.max(5.4,5.3)=" + Math.max(5.4,5.3));
        System.out.println("Math.min(5,4)=" + Math.min(5,4));
        System.out.println("Math.min(5.4,5.3)=" + Math.min(5.4,5.3));
        System.out.println("Math.random()=" + Math. random());
        System.out.println("Math.rint(5.4)=" + Math.rint(5.4));
        System.out.println("Math.rint(-5.4)=" + Math.rint(-5.4));
        System.out.println("Math.round(5.4)=" + Math.round(5.4));
        System.out.println("Math.round(5.5)=" + Math.round(5.5));
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter12;
 
public class RoundEx {
 
    public static void main(String[] args) {
         
        // 원주율을 소수점 3자리로 반올림
        double v1 = Math.PI * 1000;
        double v2 = Math.round(v1);
        double v3 = v2 / 1000.0;
        System.out.println(v3);
         
        // 한줄로 출력
        System.out.println(Math.round(Math.PI * 1000)/1000.0);
 
    }
 
}

Wrapper 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package chapter12;
 
public class WrapperEx {
 
    public static void main(String[] args) {
         
        // 정수 10이 Integer 클래스 객체로 변환 (boxing)
        Integer i1 = new Integer(10);
        Integer i2 = new Integer(10);
        System.out.println("i1==i2 : " + (i1==i2));
        System.out.println("i1.equals(i2) : " + (i1.equals(i2)));
        System.out.println("i1.toString() : " + i1.toString());
         
        //i1 객체가 100 정수로 변환 (unboxing)
        System.out.println("i1==10 : " + (i1==10));
        int i3 = 10;
        System.out.println("i1==i3 : " + (i1==i3));
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter12;
 
public class WrapperEx2 {
 
    public static void main(String[] args) {
         
        System.out.println("정수의 최대값 :" + Integer.MAX_VALUE);
        System.out.println("정수의 최소값 :" + Integer.MIN_VALUE);
        System.out.println("byte의 최대값 :" + Byte.MAX_VALUE);
        System.out.println("byte의 최소값 :" + Byte.MIN_VALUE);
        System.out.println("정수의 사이즈 :" + Integer.SIZE);
        System.out.println("float의 사이즈 :" + Float.SIZE);
        System.out.println("double의 사이즈 :" + Double.SIZE);
 
    }
 
}

문자열을 숫자로 변환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package chapter12;
 
public class WrapperEx3 {
 
    public static void main(String[] args) {
         
        String number = "100";
         
        int i1 = Integer.parseInt(number);
        int i2 = new Integer(number).intValue();
        int i3 = Integer.valueOf(number);
         
        System.out.println("i1 = "+i1);
        System.out.println("i2 = "+i2);
        System.out.println("i3 = "+i3);
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package chapter12;
 
public class WrapperEx4 {
 
    public static void main(String[] args) {
         
        int i = 10;
         
        // 기본형을 참조형으로 형변환(형변환 생략가능)
        Integer intg = (Integer)i;
        // Integer intg = Integer.valueOf(i);
         
        Long lng = 10L; // Long lng = new Long (100L);
        int i2 = intg + 10; // 참조형과 기본형간의 연산 가능
        long l = intg + lng ; // 참조형 간의 덧셈 가능
        System.out.println("i2 = "+i2);
        System.out.println("l = "+l);
         
        Integer intg2 = new Integer(30);
        int i3 = (int) intg2; // 참조형을 기본형으로 형변환 (형변환 생략가능)
        System.out.println ("i3 : "+i3);
 
    }
 
}

java.util 패키지

Random 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chapter12;
 
import java.util.Random;
 
public class RandomEx {
 
    public static void main(String[] args) {
         
        Random r1 = new Random(42);
        Random r2 = new Random(42);
         
        System.out.println("r1");
        for (int i=0; i<5; i++) {
            System.out.println(i + "=" + r1.nextInt());
        }
        System.out.println("r2");
        for (int i=0; i<5; i++) {
            System.out.println(i + "=" + r2.nextInt());
        }
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter12;
 
import java.util.Random;
 
public class RandomEx2 {
 
    public static void main(String[] args) {
         
        Random rand = new Random();
         
        for (int i=0; i<5; i++) {
            System.out.println(rand.nextInt(6)+1);
        }
 
    }
 
}

Scanner 클래스

Scanner scan = new Scanner(System.in);
String input = scan.nextLine();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chapter12;
 
import java.util.Scanner;
 
public class ScannerEx {
 
    public static void main(String[] args) {
         
        Scanner scan = new Scanner(System.in);
         
        int cnt = 0;
        while(true) {
            System.out.println("이름을 입력하세요");
            String name = scan.nextLine();
            if("".equals(name)) break;
            System.out.println(name+"님 안녕하세요.");
            cnt++;
        }
        System.out.println("총 입력된 회원수 :"+cnt);
 
    }
 
}

Date 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package chapter12;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class DateEx {
 
    public static void main(String[] args) {
         
        Date now = new Date();
        System.out.println(now);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E a");
        System.out.println(sf.format(now));
         
        Calendar cal = Calendar.getInstance();
        Date d = new Date(cal.getTimeInMillis());
 
    }
 
}

Calendar 클래스

Calendar 객체를 Date로 변환

Calendar cal = Calendar.getInstance();
Date d = new Date(cal.getTimeInMillis());

Date 객체를 Calendar로 변환

Date d = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(d);

Calendar cal = Calendar.getInstance();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chapter12;
 
import java.util.Calendar;
 
public class CalendarEx {
 
    public static void main(String[] args) {
         
        Calendar today = Calendar.getInstance();
         
        System.out.println("올해 년도 :"+today.get(Calendar.YEAR));
        System.out.println("이번달 :" + (today.get(Calendar.MONTH)+1));
        System.out.println("년도기준 몇째주 :"+today.get(Calendar.WEEK_OF_YEAR));
        System.out.println("월기준 몇째주 :"+today.get(Calendar.WEEK_OF_MONTH));
        System.out.println("일자 :" + today.get(Calendar.DATE));
        System.out.println("일자 :" + today.get(Calendar.DAY_OF_MONTH));
        System.out.println("년도기준날짜 :"+today.get(Calendar.DAY_OF_YEAR));
        System.out.println("요일 (일)~ 토)):"+today.get(Calendar.DAY_OF_WEEK));
        System.out.println("월기준몇째요일 :" + today.get(Calendar.DAY_OF_WEEK_IN_MONTH));
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package chapter12;
 
import java.util.Calendar;
 
public class CalendarEx2 {
 
    public static void main(String[] args) {
         
        Calendar today = Calendar.getInstance();
         
        System.out.println("오전 (0) 오후 (1) :" + today.get(Calendar.AM_PM));
        System.out.println("시간 (0~11) :" + today.get(Calendar.HOUR));
        System.out.println("시간 (0~23) :" + today.get(Calendar.HOUR_OF_DAY));
        System.out.println("분 (0~59) :" + today.get(Calendar.MINUTE));
        System.out.println("초 (0~59) :" + today.get(Calendar.SECOND));
        System.out.println("밀리초 (0~999) :" + today.get(Calendar.MILLISECOND));
        System.out.println("Timezone(12~12):" + today.get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000));
        System.out.println("이번달의 마지막일자 :" + today.getActualMaximum(Calendar.DATE));
         
        Calendar cal = Calendar.getInstance();
        cal.set(2020, (6-1), 12);
        System.out.println("날짜 :" +
                        cal.get(Calendar.YEAR) + "년 " +
                        (cal.get(Calendar.MONTH) + 1) + "월 " +
                        cal.get(Calendar.DATE) + "일");
 
    }
 
}

Date 클래스 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package chapter12;
 
import java.util.Date;
 
public class CalendarEx3 {
 
    public static void main(String[] args) {
         
         
        // 현재일
        int sYear = 2020;
        int sMonth = 6;
        int sDay = 12;
         
        // 이전일
        int eYear = 2020;
        int eMonth = 6;
        int eDay = 1;
         
        Date sd = new Date();
        Date ed = new Date();
 
        sd.setYear(sYear);
        sd.setMonth(sMonth-1);
        sd.setDate(sDay);
         
        ed.setYear(eYear);
        ed.setMonth(eMonth-1);
        ed.setDate(eDay);
         
        long temp = (sd.getTime() - ed.getTime()) / (1000L*60L*60L*24L);
        int diff = (int)temp;
         
        System.out.println(diff + "일 경과");
 
    }
 
}

Calendar 클래스 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package chapter12;
 
import java.util.Calendar;
 
public class CalendarEx4 {
 
    public static void main(String[] args) {
         
         
        // 현재일
        int sYear = 2020;
        int sMonth = 6;
        int sDay = 12;
         
        // 이전일
        int eYear = 2020;
        int eMonth = 6;
        int eDay = 1;
         
        Calendar sCal = Calendar.getInstance();
        Calendar eCal = Calendar.getInstance();
        sCal.set(sYear, sMonth+1, sDay);
        eCal.set(eYear, eMonth+1, eDay);
         
        long diffSec = (sCal.getTimeInMillis() - eCal.getTimeInMillis()) / 1000;
         
        long diffDay = diffSec / (24*60*60);
         
        System.out.println(diffDay + "일 경과");
 
    }
 
}

GregorianCalendar 클래스 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package chapter12;
 
import java.util.Calendar;
import java.util.GregorianCalendar;
 
public class CalendarEx5 {
 
    public static void main(String[] args) {
         
         
        // 현재일
        int sYear = 2020;
        int sMonth = 6;
        int sDay = 12;
         
        // 이전일
        int eYear = 2020;
        int eMonth = 6;
        int eDay = 1;
         
//      Calendar sCal = Calendar.getInstance();
//      Calendar eCal = Calendar.getInstance();
//      sCal.set(sYear, sMonth+1, sDay);
//      eCal.set(eYear, eMonth+1, eDay);
        Calendar sCal = new GregorianCalendar(sYear, sMonth+1, sDay);
        Calendar eCal = new GregorianCalendar(eYear, eMonth+1, eDay);
         
        long diffSec = (sCal.getTimeInMillis() - eCal.getTimeInMillis()) / 1000;
         
        long diffDay = diffSec / (24*60*60);
         
        System.out.println(diffDay + "일 경과");
 
    }
 
}

Array 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package chapter12;
 
import java.util.Arrays;
 
public class ArraysEx {
 
    public static void main(String[] args) {
         
        String[] arr = {"홍길동", "이순신", "강감찬", "김유신"};
        Arrays.fill(arr, "임꺽정"); //
        for (String n : arr) System.out.print(n + ",");
        System.out.println();
        Arrays.fill(arr, 1, 3, "X");
        for (String n : arr) System.out.print(n + ",");
 
    }
 
}

java.text 패키지

DecimalFormat 클래스

숫자 포맷을 지정할 수 있는 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package chapter12;
 
import java.text.DecimalFormat;
 
public class DecimalFormatEx {
 
    public static void main(String[] args) {
         
        double[] scores = {90.555, 80.6666, 70.77777, 60.666666, 50.5};
         
        DecimalFormat df = new DecimalFormat("#,###.00");
         
        for (int i=0; i<scores.length; i++) {
            System.out.println(df.format(scores[i]));
        }
         
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter12;
 
import java.text.DecimalFormat;
 
public class DecimalFormatEx2 {
 
    public static void main(String[] args) {
         
        DecimalFormat df1 = new DecimalFormat("#,###.##");
        DecimalFormat df2 = new DecimalFormat("000,000");
         
        System.out.println(df1.format(5500));
        System.out.println(df2.format(5500));
 
    }
 
}

Simple date format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter12;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class SimpleDateFormatEx {
 
    public static void main(String[] args) {
 
        Date now = new Date();
        System.out.println(now);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy MM dd HH:mm:ss E a");
        System.out.println(sf.format(now));
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package chapter12;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class SimpleDateFormatEx3 {
 
    public static void main(String[] args) {
         
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = "2020-06-13";
         
        Date d = null;
        try {
            d = sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(d);
         
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd E요일");
        System.out.println(sf2.format(d));
 
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package chapter12;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class SimpleDateFormatEx2 {
 
    public static void main(String[] args) {
         
        // Calendar 와 Date 간의 변환은 다 음과 같이 한다 •
        Calendar cal = Calendar.getInstance() ;
        cal.set(2020, 5, 13); //2020 년 6 월 13 일 - 월은+1
        Date day = cal.getTime() ;
        SimpleDateFormat sdf1 , sdf2 , sdf3 , sdf4 ;
        sdf1 = new SimpleDateFormat ("yyyy-MM-dd" );
        sdf2 = new SimpleDateFormat ("yy-MM-dd E요일 " ) ;
        sdf3 = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS " ) ;
        sdf4 = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss a" ) ;
        System.out.println(sdf1.format(day));
        System.out.println(sdf2.format(day));
        System.out.println(sdf3.format(day)) ;
        System.out.println(sdf4.format(day));
 
    }
 
}

java.util.regex 패키지

정규표현식을 사용하기 위한 패키지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package chapter12;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ReEx {
 
    public static void main(String[] args) {
         
        // 소문자 b로 시작하는  알파벳 소문자 0개 이상 규칙
        Pattern p = Pattern.compile("b[a-z]*");
        Matcher m;
         
        // 문자열 bat 확인
        m = p.matcher("bat");
        System.out.println("bat = "+m.matches());
         
        // 문자열 cat 확인
        m = p.matcher("cat");
        System.out.println("cat = "+m.matches());
         
        // 문자열 bed 확인
        m = p.matcher("bed");
        System.out.println("bed = "+m.matches());
 
    }
 
}

1. Pattern 클래스의 static 메서드 copile에 정규표현식을 매개변수로 넣고 객체 생성 Pattern p = Pattern.copile(“b[a-z]*”);
2. Matcher 클래스를 이용해 생성한 패턴 책체의 matcher() 메서드의 매개변수로 비교할 대상 문자열을 넣어 Matcher 객체 생성
Matcher m;
m= p.matcher("bat");  
3. Matcher 객체에 amtchers() 메서드를 호출해 매칭이 되었는지(true) 안 되었는지(false) 판단 if (m.matchers()) {…}

정규 표현식에 사용되는 문자

정규 표현식으로 문자열검증

Pattern 클래스의 static 메서드 matches() 메서드 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package chapter12;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ReEx2 {
 
    public static void main(String[] args) {
         
        String[] patterns = {"." ,"[a-z]?","[0-9]+","0[1-9]*","^[0-9]",
                "[^0-9]","[a-z]*","[a-z]+","02|010" ,"\\s", "\\S" ,"\\d" ,"\\w","\\W"};
        String[] datas = {"bat","021231234","12345","011","bed","02","A","9","a","*"};
 
        for(String d : datas) {
            System.out.print(d+"문자와 일치하는 패턴 : ");
            for(String p : patterns) {
                Pattern pattern = Pattern.compile(p);
                Matcher m = pattern.matcher(d);
                if(m.matches()) {
                    System.out.print(p+", ");
                }
            }
            System.out.println();
        }
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package chapter12;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ReEx3 {
 
    public static void main(String[] args) {
         
        String source = "휴대폰번호:010-1111-1111, 집전화번호:02-1234-5678,"
                + "이메일주소:email@gmail.com 계좌번호:123-12-123456";
        String telpattern = "(0\\d{1,2})-(\\d{3,4})-(\\d{4})";
        String emailpattern = "(\\w+)@(\\w+).(\\w+)";
        String accountpattern = "(\\d{3})-(\\d{2})-(\\d{6})";
         
        Pattern p = Pattern.compile(telpattern);
        Matcher m = p.matcher(source);
         
        System.out.println("전화번호 : ");
        while(m.find()) { // 지정된 패턴 맞는 문자열을 검색
            System.out.println(m.group() + " : "
                        + m.group(1) + "," + m.group(2) + "," + m.group(3));
        }
         
        p = Pattern.compile(emailpattern);
        m = p.matcher(source);
        System.out.println("이메일 : ");
        while(m.find()) { // 지정된 패턴 맞는 문자열을 검색
            System.out.println(m.group() + " : "
                        + m.group(1) + "," + m.group(2) + "," + m.group(3));
        }
         
        p = Pattern.compile(accountpattern);
        m = p.matcher(source);
        System.out.println("계좌번호 : ");
        while(m.find()) { // 지정된 패턴 맞는 문자열을 검색
            System.out.println(m.group() + " : "
                        + m.group(1) + "," + m.group(2) + "," + m.group(3));
        }
         
    }
 
}