ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] String Array
    Programming Lang/Java 2022. 8. 28. 02:52

    스트링 배열이란?

    String
    a set of objects joined together in a row on a single rope or thread
    밧줄이나 실 하나로 일렬로 연결된 한 세트의 물체

    a usually short piece of text consisting of letters, numbers, or symbols that is used in computer processes such as searching through large amounts of information
    대개 많은 양의 정보를 검색하는 것과 같은 컴퓨터 프로세스에서 사용되는 문자, 숫자 또는 기호로 구성된 짧은 텍스트 조각
    Array
    a large group of things, especially one that has been positioned in a particular way
    특정한 방식으로 배치된 많은 사물들


    String은 참조형의 대표적인 클래스로 기본값은 null 이다.
    char는 문자를 뜻하고 이를 나타낼 때 ‘ ’로, String은 “ ”를 사용한다.

    char c1 = 'A';
    char c2 = "A"; // Type mismatch: cannot convert from String to char
    
    String s1 = 'A'; // Type mismatch: cannot convert from char to String
    String s2 = "A";


    String class는 char 배열의 집합이며, Character 클래스의 확장형이다.
    String 클래스를 깊숙이 들어가보면 아래와 같이 구성되어있는 것을 알 수 있다.

    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

     

    literal 방식

    원시형 및 리터럴 값(실데이터) -> 스태틱 메모리에 저장
    할당될 메모리의 크기는 컴파일 타임(컴파일 하는 동안)에 결정

    String str1 = "str1";

     

    new 방식

    참조 주소 -> 힙 메모리에 저장
    할당해야 할 메모리의 크기를 프로그램이 실행되는 동안 결정해야 하는 경우(런 타임때) 유용하게 사용되는 공간

    String str2 = new String("str1");


    아래 비교 코드를 봅시다.

    if(str1==str2) {
    	System.out.println("String true1");
    }else{
    	System.out.println("String false1");
    }
    
    if(str1.equals(str2)) {
    	System.out.println("String true2");
    }else{
    	System.out.println("String false2");
    }
    
    System.out.println("=========================");
    
    int num1 = 2;
    Integer num2 = 2;
    
    if(num2==num1) {
    	System.out.println("int true1");
    }else{
    	System.out.println("int false1");
    }
    
    if(num2.equals(num1)) {
    	System.out.println("int true2");
    }else{
    	System.out.println("int false2");
    }

     

    결과

    String false1
    String true2
    • 첫번째는 데이터와 주소를 비교하기에 false 출력
    • 두번째 equals는 데이터(리터럴) 자체를 비교하여 true 출력

     

    int true1
    int true2
    • 첫번째는 오토박싱이 되므로(java 1.5부터 가능. Integer는 참조타입이지만 int타입과 만났을때 자동으로 int 형변환을 해준다. 이러한 기본 자료형 (primitive data types)에 대한 클래스 표현을 래퍼 클래스(Wrapper classes) 라고 부른다.) true 출력
    • 두번째는 equals는 데이터(객체) 자체를 비교하여 true 출력

     

    중요!

    String은 클래스이지만 final 이 붙어서 더이상 상속하여 확장이 불가능하다.
    아래는 String 클래스 정의 부분을 가져온 것이다.

    public final class String
    
        implements java.io.Serializable, Comparable<String>, CharSequence {
    
    	.
    	.
    	.

     

    String 배열의 선언 방법 3가지

    String[] name = new String[3]; //선언과 배열 생성
    String[] str1 = new String[]{"1","2","3"}; //선언과 초기화
    String[] str2 = {"1","2","3"}; //new String[] 생략가능


    배열의 주소에도 규칙이 있다.

    String[] strArr = "The String class represents character strings.".split(" ");
    Integer integerArr[] = {1,2,3,4,5};
    int intArr[] = {1,2,3,4,5};
    System.out.println("String 배열 주소 : String 타입 @ 16진수 ==> "+ strArr);
    System.out.println("Integer 배열 주소 : Integer 타입 @ 16진수 ==> "+ integerArr);
    System.out.println("int 배열 주소 : int 타입 @ 16진수 ==> "+ intArr);

     

    결과

    String 배열 주소 : String 타입 @ 16진수 ==> [Ljava.lang.String;@15db9742
    Integer 배열 주소 : String 타입 @ 16진수 ==> [Ljava.lang.Integer;@6d06d69c
    int 배열 주소 : String 타입 @ 16진수 ==> [I@7852e922

     

    더보기

    참고 서적 : 자바의 정석

     

    'Programming Lang > Java' 카테고리의 다른 글

    [Java] Inheritance, Overriding  (0) 2022.09.09
    [Java] Class, Instance, Constructor  (0) 2022.09.07
    [Java] Variable, Method, JVM  (0) 2022.09.05
    [Java] Operator  (0) 2022.08.27
    [Java] Type Casting  (0) 2021.07.01
Designed by Tistory.