java.lang 패키지 클래스 활용

주8·2023년 1월 16일
0

Object 클래스

  • 모든 클래스의 최상위 클래스로 상속받은 클래스들은 Object 클래스의 메서드를 사용할 수 있다.
  • 상속 받는 클래스에서 필요에 따라 Object 클래스의 메서드를 오버라이딩 한다.
  • equals(), toString() 등은 오버라이딩해서 사용하는 편이며, notify(), notifyAll(), wait() 메서드는 Thread와 관련된 메서드다.
MethodDescription
public final native Class<?> getClass()객체의 Class 클래스의 객체를 반환한다. Class 클래스를 사용하여 해당 클래스의 메타데이터를 얻을 수 있다. (클래스의 필드, 메서드 정보 등)
public native int hashCode()객체 자신의 해시코드(객체를 식별하는 유일한 정수값)을 반환한다.
public boolean equals(Object obj)파라미터로 전달된 객체와 객체 자신(this)의 참조값을 비교해서 같으면 true를 반환한다.
protected native Object clone()이 객체의 복사본(복제)을 생성하고 반환한다.
public String toString()이 객체의 정보를 문자열로 반환한다.
public final native void notify()일시 중지 상태의 단일 스레드를 실행 대기 상태로 만든다.
public final native void notifyAll()일시 중지 상태의 모든 스레드를 실행 대기 상태로 만든다.
public final native void wait()다른 스레드가 notify 할 때까지 현재 스레드가 대기 상태로 빠지면서 일시중지된다.
protected void finalize()객체가 Garbage collection 되기 전에 Garbage collector에 의해 호출된다. Java 9 버전 이상에서는 더 이상 사용되지 않는다(Deprecated).

Object toString()

  • toString() 메서드는 객체 정보를 문자열로 반환하는 메서드로 “패키지명.클래스명@hashcode”로 출력된다.
  • Object class의 toString() 메서드
public String toString(){
	return getClass().getName()
					+ "@"
					+ Integer.toHexString(hashcode());
}
ObjectEx01 o = new ObjectEx01();
System.out.println("Object toString()->" + o.toString());

[결과]
Object toString()->ch12.ObjectEx01@5a39699c
  • 보통 객체 멤버 필드의 정보를 출력하는 용도로 사용하기 위해 상속 받은 클래스에서 toString() 메서드를 오버라이딩해서 사용한다.
  • String이나 Integer같은 Wrapper클래스들은 toString() 메서드가 오버라이드 되어있다.
public class ObjectToString{
	private String name = "GilDong";
	private int age = 10;

	public static void main(String[] args){
		ObjectToString o = new ObjectToString();
		System.out.println(o);
		System.out.println(o.toString());
	}
	@Override
	public String toString(){
		return "name=" + name + " age=" + age;
	}
}

[결과]
name=Gildong age=10
name=Gildong age=10

Object equals(Object obj)

  • 객체 자신과 파라미터로 전달된 객체(obj)를 비교해서 같으면 true, 아니면 false 값을 반환한다.
  • Object 클래스의 equals() 메서드는 객체의 참조 값(주소)을 비교한다.
public boolean equals(Object obj){return (this==obj);}
  • equals() 메서드를 오버라이딩해서 객체의 값을 지교하는 것으로 변경한다.
class ObjectEq{
	private int val;
	public ObjectEq(int val){
		this.val = val;
	}
	@Override
	public boolean equals(Object obj){
		if(obj != null && obj instanceof ObjectEq){
			return this.val == ((ObjectEq)obj).val;
		}
		return false;
	}
}

public class ObjectEqualsTest{
	public static void main(String[] args){
		Object obj1 = new Object();
		Object obj2 = new Object();
		if(obj1.equals(obj2)){ //obj1 == obj2
			System.out.println("obj1.equals(obj2)-> true");
		}else{
			System.out.println("obj1.equals(obj2)-> false");
		}

		ObjectEq oeq1 = new ObjectEq(10);
		ObjectEq oeq2 = new ObjectEq(10);
		//객체 참조값을 비교
		if(oeq1 == oeq2){
			System.out.println("o1 == o2 -> true");
		}else{
			System.out.println("o1 == o2 -> false");
		}
		//오버라이딩된 메서드를 호출하여 객체의 필드값을 비교
		if(oeq1.equals(oeq2)){
			System.out.println("o1.equals(o2) -> true");
		}
	}
}

