Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the usage methods of the String class in Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to use the String class in Java. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.

String

String class:

Represents a string, provides a common string processing method in development, such as: find the length of the string, intercept the string, replace the string and other methods, the string is a constant, its value can not be modified after creation.

First of all, let's check the official documentation to see what method the official has set for the String class: String is also a java.lang package, so there is no need to import, here is part of the show, all the content can be referred to:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html

Several common methods:

charAt(int index):

Input character subscript, intercept character, return value is char type:

String str = "hello world"; char a = str.charAt(0); System.out.println(a);

//Output: h

compareTo(String anotherString): Compare two strings that match the first characters with different subscripts, return the difference between ASCII codes, ignore case, return String type:

String str = "hello world";int a = str.compareTo("Aello world");System.out.println(a);

//h and A ratio, output 39

compareToIgnoreCase(String str): compares two strings in dictionary order, ignoring case, returns String type:

String str = "hello world";int a = str.compareToIgnoreCase("Aello world");System.out.println(a);

//h and A ratio, output 7

concat(String str): concatenate strings:

String str = "hello world";String a = str.concat("abc");System.out.println(a);

//output: hello worldabc

contains(CharSequence s): See if the string contains a value, return Boolean value:

String str = "hello world";boolean a = str.contains("e"); //pass the value to be judged System.out.println(a)

//Output: true

boolean a = str.contains("a"); //determine aSystem.out.println(a);

//output false

endsWith(String suffix): Determines whether to return a Boolean value with the specified end (can be determined by the user mailbox suffix):

String str = "1234567489@qq.com";boolean a = str.endsWith("@ qq.com"); //Content to be judged System.out.println(a);

//Output: true

startsWith(String prefix): Determines whether a string starts with a specified prefix: (URL determination) Returns a Boolean value:

String str = "www.baidu.com";boolean a = str.startsWith("www");System.out.println(a);

//Output: true

equals(Object anObject): compares a string with a specified string for equality, case sensitive, returns a Boolean value:

String str = "www.baidu.com";boolean a = str.equals("Www.baidu.com"); //Change the first w to capital WSystem.out.println(a);

//Output: false

//if both are the same, output true

equalsIgnoreCase(String anotherString): compares a string to a specified string for equality, case insensitive, returns a Boolean value:

String str = "www.baidu.com";boolean a = str.equalsIgnoreCase("Www.Baidu.com"); //Change the first w to upper case WSystem.out.println(a);//After case insensitivity, even if one or more characters are changed to upper case, it does not affect judgment

//output true

indexOf(String str): Returns the index of the first occurrence of the specified value in a string, int type:

String str = "www.baidu.com";int a = str.indexOf("a"); //determine aSystem.out.println(a);

//Output: 5

lastIndexOf(String str): Returns the index of the specified value last found in a string, returns int type:

String str = "www.baidu.com";int a = str.indexOf("a"); //determine a, because this string has only one a, so it is still 5System.out.println(a);

//Output: 5

length(): Returns the length of a string, int type:

String str = "www.baidu.com";int a = str.length();System.out.println(a);

Output: 13

toLowerCase(): converts a string to lowercase, if it is lowercase, leave it unchanged, and return String type:

String str = "www.BAIDU.com";String a = str.toLowerCase();System.out.println(a);

//Output: www.baidu.com

toUpperCase(): Convert a string to capital letters:

String str = "WWW.BAIDU.COM";String a = str.toLowerCase();System.out.println(a);

//Output: WWW.BAIDU.COM

trim(): Remove white space from both ends of a string:

String str = " www.baidu.com "; //String a = str.trim();System.out.println(a);

//Output: www.baidu.com

String substring(int initiIndex,int endIndex): intercept string (index contains initiIndex, does not contain endIndex):

String str = "www.baidu.com";String a = str.substring(0,6); //truncate subscript 0 beginning and ending with 6 (excluding subscript 6 characters) System.out.println(a);

//Output: www.ba

String method there are many, here is not listed one by one, you can refer to the official website documentation to use

However, a String object has a fixed length and cannot change its contents or append new characters to it. In fact, this sometimes does not meet the business needs, there is always a need to change the string, so Java gives StringBuffer and StringBuilder two string buffer variable string.

StringBuffer and StringBuilder:

First look at the official introduction:

Simply put, StringBuffer is a variable character sequence. The length and content of the column can be changed by calling certain methods. Some StringBuffer methods are as follows. For details, please refer to:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuffer.html

Officially, the append method is overloaded to meet the needs of different business logic. Because StringBuffer is a class, you need to create a class to use it:

public class StringBuffertest { public static void main(String[] args) { String str = "hello world"; StringBuffer s = new StringBuffer(str); //Create a StringBuffer class, which is the same as creating a normal class s.append("hello world"); //use the append method of StringBuffer System.out.println(s); }}

//output: hello worldhello world

//This completes the string modification

The usage of StringBuilder is the same:

String str = "hello world";StringBuilder s = new StringBuilder(str);

What is the difference between StringBuilder and StringBuffer?

Mutability: String immutable character sequences, Builder and Buffer are mutable character sequences

Security: String is thread-safe, StringBuilder is thread-unsafe, StringBuffer is thread-safe. StringBuffer is more efficient than StringBuffer. Because String is immutable, it is usually the least efficient.

Usage scenario: If the string basically does not need to be changed after creation, use the String type, if you need to change the operation more, use StringBuilder, if you require thread safety, use StringBuffer.

Benefits of StringBuffer and StringBuilder classes:

Objects can be modified multiple times without creating new unused objects

String class summary:

What are the characteristics of String:

Immutability: String is a read-only string, is a typical immutable object, any operation on it, in fact, is to create a new object, and then refer to the object. The main purpose of immutable patterns is to ensure data consistency when an object needs to be shared and frequently accessed by multiple threads.

Constant pool optimization: String objects are cached in the string constant pool after they are created, and cached references are returned directly the next time the same object is created.

final: Use final to define the String class, indicating that the String class cannot be inherited, improving the security of the system.

Small extensions: what is a string constant pool?

String constant pool is located in heap memory and is specially used to store string constants. It can improve memory utilization and avoid opening up multiple blocks of space to store the same string. When creating a string, JVM will first check the string constant pool. If the string already exists in the pool, it will return its reference. If it does not exist, it will instantiate a string and put it in the pool and return its reference.

Difference between char and string constants:

Formally: A character constant is a character enclosed in single quotes A string constant is a number of characters enclosed in double quotes

Meaning: character constant equivalent to an integer value (ASCII value), can participate in expression operations, string constant represents an address value (the string in memory storage location)

Memory size: character constants occupy only one byte string constants occupy several bytes (at least one end-of-character flag)

Note in particular that we know that arrays also have length(), which is used to determine the length of the array:

int [] a = {1,2,3,4,5};system.out.println(a.length);

//Output: 5

But be careful:

Length() in array is attribute, length() in String is method!! Length() in array is attribute, length() in String is method!! Length() in array is attribute, length() in String is method!!

Thank you for reading! About "Java String class what use methods" this article is shared here, I hope the above content can have some help for everyone, so that we can learn more knowledge, if you think the article is good, you can share it to let more people see it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report