전공수업정리/Java

[JAVA]StringBuffer 클래스

킹대왕너구리 2024. 5. 16. 20:31

StringBuffer 클래스

-StringBuffer 클래스는 클래스를 문자열로 다룰 때 유용하게 사용되는 클래스 중 하나입니다.

-문자열을 수정할 수 있는 공간을 제공합니다.(가변성)

-문자열을 저장하기 위해 문자 배열을 사용합니다. 

-다양한 메소드를 지원합니다. append,insert,delete 등..

 

앞서 말한 String과의 차이는 무엇일까요?

-String은 불변한 문자열을 처리하기 위한 클래스인 반면, StringBuffer은 가변한 문자열을 처리하기 위한 클래스입니다.

-String은 새로운 객체를 생성하여 추가 및 변경이 되지만, StringBuffer은 기존의 객체로 추가 및 변경이 됩니다.

 

예제

public class StringBufferExample {
    public static void main(String[] args) {
        // StringBuffer 객체 생성
        StringBuffer sb = new StringBuffer("Hello");

        // 문자열 추가
        sb.append(" World");
        System.out.println(sb.toString());  // "Hello World"

        // 문자열 삽입
        sb.insert(5, ",");
        System.out.println(sb.toString());  // "Hello, World"

        // 문자열 삭제
        sb.delete(5, 6);
        System.out.println(sb.toString());  // "Hello World"

        // 특정 인덱스의 문자 변경
        sb.setCharAt(6, 'w');
        System.out.println(sb.toString());  // "Hello world"
    }
}

 


StringTokenizer 클래스

-StringTokenizer 클래스는 문자열을 특정 구분자를 사용하여 여러 토큰으로 분리할 수 있게 도와주는 유틸리티 클래스 입니다.

-java.util 패키지에 포함되어 있습니다.

즉 구분자, 예를 들면 공백이나 콤마를 기준으로 문자열을 토큰으로 분리할 수 있는 클래스라고 생각하면 됩니다.

 

StringTokenizer 클래스의 주요 메소드는 다음과 같습니다.

hasMoreTokens() - 더 읽은 토큰이 있는지 확인합니다.

nextToken()-다음 토큰을 반환합니다.

countTokens()-읽지 않은 토큰 수를 반환합니다.

 

import java.util.StringTokenizer;

public class StringTokenizerExample {
    public static void main(String[] args) {
        String data = "apple, banana, orange, grape";

        // 콤마와 공백을 구분자로 사용
        StringTokenizer st = new StringTokenizer(data, ", ");

        // 토큰이 더 있으면 출력
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            System.out.println(token);
        }
    }
}

 

Math 클래스

-기본적인 수학적 연산과 함수를 제공하는 클래스

-java.lang 패키지에 속해 있습니다.

-모든 메소드가 정적(static)이므로 'Math'클래스를 인스턴스 화 할 필요 없이 직접 호출하여 사용할 수 있습니다.

(예를 들어 Math 클래스의 sqrt 메소드를 사용한다고 한다면 Math 객체를 생성하지 않고 바로 Math.sqrt(25)와 같이 호출 할 수 있습니다.)

 

abs() - 절대값 반환

ceil()- 주어진 수 이상의 가장 작은 정수 double형으로 반환

floor()-주어진 수 이하의 가장 큰 정수를 double형으로 반환

max()-두 수 중 큰 값을 반환

min()-두 수 중 작은 값을 반환

pow()-첫번째 인자 기준 두번째 인자의 거듭제곱 값 반환 pow(a,b)==a^b

sqrt()-제곱근 반환

random()-0.0이상 1.0미만 임의의 double 값을 반환

 

public class MathExample {
    public static void main(String[] args) {
        // 최대값, 최소값
        System.out.println("Max of 10 and 20 is " + Math.max(10, 20));
        System.out.println("Min of 10 and 20 is " + Math.min(10, 20));

        // 절대값
        System.out.println("Absolute value of -15 is " + Math.abs(-15));

        // 거듭제곱
        System.out.println("3 raised to the power of 4 is " + Math.pow(3, 4));

        // 제곱근
        System.out.println("Square root of 25 is " + Math.sqrt(25));

        // 올림과 내림
        System.out.println("Ceil of 9.2 is " + Math.ceil(9.2));
        System.out.println("Floor of 9.8 is " + Math.floor(9.8));

        // 랜덤 값 생성
        System.out.println("Random number: " + Math.random());
    }
}

 

출력결과

Max of 10 and 20 is 20

Min of 10 and 20 is 10

Absolute value of -15 is 15

3 raised to the power of 4 is 81.0

Square root of 25 is 5.0

Ceil of 9.2 is 10.0

Floor of 9.8 is 9.0

Random number: 0.5612827201731544


Calendar 클래스

java.util 패키지에 포함되어 있습니다.

Java의 Calendar 클래스는 날짜와 시간을 관리하는 데 사용됩니다.

Calendar 클래스는 추상 클래스로 직접 인스턴스를 생성할 수 없습니다.

Calendar.getInsatance() 를 호출하여 시스템의 기본 시간대, locale( 사용자 인터페이스에서 사용되는 언어, 지역 설정, 출력 형식 등을 정의하는 문자열 ) 을 기준으로 Calendar 객체를 얻습니다.

 

주요 메소드

get(int field) - 특정 필드 값을 반환합니다. 특정 필드 값의 예시로 Calendar.YEAR, Calendar.MONTH 등이 있습니다.

set(int field,int value): 특정 필드에 값을 설정합니다.

add(int field, int amount): 특정 필드에 값을 더합니다.

roll(int field, boolean up): 특정 필드의 값을 증가시키거나 감소시킵니다. 다른 필드에는 영향을 주지 않습니다.

 

import java.util.Calendar;

public class CalendarExample {

	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();
		//현재 날짜 및 시간 출력
		System.out.println("Current Data and Time"+calendar.getTime());
		
		//현재 년도 출력
		int year = calendar.get(Calendar.YEAR);
		System.out.println("Year:"+year);
		//현재 월 출력(월은 0부터 시작하므로 +1해줘야함)
		int month=calendar.get(Calendar.MONTH);
		System.out.println("Month:"+(month+1));
		//일주일의 몇 번째 날인지 출력
		int dayOfWeek=calendar.get(Calendar.DAY_OF_WEEK);
		System.out.println("Day of Week:"+dayOfWeek);
		
		//5일 더하기
		calendar.add(Calendar.DATE,5);
		System.out.println("Date after 5 days:"+calendar.getTime());
		
		//한달 빼기
		calendar.add(Calendar.MONTH, -1);
		System.out.println("Date after subtracting a month: "+calendar.getTime());
		
		//일자 직접 설정
		calendar.set(Calendar.DATE, 1);
		System.out.println("Set to the first of the month:"+calendar.getTime());
		

	}

}

 

출력결과

Current Data and TimeThu May 16 20:28:09 KST 2024

Year:2024

Month:5

Day of Week:5

Date after 5 days:Tue May 21 20:28:09 KST 2024

Date after subtracting a month: Sun Apr 21 20:28:09 KST 2024

Set to the first of the month:Mon Apr 01 20:28:09 KST 2024