[결과]
obj1.equals(obj2) -> false
o1 == o2 -> false
o1.equals(o2) -> true

Object getClass()

  • getClass() 메서드는 실행중인 객체의 클래스 정보를 가지고 있는 Class 클래스의 런타임 클래스 객체를 얻을 수 있다.
    • public final native Class<?> getClass()
  • 런타임 클래스 객체(Runtime class object): 모든 클래스 bytecode는 java.lang.Class 객체를 사용하여 저장하며, Class 클래스의 인스턴스를 런타임 클래스 객체라고 한다. 이 객체를 사용하여 클래스 이름, 메서드 정보, 생성자 정보 등 클래스에 대한 정보를 얻을 수 있다.
  • getName(): 클래스 이름을 리턴
  • getFields(): 클래스의 필드를 리턴
  • getConstructor(): 클래스의 생성자를 리턴
  • getMethods(): 클래스의 메서드를 리턴
public class GetClassEx1{
	public static void main(String[] args){
		String str = "getClass() 메서드 실행";
		Class clazz = str.getClass();
		System.out.println("클래스명 : " + clazz.getName());
		System.out.println("상위 클래스명 : " + clazz.getSuperclass());
		System.out.println("메서드 목록");
		for(Method method : clazz.getMethods()){
			System.out.println(method.getName() + "\t");
		}
		System.out.println();
		System.out.println("필드 목록");
		for(Field field : clazz.getFields()){
			System.out.println(field.getName() + "\t");
		}
	}
}

System


