在Java编程中广泛使用的字符串是字符序列。String类是不可变的,因此一旦创建它,就不能更改String对象。如果有必要对字符串进行大量修改,则应使用字符串缓冲区和字符串生成器类。
现在让我们看看如何在Java中创建字符串-String str = “John”;
new关键字用于创建数组甚至字符串。让我们看看如何-String str = new String(“John”);
字符串类在Java中有很多方法可以操作字符串,查找长度,格式化字符串,连接等。让我们看一些示例-
在这里,我们将找到字符串的长度并将其连接-
示例public class Main {
public static void main(String args[]) {
String str1 = "This is ";
String str2 = "it!";
System.out.println("String1 = "+str1);
System.out.println("String2 = "+str2);
int len1 = str1.length();
System.out.println( "String1 Length = " + len1 );
int len2 = str2.length();
System.out.println( "String2 Length = " + len2 );
System.out.println("Performing Concatenation...");
System.out.println(str1 + str2);
}
}
输出结果String1 = This is
String2 = it!
String1 Length = 8
String2 Length = 3
Performing Concatenation...
This is it!