当前位置:网站首页>String analysis and use
String analysis and use
2022-06-10 21:55:00 【Hua Weiyun】
I finished my study today JAVA The first chapter of this lesson is the analysis and use of string classes , Finish this chapter , I have mastered the following two points , Namely String class 、StringBuffer and StringBuil class .
One .String Class analysis
String Class is often used before, but we haven't explained the specific knowledge points of this class and how to use this class , Then we will learn this class systematically . First pair String Class to do some analysis , Summarize the main knowledge points .
- String Class char Array holds data
- String It's a final class , uninheritable
- String Is an immutable class , After the object is generated , The content cannot be changed
- String Class String Member methods of type objects will return a new String Type object
Two .String Class comparison
String Class overridden equals() Method , Used to compare two strings Is the content the same . Similar to this is "==", This is also to compare whether it is the same , Just and equals() Compare things differently ,"==" Compare two String The address of the type object Are they the same? .
The case code is as follows :
public class StringDemo { public static void main(String[] args) { // TODO Auto-generated method stub String s1 = new String("123"); String s2 = new String("123"); System.out.println(s1==s2); String s3 = "234"; String s4 = "456"; System.out.println(s3==s4); System.out.println(s1.equals(s2)); }}3、 ... and . String class instantiation mechanism
Like other classes you create yourself ,String Classes also create object instances , Then let's learn Java How to create String Object's .
Java establish String There are two ways to object
- At the time of creation ,JVM You will now find whether the object exists in the string constant pool , If there is , Directly return the address of the string object , without , Just create the object in the constant pool and return the address
// The first way
String s1 = "123";
2. At the time of creation , It will also first look for the string in the constant pool , If there is , Just copy the object in the heap , And pass the address of the object in the heap to the variable ; If it doesn't exist , The string objects will be created in the heap and in the constant pool respectively , And return the address of the object in the heap , You create two objects and store them in two places
// The second way
String s2 = new String("123");
// Create objects only in the constant pool , Created an object
String s1 = "123";
// Create one object in the constant pool and one object in the heap , There are two in all
String s2 ="123”;
Four . String maintenance and parameter passing
String Class "+" and concat() Two strings can be spliced together , Form a new string . But the two are different , The difference is "+" String and non string can be spliced together , and concat() Only strings and strings can be concatenated . The case code is as follows :
public class StringDemo2 { public static void main(String[] args) { String s1 = "123"; System.out.println(s1+123); System.out.println(s1.concat("123")); }}String Parameter transfer of : First look at the code
public static void main(String[] args) { String s1 = new String("123"); show(s1); System.out.println(s1); } public static void show(String s) { s = "234"; }}Look at the output of this code 123 still 234 Well ? yes 123, Next, let's talk about why 123, Let's talk about the process of transferring parameters .
- We are main Function to create a new object 123, And then sent its address to s1, So now s1 What's stored is 123 Address in the pile
- call show() Method , And the s1 Pass in , Shape parameter s Copied arguments s1 Value , That is to say s1 Stored address , Now? s It also points to 123 The address in the heap .
- Get into show Method post execution s="234", Is to put 234 This object is assigned to s,s The address stored in is 234 The address of . But this operation is for arguments s1 No impact ,s1 It's still stored in 234 The address of .
- show() After the end , Shape parameter s disappear , object 234 Because there is no reference to it , So it will be recycled by the garbage collection mechanism .
- Print s1 still 123
5、 ... and . Common use of strings API Method
String Common methods of class :
- equals(): Used to compare whether the contents of two strings are the same
- charAt(): Returns the character at the specified index
- contains(): Determine whether the string contains another string
- indexOf(): Returns the index of the first occurrence of a string
- isEmpty(): Determine whether the string is empty
- split(): Splits the string in the specified format , Return string array
- trim(): Remove spaces at the beginning and end of a string
- toCharArray(): Convert string to character array
- replace(): Replace a character or string in a string , All replacement
- length(): Returns the length of the string
The case code is as follows :
import java.util.Arrays;public class StringDemo4 { public static void main(String[] args) { String s = "hello world"; System.out.println(s.charAt(1));//e System.out.println(s.contains("e")); System.out.println(s.indexOf("e"));// If you can't find it , return -1 System.out.println(s.isEmpty());//false String[] ss = s.split(" ");// Split the string with a space as a flag System.out.println(Arrays.toString(ss)); System.out.println(s.trim()); char[] sss = s.toCharArray(); System.out.println(Arrays.toString(sss)); System.out.println(s.replace("l", "e")); System.out.println(s.lastIndexOf("l"));//9 Returns the last occurrence of the index }}6、 ... and .StringBuffer class
StringBuffer Also called variable character sequence , Thread safe variable character sequence . It is a similar to String String buffer for , Can't modify , But you can change the contents and length of the sequence by calling some methods . You can put StringBuffer Think of it as a container , This container contains many strings , And you can manipulate these strings .StringBuffer It is synchronous and safe , This follow-up will talk about , When sharing resources with multiple threads, it is necessary to ensure synchronization safety
public class StringDemo4 { public static void main(String[] args) { // Create an empty object StringBuffer StringBuffer sb = new StringBuffer(); System.out.println(sb); System.out.println(sb.capacity());// The size of the output container The buffer defaults to 16 System.out.println(sb.length());// The length of the output object // Create a string buffer of the specified size StringBuffer sb2 = new StringBuffer(50); System.out.println(sb2); System.out.println(sb2.capacity()); System.out.println(sb2.length()); // Create a string buffer for the specified string contents StringBuffer sb3 = new StringBuffer("hello"); System.out.println(sb3); System.out.println(sb3.capacity());// The default is 16, Now? hello The length is 5, The capacity is added to 21 了 System.out.println(sb3.length()); } //StringBuffer It's a sequence of variable strings , Capacity and length can be changed }7、 ... and .StringBuilder class
StringBuil and StringBuffer similar , Are all string buffers , Asynchronous security
package com.huawei.string;/* * StringBuilder It is also a string buffer , Out of sync . If you want to compare two StringBuilder Are the instances the same , To convert to String class */public class StringDemo5 { public static void main(String[] args) { String str = new String("abc"); StringBuilder stringBuilder = new StringBuilder(str); System.out.println(" Generate a string buffer using a parameterized constructor "+stringBuilder);// Got it abc, Because it is stored in the string buffer abc // Use the empty construction method to create StringBuilder object StringBuilder builder = new StringBuilder(); System.out.println(" Null parameter constructed string buffer "+builder); //StringBuilder No rewriting equals() If you have to compare StringBuilder Is the content the same , Then you have to StringBuilder convert to String String s1 = builder.toString(); StringBuilder builder2 = new StringBuilder(); System.out.println(" Null parameter constructed string buffer "+builder2); String s2 = builder2.toString(); // First, compare the two directly StringBuilder Example System.out.println(builder.equals(builder2));//false, There is no content in these two instances , It should be the same , But the output is false, So to compare , It must be converted into String System.out.println(s1.equals(s2));//true }}Now let's summarize String,StringBuffer,StringBuilder The difference between :
- String The content is variable
- StringBuffer and StringBuilder The content of is variable
- StringBuffer It's synchronous , Data is secure but inefficient
- StringBuilder It's not synchronous , Data is insecure but efficient
You can know from the following code results ,sb Is always less than 1000, and sb1 The value of is always 1000, therefore StringBuild It's out of sync
public class Test { StringBuilder sb = new StringBuilder(); StringBuffer sb1 = new StringBuffer(); public Test() { // Create thread groups to manage threads ThreadGroup group = new ThreadGroup("testGroup"); // Create thread class objects MyThread at = new MyThread(); // Turn on 100 Threads for(int i=0;i<1000;i++) { Thread th = new Thread(group,at,String.valueOf(i)); th.start(); } while(group.activeCount()>0) {// This method returns the number of thread groups in the current thread of the active thread try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(sb.length()); System.out.println(sb1.length()); } class MyThread implements Runnable{ @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } sb.append("1"); sb1.append("1"); } } public static void main(String[] args) { new Test(); //StringBuilder To reach 1000, Out of sync ,StringBuffer Has always been a 1000, It's synchronous }}8、 ... and . summary
After learning these contents, I have mastered String Class
边栏推荐
- Factory and strategy mode implementation scheme of coupons
- 防抖和节流
- 旋转导航栏
- Fast Planner - detailed explanation of kinetic astar
- 信号与系统复习1
- Explain in detail the arithmetic operators related to matrix operation in MATLAB (addition, subtraction, multiplication, division, point multiplication, point division, power)
- LeetCode 进阶之路 - 167.两数之和 II - 输入有序数组
- Understanding of related concepts of target detection
- Leetcode advanced road - 167 Sum of two numbers II - input ordered array
- C language -- 11 branch statement if else
猜你喜欢

ThinkPHP v6.0.x反序列化漏洞复现

NFT版权/版税

About type-C
![[qingniaochangping campus of Peking University] the coordinated development of vocational education and general education, will this year's high school entrance examination be easy?](/img/3a/1376593d02adf29a1c37d894dcc0fa.png)
[qingniaochangping campus of Peking University] the coordinated development of vocational education and general education, will this year's high school entrance examination be easy?

Intelligent robot making progress in imitation learning
![[nk] 牛客月赛51 F-平均题](/img/b3/c36a0032e606f38fdc2f7c4562713c.png)
[nk] 牛客月赛51 F-平均题

Cas de test app

C language -- 1 c language cognition

微积分复习1

^29 event cycle model
随机推荐
自制Table錶格
自制Table表格
Mysql之將查詢結果插入到其它錶中
蛮力法/1~n个整数中取k个整数
ThinkPHP v6.0. X deserialization vulnerability recurrence
Leetcode advanced road - 69 Square root of X
Acl2022 | bert2bert: an efficient pre training method of parameter reuse, which significantly reduces the training cost of oversized models
实用 | 如何利用 Burp Suite 进行密码爆破!
Understanding deep learning attention
LeetCode 进阶之路 - 125.验证回文串
Cordova Plugin /JPush PhoneGap 极光推送_本地推送_消息推送
Full Permutation V3 recursion of brute force method /1~n
01js basic null and undefined difference type conversion = = code block logical operator
蛮力法/1~n的幂集 v4 递归
在模仿学习中进步的智能机器人
What do software test engineers do?
Standard dual airbags, starting from 48900 for butcher Chang'an Lumin
As a programmer, is it really that important for the underlying principles?
自媒体视频创作如何选择领域?
About type-C