Post

Utility Class

✅ class 아쉬운 점 ➡️ 해결 방법

  1. 클래스 이용하려먼, 매번 인스턴스화를 해야 함 ➡️ static활용
  2. 비슷한 클래스를 생성하기 위해서는 extends해야 함 ➡️ Inner class
  3. 클래스를 한 번만 이용할 건데, 또 새로운 클래스를 정의해야 함 ➡️ Inner class

    클래스 안에 클래스, 메소드 안에 클래스 생성도 가능

✅ Utility Class

인스턴스화 하지 않고도 사용 가능한 클래스

  • Math
  • Arrays

우리가 Utility Class만들 수도 있음
static으로 모든 것을 정의하면, class loader 시작될 때 만들어지기 때문에 인스턴스화 하지 않고도 사용 가능!

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
58
59
//utils를 정의한 StringUtils.java
//static사용해서 util로 만든다.
public class StringUtils {
    //1. 문자열이 비어 있는지 확인
    //util이니까 static
    public static boolean isEmpty(String str){
        if(str.isEmpty()==true || str ==null){
        return true;
        } else{
            return false;
        }

    }
    //2. 문자열을 반대로 뒤집기
    public static String reverse(String str){
        StringBuilder sb= new StringBuilder();
        for(int i=str.length()-1; i>=0; i--){
            sb.append(str.charAt(i));
        }
        return sb.toString();
    }
    //3. 주어진 문자열에서 특정 문자의 개수 세기
    public static int countChar(String str, char target){
        int count=0;
        for(int i=0; i<str.length(); i++){
            if(str.charAt(i) == target){
                count++;
            }
        } return count;
    }
    //4. 주어진 문자열에 특정 문자가 있는지 확인
    public static boolean containChar(String str, char target) {
        return countChar(str, target) >= 1;

    }
}

//Main
//⭐️ StringUtils하고 method바로 불러와서 사용 가능하다는 것이 핵심
public class StringUtilsTest {
    public static void main(String[] args) {
        String str= "Hello, World";
        char target= 'o';

        //1. 문자열이 비어 있는지 확인
        boolean isEmpty= StringUtils.isEmpty(str); //false

        //2. 문자열을 반대로 뒤집기
        String reverseStr= StringUtils.reverse(str); //dlroW ,olleH

        //3. 주어진 문자열에서 특정 문자의 개수 세기
        int count= StringUtils.countChar(str, target); //2
        //4. 주어진 문자열에 특정 문자가 있는지 확인
        boolean isChar= StringUtils.containChar(str, target); //true

    }
}


This post is licensed under CC BY 4.0 by the author.