반응형
자바 문자열에 큰따옴표 (") 혹은 역슬래시 (\)를 넣으면 에러가 난다.
public class Main {
public static void main(String[] args) {
System.out.println("hello world"");
}
}
문자열에 큰따옴표를 넣었다.
example.java:3: error: unclosed string literal
System.out.println("hello world"");
^
1 error
error: compilation failed
shell returned 1
에러...
println 함수 괄호 속 두 번째 따옴표가 hello world라는 문자열의 끝으로 인식한 건 괜찮다.
다만, 에러가 난 이유는 세 번째 따옴표가 또 다른 문자열의 시작으로 인식했고,
세 번째 따옴표 이후의 문자열을 닫는 따옴표가 없어 unclosed string literal라는 에러가 났다.
(물론 네 번째 따옴표를 추가해도 문자열 형식에 맞지 않아 에러가 난다.)
이번엔 역슬래시를 해보자.
public class Main {
public static void main(String[] args) {
System.out.println("hello\ world");
}
}
hello\ world라는 문자열을 출력해 보자.
example.java:3: error: illegal escape character
System.out.println("hello\ world");
^
1 error
error: compilation failed
shell returned 1
에러 메세지를 보면, 불법? 이스케이프 문자를 사용했다고 에러가 난다.
그 이유는 역슬래시 문자는 문자열에서 이스케이프 문자를 표현할 때 쓰이기 때문이다.
이스케이프 문자란 특수 문자를 문자열에 삽입 시 사용한다.
이스케이프 문자 예시: 문자열에 개행 문자(새줄 문자) 넣기.
public class Main {
public static void main(String[] args) {
System.out.println("hello\n world");
}
}
\n 문자는 개행 문자를 뜻한다.
hello
world
\n 개행 문자 때문에 \n 문자 이후에 출력할 부분은 다음 줄에 출력된다.
이스케이프 문자를 사용하면 이제 큰따옴표와 역슬래시를 문자열에서 표현할 수 있다.
큰따옴표 표현하기.
public class Main {
public static void main(String[] args) {
System.out.println("hello\" world");
}
}
\" 문자로 큰따옴표 표현하기.
hello" world
에러 없이 큰따옴표를 출력했다.
역슬래시 표현하기.
public class Main {
public static void main(String[] args) {
System.out.println("hello\\ world");
}
}
\\ 문자로 역슬래시 표현하기.
hello\ world
문자열에 역슬래시 문자가 표현된 모습.
반응형
'코딩 > Java' 카테고리의 다른 글
자바 - 변수의 데이터 타입 확인 방법 (0) | 2024.04.20 |
---|---|
자바 - 형변환 에러 이유 "incompatible types: possible lossy conversion from int to byte" (0) | 2024.03.31 |
자바 - 변수에 숫자 값 할당 시 가독성 높이는 법 (int a = 1,000,000 가능?) (0) | 2024.03.24 |
Java - Switch 문 꿀팁 (중복 코드 간결화) (1) | 2023.12.02 |
자바 - float 변수에 실수 값을 그냥 넣으면 에러 나는 이유 (0) | 2023.11.23 |