Java/모두의 자바

Chapter 05-24 참조형

계란💕 2022. 2. 5. 12:11

 

03-24.1 변수의 자료형

 

  (1) 기본형

  - 논리형: boolean

  - 문자형: char

  - 정수형: byte., short, int, long

  - 실수형: double, float

 

  (2) 참조형이란?

  - 기본형을 제외한 모든 형을 말한다. 

  - 앞서 배운 배열도 참조형, 클래스도 포함된다.

 

 

03-24.2 참조형

  Ex)

<hide>

package javaStudy;

public class RefenceDataType {
	public static void main(String[] args) {
		int i = 4;
		String str = new String("hello");
	}
}

  - 코드를 보면 기본형이 아닌 "String"이라는 클래스가 적혀 있다. 

  - new 뒤에는 생성자가 있다.

  - new: 클래스를 메모리에 올리라는 의미이다. 

  - String str = new String("hello") :

   변수 str에 String 인스턴스가 있는 게 아니라 다른 메모리 영역에 있는 String이라는 인스턴스를 변수 str이 가리킨다.

  - str에는 메모리의 위치(주소) 값이 저장된다.

  - str 변수는 String 인스턴스를 잠초한다.

  - 인스턴스: 메모리에 올라간 클래스를 말한다. 

   

 

03-24.3 String 클래스

  - String 클래스는 자바에서 가장 많이 사용하는 클래스이다.

  - 다른 클래스와 다르게 "new"라는 연산자를 이용하지 않고도 인스턴스를 만들어낼 수 있다. 

 

  Def) 힙(heap) 메모리 영역: 할당해야 할 메모리의 크기를 프로그램을 실행하는 동안 결정해야하는 경우(런타임 때)

  유용하게 사용되는 공간이다. 기본 데이터 타입은 항상 크기가 동일 하지만 객체들은 생성 시에 크기가 다를 수 

  있어서 힙에 생성한다.

 

  Ex) 인스턴스 만들기

<hide/>

package javaStudy;

public class StringExam {
	public static void main(String[] args) {
		
		String str1 = "hello";
		String str2 = "hello";
		
		String str3 = new String("hello");
		String str4 = new String("hello");
		
		if(str1 == str2) 
			System.out.println("str1과 str2는 같은 레퍼런스입니다.");
	}
}

Note) 출력 결과: str1과 str2는 같은 레퍼런스입니다.

  - str1, str2라는 변수 옆에 바로 값을 넣어도 인스턴스가 생성된다. 

  - str3, str4처럼 일반 클래스와 같이 new를 이용해도 된다.

  - new를 이용하면 같은 문자열이어도 매번 메모리에 새롭게 할당된다. 

  - String은 new가 없어도 사용가능하므로 메모리를 아끼기 위해 생략해도 된다.

  - str1, str2는 모두 "hello"라는 문자열을 만든다.

  - hello라는 문자열은 메모리 중에 상수를 저장하는 영역에 저장된다. 

  - str1, str2 모두 같은 hello를 가리키므로 hello라는 상수는 한 번만 생성

  - str1, str2는 같은 인스턴스를 가리키고 같은 인스턴스를 참조한다. 

  - str3, str4는 new키워드를 이용해 만들기 때문에 상수 영역을 참조하지 않는다. 

  - new라는 단어가 나오는 순가 인스턴스를 무조선 힙(heap) 메모리 영역에 새로 만든다.   

  - 그래서 str3, str4는 각각 인스턴스를 각각 하나씩 생성하고  각각 만든 hello를 가리킨다.

  - 기본형인 경우 비교 연산자'=='는 두 값이 같은지를 비교한다. 

  - 참조형의 경우는 값을 비교하지 않고 가리키는 주소가 같은지 가리키는 메모리 영역 주소가 같은지 확인.

 

 

03-24.4  new연산자

  Ex)

<hide/>

package javaStudy;

public class StringExam {
	public static void main(String[] args) {
		
		String str1 = "hello";
		String str2 = "hello";
		
		String str3 = new String("hello");
		String str4 = new String("hello");
		
		if(str1 == str3) 
			System.out.println("str1과 str3은 같은 레퍼런스입니다.");
		
		if(str3 == str4) 
			System.out.println("str2와 str4는 같은 레퍼런스입니다.");	
	}
}

 

  Note) 실행결과: 아무것도 출력 되지 않는다.

  - 이는 str1과 str3 그리고 str3과 str4는 서로 다른 인스턴스를 가리키기 때문이다. 

 

 

03-24.5 String의 메서드, substring 

  Ex)

<hide/>

public class StringExam {
	public static void main(String[] args) {
		
		String str1 = "hello";
		String str2 = "hello";
		
		String str3 = new String("hello");
		String str4 = new String("hello");
		
		System.out.println(str1);	
		System.out.println(str1.substring(3));	
		System.out.println(str1);			
	}
}

  Note) 실행결과

 

  - str옆에 '.'을 찍으면 String클래스가 가진 메서드를 볼 수 있다. 

  - 메서드 중에서 substring "잘라주세요"라는 뜻이다.

  - str1.substring(3)): 인덱스가 3번인 것부처 잘라서 보여달라는 뜻이다. 

  - 인덱스는 0번 부터 시작하므로 lo가 출력된다. 

  - 다시 str1을 출력하면 위의 substring 수행과 관련없이 처음과 같은 hello가 출력된다.

 

 

03-24.6 String 클래스 실습

  Ex 1) 다음 코드를 실행하여 str1 ,str2가 서로 다른 인스턴스임을 확인하라. 

<hide/>

package javaStudy;
public class StringExam {
	public static void main(String[] args) {
		String str1 = new String("Hello World");
		String str2 = new String("Hello World");
		
		if( str1 == str2 ) {
			System.out.println("str1과 str2는 같은 레퍼런스입니다.");	
		}
		else {
			System.out.println("str1과 str2는 다른 레퍼런스입니다.");	
		}
	}
}

  Note) 출력결과 : str1과 str2는 다른 레퍼런스입니다. 

  - str1과 str2는 똑같이 생긴 객체이지만 다른 영역에 개체가 저장됐다.

  - 그 객체의 저장 위치는 다르므로 == 연산자로 비교했을 때 다르다고 결과가 나온다. 

 

 

03-24.7 String 클래스 실습

  Ex 2) ==연산자를 이용해서 String을 비교하면 레퍼런스를 비교하기 때문에 같은 값인지 확인할 수 없다. 

  같은 값인지 비교하려면 equals 메서드를 이요하면 된다. 다음 코드 실행하여 동작을 확인하라.

<hide/>

package javaStudy;
public class StringExam {
	public static void main(String[] args) {
		String str1 = new String("Hello World");
		String str2 = new String("Hello World");
		
		if( str1.equals(str2) ) {
			System.out.println("str1과 str2는 같은 값을 가집니다.");	
		}
		else {
			System.out.println("str1과 str2는 다른 값을 가집니다.");	
		}
	}
}

  Note) 실행 결과: str1과 str2가 같은 값을 가집니다. 

  - equals 메서드는 == 연산자와 다르게 메서드에서 구현한 내용을 판단합니다.

  - 객체의 주소를 비교하지 않고 객체의 내용을 비교한다. 

 

'Java > 모두의 자바' 카테고리의 다른 글

Chapter 05-26 메서드(Method)란?  (0) 2022.02.05
Chapter 05-25 필드 선언  (0) 2022.02.05
Chapter 05-23 클래스(Class) 선언  (0) 2022.02.05
Chapter 04-22 for each 문  (0) 2022.02.04
Chapter 04-21 2차원 배열  (0) 2022.02.04