创建字符串
String a = "hello";
String 类是不可改变的,一旦创建了 String 对象,那它的值就无法改变了
字符串长度
用于获取有关对象的信息的方法称为访问器方法。
String 类的一个访问器方法是 length() 方法,它返回字符串对象包含的字符数。
例子:
public class Aa{
public static void main(String args[]){
String a = "hello java!!!";
int len = a.length();
System.out.println("a的长度为:" + len);
}
}
输出结果:
a的长度为:13
连接字符串
String 类提供了连接两个字符串的方法:
- string1.concat(string2);
- 使用’+'操作符来连接字符串
例子:
public class Aa{
public static void main(String args[]){
String s1 = "hello ";
String s2 = "world";
String s3 = "!!!";
String s = s1.concat(s2) + s3;
System.out.println(s);
}
}
输出结果:
hello world!!!
创建格式化字符串
输出格式化数字可以使用 printf() 和 format() 方法
例子:
public class Aa{
public static void main(String args[]){
int i = 10;
double f = 3.14;
String s = "hello";
System.out.printf("整数:%d,浮点数:%f,字符串:%s\n",i,f,s);
String fs = String.format("整数:%d,浮点数:%f,字符串:%s",i,f,s);
System.out.println(fs);
}
}
输出结果:
整数:10,浮点数:3.140000,字符串:hello
整数:10,浮点数:3.140000,字符串:hello