Java 字符串
Java String 是最广泛使用的类之一。Java String 类在java.lang
包中定义。
Java 字符串
- 基本上,字符串是字符序列,但它不是原始类型。
- 当我们在 java 中创建一个字符串时,它实际上会创建一个 String 类型的对象。
- 字符串是不可变的对象,这意味着一旦创建就无法更改。
- String 是 Java 中唯一支持运算符重载的类。我们可以使用 + 运算符连接两个字符串。例如
"a"+"b"="ab"
。 - Java 提供了两个用于字符串操作的有用的类——StringBuffer和StringBuilder。
让我们继续了解有关 Java String 类的更多信息。
创建字符串的不同方法
在 Java 中创建字符串对象的方法有很多,下面给出了一些常用的方法。
-
使用字符串文字
这是创建字符串的最常见方式。在这种情况下,字符串文字用双引号括起来。
String str = "abc";
当我们使用双引号创建字符串时,JVM 会在字符串池中查找是否有其他字符串存储了相同的值。如果找到,它只会返回对该字符串对象的引用,否则它会创建一个具有给定值的新字符串对象并将其存储在字符串池中。
-
使用 new 关键字
我们可以使用 new 运算符创建 String 对象,就像任何普通的 java 类一样。String 类中有多个构造函数可用于从 char 数组、字节数组、StringBuffer 和 StringBuilder 获取 String。
String str = new String("abc"); char[] a = {'a', 'b', 'c'}; String str2 = new String(a);
Java 字符串比较
String 类提供equals()
和equalsIgnoreCase()
方法来比较两个字符串。这些方法比较字符串的值以检查两个字符串是否相等。true
如果两个字符串相等,则返回结果,false
否则返回结果。
package com.journaldev.string.examples;
/**
* Java String Example
*
* @author pankaj
*
*/
public class StringEqualExample {
public static void main(String[] args) {
//creating two string object
String s1 = "abc";
String s2 = "abc";
String s3 = "def";
String s4 = "ABC";
System.out.println(s1.equals(s2));//true
System.out.println(s2.equals(s3));//false
System.out.println(s1.equals(s4));//false;
System.out.println(s1.equalsIgnoreCase(s4));//true
}
}
上述程序的输出是:
true
false
false
true
String 类实现了Comparable接口,该接口提供compareTo()
和compareToIgnoreCase()
方法,并按字典顺序比较两个字符串。两个字符串都转换为 Unicode 值进行比较,并返回一个可以大于、小于或等于零的整数值。如果字符串相等,则返回零,否则返回大于或小于零。
package com.journaldev.examples;
/**
* Java String compareTo Example
*
* @author pankaj
*
*/
public class StringCompareToExample {
public static void main(String[] args) {
String a1 = "abc";
String a2 = "abc";
String a3 = "def";
String a4 = "ABC";
System.out.println(a1.compareTo(a2));//0
System.out.println(a2.compareTo(a3));//less than 0
System.out.println(a1.compareTo(a4));//greater than 0
System.out.println(a1.compareToIgnoreCase(a4));//0
}
}
上述程序的输出是:
0
-3
32
0
请在String compareTo 示例中阅读更详细的信息。
Java 字符串方法
让我们通过示例程序来看看一些流行的 String 类方法。
-
分裂()
Java String split() 方法用于使用给定的表达式拆分字符串。split() 方法有两种变体。
split(String regex)
:此方法使用给定的正则表达式拆分字符串并返回字符串数组。split(String regex, int limit)
:此方法使用给定的正则表达式拆分字符串并返回字符串数组,但数组元素受指定限制。如果指定限制为 2,则该方法返回大小为 2 的数组。
package com.journaldev.examples; /** * Java String split example * * @author pankaj * */ public class StringSplitExample { public static void main(String[] args) { String s = "a/b/c/d"; String[] a1 = s.split("/"); System.out.println("split string using only regex:"); for (String string : a1) { System.out.println(string); } System.out.println("split string using regex with limit:"); String[] a2 = s.split("/", 2); for (String string : a2) { System.out.println(string); } } }
上述程序的输出是:
split string using only regex: a b c d split string using regex with limit: a b/c/d
-
包含(CharSequence s)
Java String contains() methods checks if string contains specified sequence of character or not. This method returns true if string contains specified sequence of character, else returns false.
package com.journaldev.examples; /** * Java String contains() Example * * @author pankaj * */ public class StringContainsExample { public static void main(String[] args) { String s = "Hello World"; System.out.println(s.contains("W"));//true System.out.println(s.contains("X"));//false } }
Output of above program is:
true false
-
length()
Java String length() method returns the length of string.
package com.journaldev.examples; /** * Java String length * * @author pankaj * */ public class StringLengthExample { public static void main(String[] args) { String s1 = "abc"; String s2 = "abcdef"; String s3 = "abcdefghi"; System.out.println(s1.length());//3 System.out.println(s2.length());//6 System.out.println(s3.length());//9 } }
-
replace()
Java String replace() method is used to replace a specific part of string with other string. There are four variants of replace() method.
replace(char oldChar, char newChar)
: This method replace all the occurrence of oldChar with newChar in string.replace(CharSequence target, CharSequence replacement)
: This method replace each target literals with replacement literals in string.replaceAll(String regex, String replacement)
: This method replace all the occurrence of substring matches with specified regex with specified replacement in string.replaceFirst(String regex, String replacement)
: This method replace first occurrence of substring that matches with specified regex with specified replacement in string.
package com.journaldev.examples; /** * Java String replace * * @author pankaj * */ public class StringReplaceExample { public static void main(String[] args) { //replace(char oldChar, char newChar) String s = "Hello World"; s = s.replace('l', 'm'); System.out.println("After Replacing l with m :"); System.out.println(s); //replaceAll(String regex, String replacement) String s1 = "Hello journaldev, Hello pankaj"; s1 = s1.replaceAll("Hello", "Hi"); System.out.println("After Replacing :"); System.out.println(s1); //replaceFirst(String regex, String replacement) String s2 = "Hello guys, Hello world"; s2 = s2.replaceFirst("Hello", "Hi"); System.out.println("After Replacing :"); System.out.println(s2); } }
The output of above program is:
After Replacing l with m : Hemmo Wormd After Replacing : Hi journaldev, Hi pankaj After Replacing : Hi guys, Hello world
-
format()
Java Sting format() method is used to format the string. There is two variants of java String format() method.
format(Locale l, String format, Object… args)
: This method formats the string using specified locale, string format and arguments.format(String format, Object… args)
: This method formats the string using specified string format and arguments.
package com.journaldev.examples; import java.util.Locale; /** * Java String format * * @author pankaj * */ public class StringFormatExample { public static void main(String[] args) { String s = "journaldev.com"; // %s is used to append the string System.out.println(String.format("This is %s", s)); //using locale as Locale.US System.out.println(String.format(Locale.US, "%f", 3.14)); } }
Output of above program is:
This is journaldev.com 3.140000
-
substring()
This method returns a part of the string based on specified indexes.
package com.journaldev.examples; /** * Java String substring * */ public class StringSubStringExample { public static void main(String[] args) { String s = "This is journaldev.com"; s = s.substring(8,18); System.out.println(s); } }
String Concatenation
String concatenation is very basic operation in java. String can be concatenated by using “+” operator or by using concat()
method.
package com.journaldev.examples;
/**
* Java String concatenation
*
* @author pankaj
*
*/
public class StringConcatExample {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + s2;
//using + operator
System.out.println("Using + operator: ");
System.out.println(s3);
//using concat method
System.out.println("Using concat method: ");
System.out.println(s1.concat(s2));
}
}
Output of above program is:
Using + operator:
HelloWorld
Using concat method:
HelloWorld
Check this post for more information about String Concatenation in Java.
Java String Pool
Memory management is the most important aspect of any programming language. Memory management in case of string in Java is a little bit different than any other class. To make Java more memory efficient, JVM introduced a special memory area for the string called String Constant Pool. When we create a string literal it checks if there is identical string already exist in string pool or not. If it is there then it will return the reference of the existing string of string pool. Let’s have a look at the below example program.
package com.journaldev.examples;
/**
* Java String Pool Example
*
*/
public class StringPoolExample {
public static void main(String[] args) {
String a = "abc";
String b = "abc";
String c = "def";
//same reference
if (a==b) {
System.out.println("Both string refer to the same object");
}
//different reference
if (a==c) {
System.out.println("Both strings refer to the same object");
}else {
System.out.println("Both strings refer to the different object");
}
}
}
The output of above program is:
Both string refer to the same object
Both strings refer to the different object
Check this post for more about Java String Pool.
String intern() Method
When we create a string using string literal, it will be created in string pool but what if we create a string using new keyword with the same value that exists in string pool? Can we move the String from heap memory to string pool? For this intern() method is used and it returns a canonical representation of string object. When we call intern() method on string object that is created using the new keyword, it checks if there is already a String with the same value in the pool? If yes, then it returns the reference of that String object from the pool. If not, then it creates a new String with the same content in the pool and returns the reference.
package com.journaldev.examples;
/**
* Java String intern
*
* @author pankaj
*
*/
public class StringInternExample {
public static void main(String[] args) {
String s1 = "pankaj";
String s2 = "pankaj";
String s3 = new String("pankaj");
System.out.println(s1==s2);//true
System.out.println(s2==s3);//false
String s4 = s3.intern();
System.out.println(s1==s4);//true
}
}
Check this post to learn more about Java String intern method.
String Immutability Benefits
Some of the benefits of String being immutable class are:
- String Constant Pool, hence saves memory.
- Security as it’s can’t be changed.
- Thread safe
- Class Loading security
Check this post for more about Sting Immutablity Benefits.
Java 8 String join()
A new static method join() has been added in String class in Java 8. This method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. Let’s look at an example to understand it easily.
List<String> words = Arrays.asList(new String[]{"Hello", "World", "2019"});
String msg = String.join(" ", words);
System.out.println(msg);
Output: Hello World 2019
Java 9 String Methods
There are two methods added in String class in Java 9 release. They are - codePoints() and chars(). Both of these methods return IntStream object on which we can perform some operations. Let’s have a quick look at these methods.
String s = "abc";
s.codePoints().forEach(x -> System.out.println(x));
s.chars().forEach(x -> System.out.println(x));
Output:
97
98
99
97
98
99
Java 11 String Class New Methods
There are many new methods added in String class in Java 11 release.
- isBlank() - returns true if the string is empty or contains only white space codepoints, otherwise false.
- lines() - returns a stream of lines extracted from this string, separated by line terminators.
- strip(), stripLeading(), stripTrailing() - for stripping leading and trailing white spaces from the string.
- repeat() - returns a string whose value is the concatenation of this string repeated given number of times.
Let’s look at an example program for these methods.
package com.journaldev.strings;
import java.util.List;
import java.util.stream.Collectors;
/**
* JDK 11 New Functions in String class
*
* @author pankaj
*
*/
public class JDK11StringFunctions {
public static void main(String[] args) {
// isBlank()
String s = "abc";
System.out.println(s.isBlank());
s = "";
System.out.println(s.isBlank());
// lines()
String s1 = "Hi\nHello\rHowdy";
System.out.println(s1);
List lines = s1.lines().collect(Collectors.toList());
System.out.println(lines);
// strip(), stripLeading(), stripTrailing()
String s2 = " Java, \tPython\t ";
System.out.println("#" + s2 + "#");
System.out.println("#" + s2.strip() + "#");
System.out.println("#" + s2.stripLeading() + "#");
System.out.println("#" + s2.stripTrailing() + "#");
// repeat()
String s3 = "Hello\n";
System.out.println(s3.repeat(3));
s3 = "Co";
System.out.println(s3.repeat(2));
}
}
Output:
false
true
Hi
Hello
Howdy
[Hi, Hello, Howdy]
# Java, Python #
#Java, Python#
#Java, Python #
# Java, Python#
Hello
Hello
Hello
CoCo
That’s all about Java String class, it’s method and String manipulation examples.
You can checkout more String examples from our GitHub Repository.
Reference: API Doc