如何在 Java 9 中的 JShell 中实现字符串实用程序和不变性?

javaobject oriented programmingprogramming更新于 2025/10/25 20:28:17

JShell  是一个交互式 命令行 工具,用于实现简单语句,如表达式、类、方法、字段、接口等。String 类是内置 java.lang 包的一部分,并提供了几种用于常见文本处理的方法。

1) 字符串实用程序:String 提供了几种内置实用程序方法。 indexOf()、lastIndexOf()、startsWith()、endsWith()、isEmpty()、equals()、equalsIgnoreCase() 等方法属于字符串实用程序的一部分。

在下面的代码片段中,我们在 JShell 工具中实现了字符串实用程序方法。

Snippet-1

jshell> String str = "JShell is a new feature in Java9";
str ==> "JShell is a new feature in Java9"

jshell> str.indexOf("new")
$4 ==> 12

jshell> str.charAt(7)
$5 ==> 'i'

jshell> str.indexOf('i')
$6 ==> 7

jshell> str.lastIndexOf('i')
$7 ==> 24

jshell> str.contains("feature")
$8 ==> true

jshell> str.startsWith("JShell")
$9 ==> true

jshell> str.startsWith("Java9")
$10 ==> false

jshell> str.endsWith("Java9")
$11 ==> true

jshell> str.endsWith("a9")
$12 ==> true

jshell> str.endsWith("a9java")
$13 ==> false

jshell> String str1 = "value"
str1 ==> "value"

jshell> str1.equals("value")
$15 ==> true

jshell> str1.equals("VALUE")
$16 ==> false

jshell> str1.equalsIgnoreCase("VALUE")
$17 ==> true

2) 字符串不可变性:字符串对象是不可变的,这意味着我们不能在创建它们之后更改它们的值。

在下面的代码片段中,String 类的方法concat()将两个 String 对象的内容合并为一个。但是,"str"引用的原始值保持不变。concat()方法将创建一个新的 String 对象。与concat()方法一样,其他 String 方法(例如toUpperCase()、toLowerCase()和trim()方法)返回新的 String 对象。

代码片段-2

jshell> String str = "Tutorialspoint";
str ==> "Tutorialspoint"

jshell> str.concat(" is e-learning app");
$3 ==> "Tutorialspoint is e-learning app"

jshell> str
str ==> "Tutorialspoint" ^

jshell> String str1 = str.concat(".")
str1 ==> "Tutorialspoint."

jshell> str1
str1 ==> "Tutorialspoint."

jshell> String str = str.concat(" is e-learning app");
str ==> "Tutorialspoint is e-learning app"

jshell> str
str ==> "Tutorialspoint is e-learning app"

jshell> String str1 = "Tutorialspoint";
str1 ==> "Tutorialspoint"

jshell> str1.concat(" is e-learning app");
$2 ==> "Tutorialspoint is e-learning app"

jshell> str1
str1 ==> "Tutorialspoint"

jshell> String str2 = str1.concat(" is e-learning app");
str2 ==> "Tutorialspoint is e-learning app"

jshell> str1
str1 ==> "Tutorialspoint"

jshell> String str3 = str2.concat(".");
str3 ==> "Tutorialspoint is e-learning app."

jshell> str1
str1 ==> "Tutorialspoint"

jshell> str2
str2 ==> "Tutorialspoint is e-learning app"

jshell> String s = "Tutorialspoint is e-learning app."
s ==> "Tutorialspoint is e-learning app."

jshell> s.toUpperCase()
$10 ==> "TUTORIALSPOINT IS E-LEARNING APP."

jshell> s.toLowerCase()
$11 ==> "tutorialspoint is e-learning app."

相关文章


有用资源