在 Java 中,可以使用 '${}' 来获取变量的值或表达式的结果。这通常用于字符串模板中,例如:

String name = 'Alice';
int age = 25;
String message = 'My name is ${name} and I am ${age} years old.';
String interpolated = message.replace('${name}', name).replace('${age}', Integer.toString(age));
System.out.println(interpolated); // My name is Alice and I am 25 years old.

在上面的示例中,我们使用 '${}' 来引用变量 name 和 age,然后使用 replace() 方法将其替换为相应的值。最终,我们得到了插值后的字符串 interpolated。

注意,'${}' 中可以是任何有效的 Java 表达式,例如:

int x = 10;
int y = 20;
String result = 'The sum of ${x} and ${y} is ${x + y}.';

在这个例子中,我们使用 '${}' 来计算 x 和 y 的和,并将结果插入到字符串中。最终,result 的值为 'The sum of 10 and 20 is 30.'。

Java 字符串插值:使用 ${} 获取变量值

原文地址: https://www.cveoy.top/t/topic/oYHP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录