11. Java字符串

Java字符串

在前面的章节中,我们知道 Java的数据类型分为 基本数据类型引用数据类型

Java的字符串,类型为 String ,就属于引用数据类型

在实际的Java编码过程中,字符串的使用是远处不在的。

这一小节我们就来讲解 Java的字符串

1 什么是字符串 ?

字符串(String) 就是0个或者多个字符组成的序列,简单来说,字符串就是一串字符

在我们的第一个Java程序中,打印的第一句话 “hello,world” 就属于一个字符串

2 创建字符串

2.1 直接创建

这是创建字符串最简单的方式:

String str = "HelloWorld开发者社区";

2.2 使用构造函数创建

String str = new String("HelloWorld开发者社区");

3 字符串的内存分布

  • 通过 String str = "HelloWorld开发者社区"; 这种方式定义的字符串,字符串 “HelloWorld开发者社区” 是存在于常量池中

  • 通过 String str = new String("HelloWorld开发者社区"); 构造函数定义的字符串,字符串 “HelloWorld开发者社区” 是存在于堆中

示例:

public class HelloWorld { public static void main(String[] args) { // 此时 s, s1, s2 都指向常量池中的同一个字符串 "abc" String s = "abc"; String s1 = "abc"; String s2 = s; // 此时 s4 ,s5 对应的字符串"hello,world"存在于堆中 String s4 = new String("hello,world"); String s5 = s4; } }

从上面的示例代码以及注释中,可以知道

  • 直接使用String 定义字符串,存在于常量池中
  • 使用构造函数定义的字符串,存在于堆中

可以使用下面的一张图来解释

image-20210629211318906

Java的内存区域中,有两个区,一个是常量池,一个是堆。现在不需要知道

后面会讲解,只要知道有这2个区,不同方式定义的字符串是在不同的区域中就行了

注意:String类是不可以改变的,一旦创建了字符串就不能再对其进行修改了

如果需要对字符串进行修改,应该使用 StringBuffer 或者 StringBuilder

4 字符串长度

定义的字符串是有长度的,空字符串,即 String str = "";长度是 0

String 类的 length() 方法就是获取字符串的长度

如下:

public class HelloWorld { public static void main(String[] args) { String str = "example.com"; System.out.println("HelloWorld开发者社区网址长度是:" + str.length()); } } //输出如下 : HelloWorld开发者社区网址长度是:18

5 字符串的连接

5.1 使用 concat() 方法

用法: str1.concat(str2) , 返回一个新的字符串

如下示例:

public class HelloWorld { public static void main(String[] args) { String s1 = "hello "; String s2 = "world"; String s = s1.concat(s2); System.out.println(s); } } //输出: hello world

5.2 使用 + 号连接字符串

用法: str1 + str2

把上面的例子改成使用 + 连接字符串,如下:

public class HelloWorld { public static void main(String[] args) { String s1 = "hello "; String s2 = "world"; String s = s1 + s2; System.out.println(s); } } //输出:hello world

5.2.1 使用 + 可以连接不同类型的变量

比如: 字符串 + 数, 字符串 + boolean 等,返回的是一个新的字符串

如下示例:

public class HelloWorld { public static void main(String[] args) { String str = "hello : "; int a = 100; boolean b = true; System.out.println(str + a); System.out.println(str + b); } } //输出如下: hello : 100 hello : true

事实上,使用 + 连接字符串用的最多

6 创建格式化的字符串

String 类有一个静态方法,可以将各种类型的数据格式化到一起,通过占位符,来确定不同的类型,并返回格式化后的字符串

如下示例:

public class HelloWorld { public static void main(String[] args) { String site = "example.com"; String name = "待兔"; int year = 2; // 格式化字符串, %s, %d 分别代表字符串和整数,也就是占位符 // 这些占位符与后面的变量相对应 String str = String.format("%s 网站的创建是 %s , 网站成立 %d 年了",site,name,year); System.out.println(str); } } //输出: example.com 网站的创建是 待兔 , 网站成立 2 年了

小结

  • 字符串就是一串字符
  • 可以使用 String str = "hello,world"; 这种方式创建字符串
  • 也可以使用 String str = new String("hello,world"); 构造函数的方法创建字符串
  • 直接使用定义变量的方式创建的字符串,是在常量池中
  • 通过构造函数创建的字符串,字符串是在堆上
  • 可以通过 concat() 方法连接字符串
  • 也可以使用 +连接字符串,用的最多的就这种方法
  • 可以使用 String.format()方法通过占位符的方式 ,格式化字符串