java 면접 질문 정리(String) - 13 : 질문, 개인 작성 -

S.Sun·2024년 1월 12일
0

자바 면접

목록 보기
17/31

면접 질문

1. immutable 에 대하여 설명하시오.

2. 아래의 결과를 예측하고,이유를 설명하시오.

String str1 = "Simple String";
String str2 = "Simple String";
String str3 = new String("Simple String");
String str4 = new String("Simple String");
//참조변수의 참조 값 비교
if(str1 == str2)
	System.out.println("str1과 str2는 동일 인스턴스 참조");
else
	System.out.println("str1과 str2는 다른 인스턴스 참조");
if(str3 == str4)
	System.out.println("str3과 str4는 동일 인스턴스 참조");
else
	System.out.println("str3과 str4는 다른 인스턴스 참조");

3. 2번의 메모리를 그리시오.

4. 사용자에게 받은 문자열을 역순으로 화면에 출력하는 프로그램을 작성하시오.

//scanner 함수와 string 함수의 charAt() 함수를 이용해 볼것
입력:abcde
출력:edcba

5. String 에서 concat 메소드에 대해서 설명하시오.

6. String 에서 substring 메서드 사용법은?

7. String compareTo 사용법은?

8. String.valueOf 에 대하여 설명하시오.

9. 아래가 실행되는 원리(함수)를 표현해 보세요.

String str = "age" + 17;

개인 작성

  1. 객체 중, 상수처럼 처음 초기 데이터 할당은 가능하지만 이후 데이터 수정이 불가능한 객체를immutable object라 한다.
  2. str1과 str2는 동일 인스턴스 참조
    str3과 str4는 다른 인스턴스 참조

(str1과 str2의 객체는 A, str3의 객체는 B, str4의 객체는 C라고 표현하겠다.)
이유 : str1과 str2는 "Simple String"이라는 값이 들어간 객체 A의 주소값을 가지지만, str3와 str4는 각각 "Simple String"이라는 값이 들어가는 또 다른 객체 B, C를 생성한 뒤 해당 객체들의 주소값을 가져온 것이다.
3.

import java.util.Scanner;

public class ReversePrint {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//scanner 함수와 string 함수의 charAt() 함수를 이용해 볼것
		//		입력:abcde
		//		출력:edcba
		Scanner sc = new Scanner(System.in);
		String rp = sc.next();
		String np = "";
		int x = (rp.length()-1);
		for(int i = x ; i >= 0 ;i--) {
			np += rp.charAt(i);
		}
		System.out.println(np);
	}
}
  1. concat() : 두 문자열을 연결시킬 때 사용하는 함수.
String x = "coffee"; 
String y = "One";

System.out.println(x.concat(y));
// x + y 
// "coffeeOne"
String x = "coffee"; 

System.out.println(x.substring(2));
// index 2부터 이어지는 문자열 추출
// "ffee"
System.out.println(x.substring(1,4));
// index 1부터 4미만까지 이어지는 문자열. index 1 부터 (4-1)개만큼의 문자열 추출
// "off"
int cmp;
String word = "abcdefg";
String word2 = "Abcdefg";
cmp = word.compareTo(word2); 
// compareTo() : 두 단어를 비교하여, '사전' 내 단어 순서 상 어느 것이 먼저 있는지를 판별. 정수값 리턴.
// cmp < 0 : word가 word2보다 사전 앞에 위치한다는 것.  
// cmp > 0 : word2가 word보다 사전 앞에 위치한다는 것. 대문자가 소문자보다 먼저 온다.
// (word내 값이 나오는 페이지) - (word2내 값이 나오는 페이지) 라고 생각하면 쉽다.
  1. String.valueOf() 함수는 데이터 타입이 기본형인 데이터를 String형으로 변환하는 함수이다.
String str = "age" + 17;

// 17만 String으로 변환한다면 다음과 같다.
// String str = "age".concat(String.valueOf(17));

// 실제로는 아래와 같다
// String str = (new StringBuilder("age").append(String.valueOf(17))).toString();

// StringBuilder 클래스 내에서 String 클래스형으로 변환시켜주는 toString()함수를 지원한다. 
profile
두리둥둥

0개의 댓글