NULL

JAVA String클래스의 메소드, 불변 클래스 본문

Back-end/JAVA

JAVA String클래스의 메소드, 불변 클래스

1924 2022. 1. 21. 15:45

 

public static void main(String[] args) {
		
		String str = "hello";
		//String은 한번 만든 객체를 바꾸지 않는다. - 불변 클래스
		System.out.println(str.length());
		System.out.println(str.concat(" world"));
		System.out.println(str);
		
		str = str.concat(" world");
		System.out.println(str);
		// 변수로 concat을 사용해서 문자열을 추가하면 값이 변하게 된다.
		
		System.out.println(str.substring(3)); // 3번째 인덱스부터 마지막까지만 짜른다.
		System.out.println(str.substring(1, 3)); // 1번째 인덱스부터 3번째인덱스 까지 짜른다.
	}

 

 

불변 클래스(Immutable Class)는 변경하지 못하는 가변적이지 않은 클래스이다.

불변 클래스(Immutable Class)는 레퍼런스 타입의 객체이기 때문에 힙(heap)영역에 생성된다.

 

자바에서는 대표적으로 String, Boolean, Integer, Float, Long 등이 있다.

 

이러한 불변 클래스(Immutable Class)들은 힙(heap)영역에서 변경 불가능할 뿐,값을 재할당하는 것은 가능하다.

Comments