System Properties

  • System Properties는 System의 Run-time 환경 변수를 얻어오거나 셋팅할 때 사용한다.
  • System.getProperties() 메서드를 호출하면 [java.util.Properties](http://java.util.Properties) 클래스의 객체가 반환된다.
  • getProperty(”property name”)을 호출하면 property value를 반환한다.
  • java 구종시에 -D 옵션으로 property를 정의할 수 있다.
  • Command line
    • java -Dname=value 클래스명 → System.getProperty(”name”) → value return
  • Properties 클래스는 name과 value 한 쌍의 데이터로 매핑된다.
  • propertyNames() 메소드는 모든 proeprty name들을 Enumeration(열거형 데이터)으로 반환한다.
  • load()와 store() 메소드로 file의 property를 불러오거나 저장할 수 있다.
  • Properties 클래스를 이용한 속성 파일의 정보가 변경되어도 재컴파일할 필요가 없어 자주 변경되는 정보를 저장하는데 사용된다.
import java.util.Enumeration;
import java.util.Properties;

public class PropertiesTest{
	public static void main(String[] args){
		Properties props = System.getProperties();
		Enumeration propsNames = props.propertyNames();

		while(propsNames.hasMoreElements()){
			String propName = (String)propsNames.nextElement();
			String property = props.getProperty(propName);
			System.out.println("property '" " propName +
							"' = '" + property + "'");
		}
	}
}

[결과]
property 'java.runtime.name' = 'OpenJDK Runtime Environment'
property 'java.vm.version' = '11.0.12+0'
property 'gopherProxySet' = 'false'
property 'java.vm.vendor' = 'Homebrew'
property 'java.vendor.url' = 'https://github.com/Homebrew/homebrew-core/issues'
property 'path.separator' = ':'
property 'java.vm.name' = 'OpenJDK 64-Bit Server VM'
property 'user.country' = 'KR'
property 'java.runtime.version' = '11.0.12+0'
property 'os.arch' = 'aarch64'
property 'java.vm.specification.vendor' = 'Oracle Corporation'
property 'os.name' = 'Mac OS X'
property 'sun.jnu.encoding' = 'UTF-8'
property 'jdk.debug' = 'release'
property 'java.class.version' = '55.0'
property 'java.specification.name' = 'Java Platform API Specification'
property 'sun.management.compiler' = 'HotSpot 64-Bit Tiered Compilers'
...

Console I/O

  • System.out: standard output으로 데이터를 출력할 때 사용하며 PrintStream type의 Object이다.
  • System.in: standard input으로 데이터를 읽어들일 때 사용하며 InputStream type의 object이다.
  • System.err: standard error를 출력할 때 사용하며 PrintStream type의 Object이다.
  • print()와 println() (new line: \n)메소드가 primitive type으로 overloading되어 있다.
    void println(boolean)
    void println(char)
    void println(double)
    void println(fload)
    void println(int)
    void println(long)
    void println(char[])
    void println(Object)
public class KeyboardInput{
	public static void main(String[] args){
		String s;

		//키보드로 입력받을 수 있는 reader 객체를 생성한다.
		InputStreamReader ir = new InputStreamReader(System.in);
		BufferedReader in = new BufferedReader(ir);

		System.out.println("Stop 버튼을 누르면 프로그램이 종료됩니다!");
	
		try{
			//콘솔에서 입력을 받는다
			s = in.readLine();
			while(s != null){
				//입력받은 값을 출력
				System.out.println("Read: " + s);
				s = in.readLine(); //다시 입력 받는다
			}
			in.close(); //입력 받는 Reader를 close
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}

Math class

  • 자주 사용하는 static 수학용 계산 기능들의 모듬 클래스이다.
  • 모두 static 메서드로 구성되어 있어 객체 생성없이 사용한다.
  • log, 삼각 함수 등과 같은 기본적인 수치 연산을 수행하기 위한 다양한 메서드를 포함하고 있다.
  • truncation: ceil, floor, round
  • max, min, abs(절다값)
  • 삼각함수: sin, cos, tan, asin, acos, atan, toDegrees, toRadians
  • 대수: log, exp
  • 기타: sqrt, pow, random
  • 상수: PI, E(오일러의 수-자연로그의 밑 값으로 약 2.718을 의미)
MethodDescription
abs(value)주어진 값의 절대값을 반환한다.
max(v1, v2)두 값 중 가장 큰 값을 반환한다.
min(v1, v2)두 값 중 가장 작은 값을 반환한다.
round(value)십진수를 가장 가까운 값으로 반올림하는데 사용된다.
sqrt(value)숫자의 제곱근을 반환하는데 사용된다.
pow(v1, v2)첫 번째 인수의 값을 두 번째 인수로 거듭제곱한 값을 반환한다.
signum(value)주어진 값의 부호를 찾는데 사용된다.
ceil(value)주어진 값을 올림하여 반환한다.
floor(value)주어진 값을 버림하여 반환한다.
sin(value)주어진 이중 값의 삼각 사인 값을 반환하는데 사용된다.
random()0.0보다 크거나 같고 1.0보다 작은 양수 부호의 랜덤 값을 반환한다.
rint(value)주어진 값과 가장 가까운 정수의 double형을 반환한다.
public class MathTest{
	public static void main(String[] args){
		out.println("10의 절대값 : " + Math.abs(10));
		out.println("10.0 절대값: " + Math.abs(10L));
		out.println("20.0d의 절대값 : " + Math.abs(-20.0d));
		out.println("큰 값을 반환 : " + Math.max(20, 10));
		out.println("작은 값을 반환 : " + Math.min(10.0, 20.0));
		out.println("Random 값을 반환 : " + Math.random());
		out.println("올림 값 : " + Math.ceil(20.3));
		out.println("작거나 같은 가장 작은 정수를 반환 : " + Math.floor(99.7));
		out.println("가장 가까운 정수를 double 타입으로 반환 : " + Math.rint(101.57));
		out.println("radians로 지정된 sin 값을 반환 : " + Math.sin(100));
		out.println("radians로 지정된 cos 값을 반환 : " + Math.cos(100));
		out.println("radians로 지정된 tan 값을 반환 : " + Math.tan(100));
		out.println("100으로 지정된 로그값을 반환 : " + Math.log(100));
		out.println("3.0의 2.0승 값을 double 값으로 반환 : " + Math.pow(3.0, 2.0));
		out.println("Square root값을 double 값으로 반환 : " + Math.sqrt(3));
	}
}

[결과]
10의 절대값 : 10
10.0 절대값 : 10
20.0d의 절대값 : 20.0
큰 값을 반환 : 20
작은 값을 반환 : 10.0
Random 값을 반환 : 0.6787390797156491
올림 값 : 21.0
작거나 같은 가장 작은 정수를 반환 : 99.0
가장 가까운 정수를 double 타입으로 반환 : 102.0
radians로 지정된 sin 값을 반환 : -0.5063656411097588
radians로 지정된 cos 값을 반환 : 0.8623188722876839
radians로 지정된 tan 값을 반환 : -0.5872139151569291
100으로 지정된 로그값을 반환 : 4.605170185988092
3.02.0승 값을 double 값으로 반환 : 9.0
Square root값을 double 값으로 반환 : 1.7320508075688772

Wrapper class

  • 기본형을 클래스로 정의한 것. 기본형 값도 객체로 다뤄져야 할 때가 있다.
  • Java의 래퍼 클래스는 기본형(Primitive type)값을 객체로, 객체를 기본형 값으로 변환하는 메커니즘을 제공한다. (포장 클래스)
  • Java 5.0버전부터 제공되는 오토박싱(Autoboxing) 및 언박싱(Unboxing) 기능은 자동으로 변환해준다.
  • 8개의 래퍼 클래스가 있다.
기본형래퍼클래스
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
  • 래퍼클래스의 equals() 메서드는 값을 비교할 수 있도록 오버라이딩되어 있다.
public boolean equals(Object obj){
	if(obj instanceof Integer){
		return value == ((Integer)obj).intValue();
	}
	return false;
}

//사용예
Integer i1 = Integer.valueOf(10);
Integer 12 = Integer.valueOf(10);
boolean isEquals = i1.equals(i2);

Boxsing, UnBoxing

  • 박싱(Boxing): 기본형(Primitive type)을 래퍼클래스의 인스턴스로 변환하는 것을 박싱이라고 한다.
  • 오토박싱(Autoboxing): 기본형(Primitive type)을 래퍼 클래스로 자동 변환하는 것을 오토박싱이라고 한다.
  • 예를들면 byte 기본형에서 Byte 래퍼클래스로 자동 변환된다.
public class AutoBoxing{
	public static void main(String[] args){
		int val = 20;
		//valueOf() 메서드를 이용하여 래퍼 클래스 객체 변환
		Integer i1 = Integer.valueOf(val);
		//Autoboxing으로 래퍼 클래스 객체 자동 변환
		Integer i2 = val;
	}
}
  • 언박싱(Unboxing): 래퍼 클래스 객체를 기본형(Primitive type)으로 변환하는 것을 언박싱이라고 한다.
  • 오토언박싱: 래퍼 클래스 객체를 기본형(Primitive type)으로 자동 변환하는 것을 오토 언박싱이라고 한다.
  • new 생성자로 생성하는 것은 deprecated되었고, Static factory 메서드인 valueOf()사용을 권장한다.
public class UnBoxing{
	public static void main(String[] args){
		//new 생성자를 사용하는 것은 deprecated되었다
		//Integer i = new Integer(20);
		Integer i = Integer.valueOf(20);

		//intValue() 메서드를 이용하여 기본형으로 변환
		int val1 = i.intValue();
		//Unboxing 기능으로 기본형으로 자동 변환
		int val2 = i;
	}
}
  • Java 1.5버전부터는 박싱과 언박싱이 필요한 상황에서 컴파일러가 이를 자동으로 처리해준다.
  • 오토박싱과 오토언박싱을 통해 기본혀오가 래퍼클래스 간의 다양한 연산도 가능하다.
public class AutoBoxingUnBoxing{
	public static void main(String[] args){
		Integer num = Integer.valueOf(15); //박싱
		int n = num.intValue(); //언박싱
		System.out.println(n);
	
		Character ch = 'X'; //Character ch = new Character('X'); :오토박싱
		char c = ch; //char c = ch.charValue(); :오토언박싱
		System.out.println(c);

		//오토박싱과 오토언박싱을 통해 기본형과 래퍼클래스간의 다양한 연산도 가능하다
		Integer num1 = Integer.valueOf(7); //박싱
		Integer num2 = Integer.valueOf(3); //박싱

		int int1 = num1.intValue(); //언박싱
		int int2 = num2.intValue(); //언박싱

		Integer result1 = num1 + num2; //10
		Integer result2 = int1 - int2; //4
	}
}

Number class

  • 숫자를 멤버변수로 갖는 Numbers는 BigDecimal, BigInteger와 래퍼 클래스의 조상 클래스로 Abstract 클래스다.
  • Number클래스는 표현된 숫자 값을 byte, double, float, int, long, short 유형으로 변환하는 4개의 추상 메서드와 2개의 Concrete 메서드를 제공한다.
  • 예를들어 Double 객체에 intValue() 메서드로 기본형으로 변환할 수 있다. (실수 → 정수)
Modifier 리턴타입메서드Description
bytebyteValue()지정된 숫자의 값을 byte로 변환한다.
abstract doubledoubleValue()지정된 숫자의 값을 double로 변환한다.
abstract floatfloatValue()지정된 숫자의 값을 float으로 변환한다.
abstract intintValue()지정된 숫자의 값을 int로 변환한다.
abstract longlongValue()지정된 숫자의 값을 long으로 변환한다.
shortshortValue()지정된 숫자의 값을 short로 변환한다.

Number Abstract 클래스와 이를 상속하고 있는 Integer 래퍼클래스 소스의 일부다.

public abstract class Number{
	implements java.io.Serializable{
		public abstract int intValue();
		public abstract long longValue();
		public abstract float floatValue();
		public abstract double doubleValue();
		public byte byteValue(){
			return (byte)intValue();
		}
		public short shortValue(){
			return (short)intValue();
		}
	}
}

public final class Integer extends Number implements Comparable<Integer> {
...
	public int intValue(){
		return value;
	}
}

public class NumberTestEx{
	public static void main(String[] args){
		Double doubleValue = Double.valueOf(123.456);

		int intValue = doubleValue.intValue(); //소숫점 버림
		short shortValue = doubleValue.shortValue();
		long longValue = doubleValue.longValue();

		System.out.println("integer value: " + intValue);
	}
}

[결과]
integer value: 123

String class

  • String은 문자열을 다루기 위해 이용하며 “abc”와 같은 모든 문자열 리터럴은 이 클래스의 인스턴스로 구현된다.
  • String은 기본적으로 char값의 시퀀스(일련의 문자)를 나타내는 객체이다.
  • Java String 클래스는 compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()과 같은 문자열에 대한 작성을 수행하는 많은 메서드를 제공한다.
  • String클래스는 Serializable, Comparable 및 CharSequence 인터페이스를 구현한다.
  • String 인스턴스의 내용은 변경할 수 없으며, 이런 변경할 수 없는 객체를 불변형 객체(immutable obejct)라고 한다. 문자열을 변경할 때마다 새 인스턴스가 생성된다.
  • CharSequence 인터페이스는 문자 시퀀스를 나타내는데 사용되며, char 값을 읽을 수 있는 시퀀스다.
  • 변경 가능한 문자열은 StringBuffer, StringBuilder 클래스를 사용할 수 있다.
char[] ch = {'g','i','l','d','o','n','g'};
String s = new String(ch); //String s = 'gildong";과 같음

  • 문자열 객체를 생성하는 방법은 문자열 리터럴과 new 키워드를 이용하는 2가지 방법이 있다.
  • 문자열 리터럴(String Literal)
    • 큰따움표(”)를 사용하여 생성된다 → String s = “문자열 리터럴”;
    • 문자열 객체는 “string constant pool”이라는 특별한 메모리 영역에 저장된다.
    • 문자열 리터럴 생성시마다 JVM은 “string constant pool”을 먼저 확인하여 동일한 문자열이 풀에 존재할 경우 풀링된 인스턴스 참조값을 반환한다.
    • 풀에 없을 경우 새 문자열 인스턴스가 생성되어 풀에 배치한다.
  • 메모리를 보다 효율적으로 운용하기 위해 문자열 리터럴 개념을 사용한다.
String s1 = "literal";
String s2 = "literal"; //새 인스턴스를 생성하지 않는다.

  • new 키워드로 String 객체를 생성할 경우 JVM은 Heap memory에 새 문자열 객체를 생성하고, literal 문자열이 상수풀에 배치된다.
    String s = new String(”gildong”);
  • 변수 s는 string constant pool이 아닌 힙의 객체를 참조한다.
public class StringEx01 {
	public static void main(String args[]){
	String s1 = "java"; // 문자열 리터럴로 string 객체 생성
	char ch[] = {'g','i','l','d','o','n','g'};
	String s2 = new String(ch); // char 배열을 문자열로 변환
	// new 키워드로 자바 문자열 객체 생성
	String s3 = new String("새로운 문자열");
	System.out.println(s1);
	System.out.println(s2);
	System.out.println(s3);
	String strVar1 = "abc";
	String strVar2 = "abc";
	String strVar3 = new String("abc");
	String strVar4 = new String("abc");
	// true = 동일한 객체 참조값
	System.out.println(strVar1 == strVar2);
	// false = new로 생성되어 객체 참조값이 다르다
	System.out.println(strVar3 == strVar4);
	// 오버라이된 equals메서드로 값을 비교
	System.out.println(strVar1.equals(strVar2));
	System.out.println(strVar3.equals(strVar4));
	}
}

[결과]
java
gildong
새로운 문자열
true
false
true
true
MethodDescription
charAt(int index)지정한 index에 있는 문자를 반환한다.
length()문자열의 길이를 반환한다.
concat(String str)파라미터 문자열을 현재 문자열에 덧붙인다.
substring(int beginIndex, int endIndex)지정한 시작위치부터 종료위치 범위에 포함된 문자열을 반환한다.
isEmpty()빈 문자열 여부를 반환한다.
contains(CharSequence s)지정된 문자열이 포함되어 있는지 여부를 반환한다.
replace(char old, char new)문자열 중의 old 문자를 new 문자로 변경한 문자열을 반환한다.
equalsIgnoreCase(String another)문자열과 another 문자열을 대소문자 구분없이 동일한지 여부를 반환한다.
split(String regex)문자열을 지정된 분리자*(regex)로 나누어 문자열 배열에 저장 후 반환한다.
indexOf(int ch)주어진 문자열이 존재하는지 확인하여 그 위치를 반환하며, 없으면 -1을 반환한다.
toLowerCase()저장되어 있는 문자열을 모두 소문자로 변환 후 반환한다.
toUpperCase()저장되어 있는 문자열을 모두 대문자로 변환 후 반환한다.
trim()저장되어 있는 문자열의 왼쪽 끝과 오른쪽 끝에 있는 공백을 제거한 문자열을 반환한다.
valueOf(기본형 value)지정된 값을 문자열로 변환하여 반환한다.
String s = new String("ABCDEFGH");
System.out.println(s.charAt(4)); //E
System.out.println(s.compareTo("ABCDEFGH")); //0
System.out.println(s.compareToIgnorCase("abcdefgh")); //0
System.out.println(s.concat("abc")); //ABCDEFGHabc
System.out.println(s.endsWith("FGH")); //true
System.out.println(s.equals("ABCDEFGH")); //true
System.out.println(s.equalsIgnoreCase("abcdefgh")); //true

s = new String("This is a String");
System.out.println(s.indexOf("i"); //2
System.out.println(s.indexOf("i", 7)); //13
System.out.println(s.indexOf("is")); //2
System.out.println(s.lastIndexOf("is")); //5
System.out.println(s.length()); //16
System.out.println(s.replace('i', 'Q')); //ThQs Qs a StrQng
System.out.println(s.replaceAll("is", "IS")); //ThIS IS a String
System.out.println(s.startWith("This")); //true
System.out.println(s.substring(5)); //is a String
System.out.println(s.substring(5, 13)); //is a Str
System.out.println(s.toLowerCase()); //this is a string
System.out.println(s.toUpperCase()); //THIS IS A STRING

StringBuffer class

MethodDescription
append(데이터타입 value)지정된 값을 현재 문자열 끝에 추가한다.
capacuty()현재 문자열의 총 버퍼크기(용량)을 반환한다. 버퍼의 기본 용량은 16개이며, 현재 용량에서 문자 수가 증가하면 (oldcapacity * 2)+2만큼 용량이 증가한다.
예) 현재 용량이 16인 경우 → (16*2)+2=34
charAt(int index)지정한 index에 있는 문자를 반환한다.
delete(int beginIndex, int endIndex)지정한 시작위치부터 종료위치 범위에 문자열 중에서 삭제한 문자열을 반환한다.
indexOf(String str)str 문자열의 인덱스를 반환한다.
length()문자열내의 문자 개수를 반환한다.
replace(int start, int end, String str)start에서 ends문자열을 str 문자열로 대체하여 반환한다.
reverse()문자열의 역순으로 된 문자열을 반환한다.
substring(int start, int end)start에서 end까지의 문자열을 반환한다.
public class StringBufferEx01 {
	public static void main(String[] args) {
	StringBuffer sb = new StringBuffer();
	sb.append("홍길동");
	sb.append("버퍼 테스트");
	sb.insert(3, "문자열 추가 ");
	sb.substring(0,2);
	String result = sb.toString();
	System.out.println("capacity="+sb.capacity());
	System.out.println("length="+sb.length());
	System.out.println("result : " + result);
	// 지정 인덱스 문자열 변경
	sb.replace( 1 , 3 , "자바" );
	System.out.println("sb replace : " + sb);
	// 지정 인덱스 문자열 삭제
	sb.delete( 1 , 3 );
	System.out.println("sb delete : " + sb);
	// 문자열을 반대로 변경
	sb.reverse();
	System.out.println("sb reverse : " + sb);
	}
}

[결과]
capacity=16
length=16
result : 홍길동문자열 추가 버퍼 테스트
sb replace : 홍자바문자열 추가 버퍼 테스트
sb delete : 홍문자열 추가 버퍼 테스트
sb reverse : 트스테 퍼버 가추 열자문홍

Capacity 예제

public class StringBuferEx03 {
	public static void main(String args[]){
		StringBuffer sb=new StringBuffer();
		System.out.println(sb.capacity());//default 16
		sb.append("Hello");
		System.out.println(sb.capacity());//now 16
		sb.append("java is my favourite language");
		System.out.println(sb.capacity());//now (16*2)+2=34 (oldcapacity*2)+2
	}
}

String class, StringBuffer class

  • string 객체는 immutable(불변형) Unicode characters다.

  • concat, replace, substring, toLowerCase, toUpperCase, trim 메서드들은 새로운 String Object를 생성하는 메서드들이다.

  • 검색 메서드: endsWith, startWith, indexOf, lastIndexOf

  • 비교 메서드: equals, equalsIgnoreCase, compareTo

  • 기타: chatAt, length

  • StringBuffer object는 mutable(변형) Unicode characters다.

  • 생성자

    • StringBuffer() - empty buffer를 생성한다.
    • StringBuffer(int capacity) - capacity만큼 버퍼를 초기화하여 생성한다.
    • StringBuffer(String initialString) - 초기 string값을 포함하여 buffer를 초기화하여 생성한다.
  • Modification methods: append, insert, reverse, serCharAt, serLength

StringBuffer buffer = new StringBuffer();
buffer.append("bind").append("string");
  • StringBuffer는 동일한 객체에 값을 변경할 수 있는 mutable 객체다.
  • append() 메서드는 인수로 전달된 값을 문자열로 변환 후 해당 문자열의 마지막에 추가된다.
  • String 클래스의 concat()과 결과는 동일하지만, 내부적인 처리 속도가 훨씬 빠르다.
  • 멀티스레드 환경에서는 불변 클래스를 사용하면 좀 더 신뢰할 수 있는 코드를 작성할 수 있다. 왜냐하면 하나의 객체에 스레드가 접근하게 되면 공유에 대한 Thread safe한 처리를 해줘야 하지만 불변 인스턴스는 값이 변하지 않는다는 점이 보장된다.
StringBuffer sb = new StringBuffer("스트링버퍼");
sb.append("123");
StringStringBuffer
불변형(immutable)이다.변경 가능(mutable)하다.
문자열에 변화를 주는(문자열을 더해 조합하는 등의 변화) 새로운 String 인스턴스를 생성하고 기존 인스턴스가 삭제될 수 있다. 인스턴스 생성이 반복되는 과정 속에서 overhead가 심해질 수 있다.빠르며 문자열을 연결할 때 String보다 메모리를 덜 소비한다.
Object 클래스의 equals() 메서드를 오버라이드하며, equals() 메서드로 두 문자열의 내용을 비교할 수 있다.equals() 메서드를 오버라이드하지 않았다.
값을 비교하려면 toString()으로 문자열을 얻은 후 String의 equals()메서드로 비교한다.
String constant pool을 사용한다.Heap 메모리를 사용한다.

Overhead 비교 예제

public class StringVSStringBuffer{
	public static String concatWithString() {
		String t = "Java";
		for (int i=0; i<10000; i++){
			t = t + "연결";
		}
		return t;
	}
	public static String concatWithStringBuffer(){
		StringBuffer sb = new StringBuffer("Java");
		for (int i=0; i<10000; i++){
			sb.append("연결");
		}
		return sb.toString();
	}
	public static void main(String[] args){
		long startTime = System.currentTimeMillis();
		concatWithString();
		System.out.println("String을 연결시키는데 걸리는 시간 : "+(System.currentTimeMillis()-startTime)+"ms");
		startTime = System.currentTimeMillis();
		concatWithStringBuffer();
		System.out.println("StringBuffer를 연결할 때 걸리는 시간 : "+(System.currentTimeMillis()-startTime)+"ms");
	}
}
[결과]
String을 연결시키는데 걸리는 시간 : 54ms
StringBuffer를 연결할 때 걸리는 시간 : 0ms

StringBuilder class

  • StringBuilder 클래스는 가변(mutable) 문자열을 생성하는데 사용하며, 클래스내 메서드가 동기 처리가 안 되는 점을 제외하면 StringBuffer클래스와 동일하다.
  • Java 1.5버전부터 사용할 수 있다.
public class StringBuilderEx1{
	public static void main(String[] args){
		StringBuilder sb = new StringBuilder("Hello");
		sb.delete(1,3);
		System.out.println("sb delete : "+sb); //Hlo
		sb.reverse();
		System.out.println("sb reverse "+sb) //olH
		//문자 대체, 문자 교체, 문자 치환
		sb.setCharAt(1, 'b');
		System.out.println("sb setCharAt : "+sb); //obH
	}
}

동기화 처리

StringBuffer의 문자열 리터럴을 추가하는 append() 메서드는 스레드 동기화를 위한 synchronized 처리가 되어 있다.

@Override
public synchronized StringBuffer append(Object obj){
	toStringCache = null;
	super.append(String.valueOf(obj));
	return this;
}

@Override
@HotSpotIntrinsicCandidate
public StringBuilder append(String str){
	super.append(str);
	return this;
}
profile
웹퍼블리셔의 백엔드 개발자 도전기

0개의 댓글