In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the common interview questions of String in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the common String interview questions in Java?"
String basic Java String class
Strings are widely used in Java programming, where strings belong to objects in Java, and Java provides String classes to create and manipulate strings.
Create a string
The easiest way to create a string is as follows:
String greeting = "rookie tutorial"
When you encounter a string constant in your code, the value here is "Rookie tutorial", which the compiler uses to create a String object.
Like other objects, you can use keywords and constructors to create String objects.
The String class has 11 constructors that provide different parameters to initialize the string, such as a character array parameter:
StringDemo.java file code: public class StringDemo {public static void main (String args []) {char [] helloArray = {'ringing,' upright, 'nasty,' oval, 'oval,' b'}; String helloString = new String (helloArray); System.out.println (helloString);}}
The compilation and running results of the above examples are as follows:
Runoob
Note: the String class is immutable, so once you create a String object, its value cannot be changed (see the notes section for more information).
If you need to make a lot of changes to the string, you should choose to use the StringBuffer & StringBuilder class.
Common methods of creating String objects in the basic usage of String
(1) String S1 = "mpptest"
(2) String S2 = new String ()
(3) String S3 = new String ("mpptest")
The methods commonly used in String are used as shown in the figure. Ask du Niang specifically.
The use of three methods: lenth () substring () charAt () package com.mpp.string; public class StringDemo1 {public static void main (String [] args) {/ / define a string "it's getting dark, snow is coming, can we have a drink, man?" String str = "it's getting dark, snow is coming, can we have a drink, man"; System.out.println ("the length of the string is:" + str.length ()) / / the snow word printout of the string charAt (int index) System.out.println (str.charAt (4)); / / take out the substring System.out.println (str.substring (2)); / / take out the substring from index2 to the end, including 2 System.out.println (str.substring (2)) / / remove the substrings of index from 2 to 4, including 2 excluding 4 regardless of head and tail}}
The use of two methods to find the first / last occurrence of a character or substring in a string: indexOf () lastIndexOf ()
Package com.mpp.string; public class StringDemo2 {public static void main (String [] args) {String str = new String ("Zhao Ke Hu Ying Wu Gou Hu Tuan Shuang Xueming"); / / find the position where Hu first appears in the string System.out.println ("\" Hu\ "first appears in the string:" + str.indexOf ("Hu")) / / find the position where the substring "Hu Ying" appears for the first time in the string System.out.println ("\" Hu Ying\ "the first occurrence position in the string" + str.indexOf ("Hu Ying")); / / find the position where Hu appears for the last time in the string System.out.println (str.lastIndexOf ("Hu")) / find the position of the last occurrence of the substring "Hu Ying" in the string System.out.println (str.lastIndexOf ("Hu Ying")); / / from the position where indexof is 5, find the first "Wu" System.out.println (str.indexOf ("Wu", 5));}} the conversion package com.mpp.string; import java.io.UnsupportedEncodingException between the string and the byte array Public class StringDemo3 {public static void main (String [] args) throws UnsupportedEncodingException {/ / conversion between string and byte array String str = new String ("hhhabc silver saddle shining white horse is like a meteor"); / / convert the string to byte array and print out byte [] arrs = str.getBytes ("GBK"); for (int iTuno Tinci) {System.out.print (arrs [I]) } / / convert the byte array to the string System.out.println (); String str1 = new String (arrs, "GBK"); / / keep the character set consistent, otherwise there will be garbled System.out.println (str1);}} the difference between the = = operator and equals: what the reference points to and the address that the reference points to
Package com.mpp.string; public class StringDemo5 {public static void main (String [] args) {String str1= "mpp"; String str2 = "mpp"; String str3 = new String ("mpp"); System.out.println (str1.equals (str2)); / / true content same System.out.println (str1.equals (str3)); / / true content same System.out.println (str1==str2) / / same true address System.out.println (str1==str3); / / different false address}} string immutability
Once an object in String is created, it cannot be modified and is immutable
The so-called modification actually creates a new object and points to the same memory space.
In the image above, S1 no longer points to the memory space where imooc is located, but to hello,imooc.
String connection @ Testpublic void contact () {/ / 1 connection String S1 = "a"; String S2 = "a"; String S3 = "a" + S2; String S4 = "a" + "a"; String S5 = S1 + S2; / / when the expression is constant, the runtime is calculated when the compilation time is complete and / / the expression has variables, so the address is different System.out.println (S3 = = S4) / / f System.out.println (S3 = = S5); / f System.out.println (S4 = = "aa"); / / t} the difference between String, String builder and String buffer
String is a basic and important class in Java, and String is also a typical implementation of the Immutable class, which is declared as final class, and all other properties except hash are declared as final. Because of its immutability, for example, a lot of useless intermediate objects will be generated when concatenating strings, and frequent such operations will affect performance.
StringBuffer is to solve a large number of string splicing generated a lot of intermediate object problems and provide a class, provide append and add methods, you can add the string to the end of the existing sequence or specified location, its essence is a thread-safe modifiable character sequence, all the methods to modify the data are added with synchronized. But ensuring thread safety comes at a cost of performance.
In many cases, our string concatenation operation does not require thread safety, when StringBuilder comes on stage. StringBuilder is released by JDK1.5, which is essentially no different from StringBuffer, except that the part that ensures thread safety is removed and the overhead is reduced.
Both StringBuffer and StringBuilder inherit AbstractStringBuilder, and both take advantage of the modifiable char array (JDK 9 is followed by the byte array).
Therefore, if we have a large number of string concatenation, if we can predict the size, it is best to set capacity in new StringBuffer or StringBuilder to avoid the overhead of multiple capacity expansion. To expand the capacity, you need to discard the original array and copy the array to create a new array.
When we usually develop a small amount of string concatenation, we don't need to worry about it, for example
String str = "aa" + "bb" + "cc"
For strings without variables like this, the compilation phase will directly synthesize "aabbcc", and then see if there is any in the string constant pool (we will talk about the constant pool below). It will also be referenced directly. If not, it will be generated in the constant pool and the reference will be returned.
If it is with variables, in fact, the impact is not great, JVM will help us optimize it.
1. String is preferred in business scenarios where strings do not often change (the code is clearer and more concise). Such as constant declarations, a small number of string operations (concatenation, deletion, etc.).
2. In the case of single thread, if there are a large number of string operations, StringBuilder should be used to manipulate strings. Instead of using String "+", you can use it to avoid producing a large number of useless intermediate objects, space-consuming and inefficient execution (it takes a lot of time to create new objects and recycle objects). Such as JSON packaging and so on.
3. In the case of multithreading, if there are a large number of string operations, StringBuffer should be used. Such as HTTP parameter parsing and encapsulation.
String class source code analysis String type internpublic void intern () {/ / 2:string intern use / / S1 is the basic type, compare values. S2 is a string instance. Comparing instance address / / string types with the equals method will only compare the value String S1 = "a"; String S2 = new String ("a"); / / when calling intern, if the character in S2 is not in the constant pool, join the constant pool and return the constant reference String S3 = s2.intern (); System.out.println (S1 = = S2); System.out.println (S1 = = S3) } equals method of equals// string of type String / / public boolean equals (Object anObject) {/ / if (this = = anObject) {/ / return true;//} / / if (anObject instanceof String) {/ / String anotherString = (String) anObject;// int n = value.length / / if (n = = anotherString.value.length) {/ / char v1 [] = value;// char v2 [] = anotherString.value;// int I = 0 / / while (nMel -! = 0) {/ / if (v1 [I]! = v2 [I]) / / return false;// iTunes / / return true / /} / return false;//} StringBuffer and Stringbuilder
The bottom layer is the variable character array value that inherits the parent class
/ * *-The value is used for character storage. * / char [] value; initialization capacity is 16 Universe Constructs a string builder with no characters init and an- initial capacity of 16 characters. * / public StringBuilder () {super (16);} the append methods of both classes are from the parent AbstractStringBuilder method public AbstractStringBuilder append (String str) {if (str = = null) return appendNull (); int len = str.length (); ensureCapacityInternal (count + len); str.getChars (0, len, value, count); count + = len; return this;} @ Overridepublic StringBuilder append (String str) {super.append (str) Return this;} @ Overridepublic synchronized StringBuffer append (String str) {toStringCache = null; super.append (str); return this;} append method
Stringbuffer adds the synchronized keyword to most operations involving string modification to ensure thread safety and low efficiency.
The String type uses the + operator such as
String a = "a"
When a = a + a;, actually encapsulate an as stringbuilder, call the append method and then return it with tostring, so when you use a lot of string addition, a large number of stringbuilder instances will be generated, which is very wasteful, and stringbuilder should be used instead of string.
Notice that a function is called in the append method.
EnsureCapacityInternal (count + len)
This method calculates whether the space after append is sufficient, and if it is insufficient, it needs to be expanded.
Public void ensureCapacity (int minimumCapacity) {if (minimumCapacity > 0) ensureCapacityInternal (minimumCapacity);} private void ensureCapacityInternal (int minimumCapacity) {/ / overflow-conscious code if (minimumCapacity-value.length > 0) {value = Arrays.copyOf (value, newCapacity (minimumCapacity);}}
Expand if the new string length is greater than the length of the value array
The length after expansion is generally twice the original length + 2.
If the expanded length exceeds the maximum array length MAX_ARRAY_SIZE supported by jvm.
Consider two situations
If the length of the new string exceeds the int maximum, an exception is thrown, otherwise the maximum length of the array is directly used as the length of the new array.
Private int hugeCapacity (int minCapacity) {if (Integer.MAX_VALUE-minCapacity)
< 0) { // overflow throw new OutOfMemoryError(); } return (minCapacity >MAX_ARRAY_SIZE)? MinCapacity: MAX_ARRAY_SIZE;} Delete
These two types of delete operations:
All are deleted by calling the delete method of the parent class
Public AbstractStringBuilder delete (int start, int end) {if (start)
< 0) throw new StringIndexOutOfBoundsException(start); if (end >Count) end = count; if (start > end) throw new StringIndexOutOfBoundsException (); int len = end-start; if (len > 0) {System.arraycopy (value, start+len, value, start, count-end); count- = len;} return this;}
In fact, you re-copy the remaining characters into the character array value.
System.arraycopy is used to copy the array here, and the speed is relatively fast.
System.arraycopy method
Turn to self-knowledge:
On mainstream high-performance JVM (HotSpot VM, IBM J9 VM, JRocket, and so on), System.arraycopy () can be considered reliable and efficient when copying arrays-if you find something that is not efficient enough, please report it to performance bug, which will certainly be improved soon.
The java.lang.System.arraycopy () method is declared as a native method in the Java code. So the most na ï ve implementation is through JNI calling the native code in JVM.
The immutability of String
About the immutability of String, here's a good answer.
What is immutable?
String immutability is very simple, as shown in the following figure, an existing string "abcd" is assigned to "abcedl" for the second time, not to modify the data on the original memory address, but to repoint to a new object, new address.
The relationship between String and JVM
Let's take a look at the Java stack, Java heap, method area, and constant pool:
Java stack (thread private data area):
Each Java virtual machine thread has its own Java virtual machine stack, and the Java virtual machine stack is used to store stack frames. When each method is executed, a stack frame (Stack Frame) is created at the same time to store local variables, operation stacks, dynamic links, method exits and other information. Each method is called until the completion of execution, corresponding to a stack frame in the virtual machine stack from the stack to the stack process.
Java heap (thread shared datazone):
Created when the virtual machine starts, the sole purpose of this memory area is to hold object instances, where almost all object instances are allocated.
Method area (thread shared data area):
The method area is created when the virtual machine starts, and it stores the structural information of each class. for example, run constant pools, field and method data, bytecode contents of constructors and common methods, and special methods used in class, instance, and interface initialization. The permanent generation before JDK8 is an implementation of the method area, while the JDK8 meta-space replaces the permanent generation, and the permanent generation is removed, which can also be understood as an implementation of the method area.
Constant pool (thread shared data area):
Constant pools are often divided into two categories: static constant pools and running constant pools. The static constant pool, which is the constant pool in the Class file, exists in the Class file. The runtime constant pool (Runtime Constant Pool) is part of the method area that holds some runtime constant data.
The following focuses on the string constant pool:
The string constant pool exists in the runtime constant pool (before JDK7, it exists in the runtime constant pool, and in JDK7 it has been transferred to the heap). The existence of string constant pools enables JVM to improve performance and reduce memory overhead. Using the string constant pool, whenever we create a string constant with a literal (String s = "1";), JVM first checks the string constant pool and assigns the address of the string object to reference s (reference s is in the Java stack) if the string already exists in the constant pool. If the string does not exist in the constant pool, the string is instantiated and placed in the constant pool, and the address of the string object is assigned to the reference s (which is in the Java stack). Use string constant pools whenever we use the keyword new (String s=new String ("1") When creating a string constant, JVM first checks the string constant pool, and if the string already exists in the constant pool, the string object is no longer created in the string constant pool, but is copied directly in the heap, and then the address of the object in the heap is assigned to the reference s. If the string does not exist in the constant pool, the string is instantiated and placed in the constant pool Then make a copy of the object in the heap and assign the address of the object in the heap to the reference s. Why is String not changeable?
After opening the JDK source code, the first three lines of the java.lang.String class are written as follows:
Public final class String implements java.io.Serializable, Comparable, CharSequence {/ * * String are essentially char arrays. And use the final keyword to modify. * / private final char value [];...}
First of all, the String class is modified with the final keyword, which means that String is not inheritable. See below that the main member field value of the String class is an char [] array and is decorated with final.
Final-decorated fields cannot be changed after they are created. Some people think this is the end of the story, but it is not. Because although value is immutable, only the reference address of value is immutable. The fact that you can't block the Array array is variable.
The data structure of Array is shown in the following figure.
In other words, the Array variable is just a reference on stack, and the ontology structure of the array is in the heap heap.
The value in the String class is decorated with final, only that the reference address called value in stack is immutable. It is not said that the data of array itself in the heap is immutable. Look at the following example
Final int [] value= {1jie 2J 3}; int [] another= {4J 5J 6}; value=another; / / compiler error, final immutable value decorated with final, the compiler does not allow me to point value to another address in the heap area. But if I just hit on the array elements, I'll do it in a minute. Final int [] value= {1jc2jol 3}; value [2] = 100; / / at this time the array is already {1Jet 2100} so String is immutable, the key is because of the engineers from SUN. In all the subsequent String methods, it is careful not to move the elements in the Array and not to expose the internal member fields. In the sentence private final char value [], the private access of private is more important than that of final. And the designer is also very careful to set the entire String so that final forbids inheritance to avoid being destroyed by others' inheritance. So String is the immutable key to all the underlying implementations, not a final. The test is the engineer's ability to construct data types and encapsulate data. What are the benefits of immutability?
The simplest reason is for safety. Take a look at the following scenario (the comment response example is not clear enough, now write it in full), a function appendStr () returns after adding a paragraph "bbb" to the immutable String parameter. AppendSb () is responsible for adding "bbb" to the variable StringBuilder.
Summarize the immutability of the following String.
First of all, the final-decorated class only guarantees that it cannot be inherited, and the address of the object of this class in heap memory will not be changed.
2 but the reference that holds the String object itself can be changed, for example, it can point to other objects.
The final-modified char array ensures that the reference of the char array is immutable. However, the value can be modified by char [0] ='a'. However, String does not provide methods to do this internally, so the immutability of String is also based on code encapsulation and access control.
For instance
Final class Fi {int a; final int b = 0; Integer s;} final char [] a = {'a'}; final int [] b = {1}; @ Testpublic void final modifier class () {/ / reference is not modified by final, so it is mutable. / / final only modifies the Fi type, that is, the memory address of the object instantiated by Fi is immutable in the heap. Although the memory address is immutable, the internal data can be changed. Fi f = new Fi (); f.a = 1; System.out.println (f); f.a = 2; System.out.println (f); / / changing the value in the instance does not change the memory address. Fi ff = f ff / Let the reference point to the new Fi object, which is held by the new reference. / / changing the direction of the reference will not change the address of the original object f = new Fi (); System.out.println (f); System.out.println (ff);}
The modification of f. A here can be understood as an operation such as char [0] ='a'. Only change the data value, not the memory value.
String common tool class
Problem description
In many cases, we need to perform a lot of fixed operations on strings, and these operations are not preset in JDK/JRE, so we think of apache-commons components, but it can't completely cover our business requirements, so we often have to write some code ourselves. Here are some common methods based on apache-commons components:
MAVEN depends on org.apache.commons commons-lang3 ${commons-lang3.version}
Code result
Public class StringUtils extends org.apache.commons.lang3.StringUtils {/ * * string with the value of "NULL" * / private static final String NULL_STRING = "NULL"; private static final char SEPARATOR ='_'; / * returns true * ① if the following conditions are satisfied. The input parameter is empty * ②. The input parameter is an empty string * ③. Input parameter is "null" string * * @ param string character type * @ return boolean * / public static boolean isNullOrEmptyOrNULLString (String string) {return isBlank (string) | | NULL_STRING.equalsIgnoreCase (string) } / * convert string to binary code * this method will not return null * * @ param str string to be converted * @ return binary bytecode array * / public static byte [] toBytes (String str) {return isBlank (str)? New byte [] {}: str.getBytes ();} / * * convert the string to binary code * this method will not return the string that null * * @ param str needs to convert * @ param charset encoding type * @ return binary bytecode array * @ throws UnsupportedEncodingException string conversion occurs when the encoding does not support * / public static byte [] toBytes (String str, Charset charset) throws UnsupportedEncodingException {return isBlank (str)? New byte [] {}: str.getBytes (charset.displayName ()) } / * * convert string to binary code * this method will not return null * * @ param str string to be converted * @ param charset encoding type * @ param locale encoding type corresponding region * @ return binary bytecode array * @ throws UnsupportedEncodingException string conversion occurs when the encoding does not support * / public static byte [] toBytes (String str, Charset charset) Locale locale) throws UnsupportedEncodingException {return isBlank (str)? New byte [] {}: str.getBytes (charset.displayName (locale));} / * binary code to string * this method does not return null * * @ param bytes binary code * @ return string * / public static String bytesToString (byte [] bytes) {return bytes = = null | | bytes.length = = 0? EMPTY: new String (bytes);} / * * binary code to string * this method will not return null * * @ param bytes binary code * @ param charset code set * @ return string * @ throws UnsupportedEncodingException the current binary code may not support the passed encoding * / public static String byteToString (byte [] bytes, Charset charset) throws UnsupportedEncodingException {return bytes = = null | | bytes.length = = 0? EMPTY: new String (bytes, charset.displayName ()) } / * binary code to string * this method will not return null * * @ param bytes binary code * @ param charset code set * @ param locale localization * @ return string * @ throws UnsupportedEncodingException the current binary code may not support the passed encoding * / public static String byteToString (byte [] bytes, Charset charset, Locale locale) throws UnsupportedEncodingException {return bytes = = null | | bytes.length = = 0? EMPTY: new String (bytes, charset.displayName (locale));} / * * convert object to string * * @ string to be converted by param object * @ return string, which may be empty * / public static String parseString (Object object) {if (object = = null) {return null;} if (object instanceof byte []) {return bytesToString ((byte []) object);} return object.toString () } / * convert a string to int type * * @ param str string to be converted * @ return int * @ throws NumberFormatException string is thrown * / public static int parseInt (String str) throws NumberFormatException {return isBlank (str)? 0: Integer.parseInt (str) if the string format is incorrect } / * convert a string to double type * * @ param str string to be converted * @ return double * @ throws NumberFormatException string is thrown * / public static double parseDouble (String str) throws NumberFormatException {return isBlank (str)? 0D: Double.parseDouble (str) if the string format is incorrect } / * convert a string to long type * * @ param str string to be converted * @ return long * @ throws NumberFormatException string is thrown * / public static long parseLong (String str) throws NumberFormatException {return isBlank (str)? 0L: Long.parseLong (str) if the string format is incorrect } / * convert a string to float type * * @ param str string to be converted * @ return float * @ throws NumberFormatException string is thrown * / public static float parseFloat (String str) throws NumberFormatException {return isBlank (str)? 0L: Float.parseFloat (str) if the string format is incorrect } / * get the i18n string * * @ param code * @ param args * @ return * / public static String getI18NMessage (String code, Object [] args) {/ / LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean (LocaleResolver.class); / / HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()). GetRequest (); / / Locale locale = localLocaleResolver.resolveLocale (request); / / return SpringContextHolder.getApplicationContext (). GetMessage (code, args, locale); return "" } / * obtain user remote address * * @ param request request header * @ return user ip * / public static String getRemoteAddr (HttpServletRequest request) {String remoteAddr = request.getHeader ("X-Real-IP"); if (isNotBlank (remoteAddr)) {remoteAddr = request.getHeader ("X-Forwarded-For");} else if (isNotBlank (remoteAddr)) {remoteAddr = request.getHeader ("Proxy-Client-IP") } else if (isNotBlank (remoteAddr)) {remoteAddr = request.getHeader ("WL-Proxy-Client-IP");} return remoteAddr! = null? RemoteAddr: request.getRemoteAddr ();} / * Hump naming tool * * @ return toCamelCase ("hello_world") = = "helloWorld" * toCapitalizeCamelCase ("hello_world") = = "HelloWorld" * toUnderScoreCase ("helloWorld") = "hello_world" * / public static String toCamelCase (String s, Locale locale, char split) {if (isBlank (s)) {return ";} s = s.toLowerCase (locale); StringBuilder sb = new StringBuilder () For (char c: s.toCharArray ()) {sb.append (c = = split? Character.toUpperCase (c): C);} return sb.toString ();} public static String toCamelCase (String s) {return toCamelCase (s, Locale.getDefault (), SEPARATOR);} public static String toCamelCase (String s, Locale locale) {return toCamelCase (s, locale, SEPARATOR);} public static String toCamelCase (String s, char split) {return toCamelCase (s, Locale.getDefault (), split) } public static String toUnderScoreCase (String s, char split) {if (isBlank (s)) {return ";} StringBuilder sb = new StringBuilder (); for (int I = 0; I
< s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = (i < (s.length() - 1)) && Character.isUpperCase(s.charAt(i + 1)); boolean upperCase = (i >0) & & Character.isUpperCase (c); sb.append ((! upperCase | |! nextUpperCase)? Split: "") .append (Character.toLowerCase (c));} return sb.toString ();} public static String toUnderScoreCase (String s) {return toUnderScoreCase (s, SEPARATOR) } / * convert the string to the ternary operation expression of JS to get the value of the object * * @ param objectString object string * for example: input parameter: row.user.id/ returns:! rowstring input: row.user.id/ returns:! rowstring. User.id conversion: row.user.id * / public static String toJsGetValue_Expression (String objectString) {StringBuilder result = new StringBuilder (); StringBuilder val = new StringBuilder () String [] fileds = split (objectString, "."); for (int I = 0; I < fileds.length; iTunes +) {val.append ("." + fileds [I]); result.append ("!" + (val.substring (1)) + "?':");} result.append (val.substring (1)); return result.toString () }} at this point, I believe you have a deeper understanding of "what are the common String interview questions in Java?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.