JShell (Java 9 REPL) giúp thực thi, đánh giá chương trình Java đơn giản: statement, loop, expression... Môi trường programming đơn giản command-line: read → evaluate → print.
Ví dụ thao tác String trong JShell
jshell> String str = "{abcd}";
str ==> "{abcd}"
jshell> str.substring(2, str.length() - 1)
$7 ==> "bcd"
jshell> String s1 = new String("abcd");
s1 ==> "abcd"
jshell> String s2 = new String("abcd");
s2 ==> "abcd"
jshell> s1 == s2
$10 ==> false
jshell> s1.equals(s2)
$11 ==> true
jshell> String s3 = "abcd";
s3 ==> "abcd"
jshell> String s4 = "abcd";
s4 ==> "abcd"
jshell> s3 == s4
$14 ==> true
jshell> s3.equals(s4)
$15 ==> true
jshell> s1 == s3
$16 ==> false
jshell> s1.equals(s3)
$17 ==> true
jshell> String s5 = "a" + "bcd";
s5 ==> "abcd"
jshell> s3 == s5
$19 ==> true
jshell> "abcd".getBytes()
$20 ==> byte[4] { 97, 98, 99, 100 }
jshell> "abcd".getBytes("UTF-16")
$22 ==> byte[10] { -2, -1, 0, 97, 0, 98, 0, 99, 0, 100 }
jshell> String raw = "1|2|3|4";
raw ==> "1|2|3|4"
jshell> raw.split("\\|")
$24 ==> String[4] { "1", "2", "3", "4" }
Giải thích hành vi
| Biểu thức | Kết quả | Giải thích |
|---|---|---|
new String("abcd") | Object mới mỗi lần | Heap allocation, == false |
"abcd" (literal) | String pool (interned) | == true cho cùng literal |
"a" + "bcd" | Compile-time constant folding | Gộp thành "abcd" → pool → == true |
getBytes() | Default charset (UTF-8) | 1 byte/char ASCII |
getBytes("UTF-16") | UTF-16 with BOM | 2 byte/char + 2 byte BOM |
split("\\|") | Regex split | Escape | vì là meta-char |
Phương thức String hữu ích khác (Java 9+)
chars(),codePoints()→ IntStream.strip(),stripLeading(),stripTrailing()(Java 11) – Unicode aware trim.isBlank()(Java 11) – chỉ whitespace.lines()(Java 11) – Stream<String> theo dòng.repeat(int)(Java 11) – lặp chuỗi.
JShell là sandbox hoàn hảo để khám phá String API, hiểu string interning, encoding, regex.