String class and StringBuffer class

String and StringBuffer are in the Java.Lang package (a class in this package does not need to be imported when used).
They can store and process a string, that is, personal data containing multiple characters.

Once the String class is initialized, it cannot be changed and StringBuffer is just fine.
It is used to encapsulate a string variable. It can be converted to a string using toString().

Normally, you can use StringBuffers to generate character data dynamically.

In addition, string implements the eqaals method, which is the result of a new string (“ABC”).

StringBuffer does not implement the Equals method, so new StringBuffer (“ABC”) results. equals(new StringBuffer (“ABC”) is false.

String covers the Equals method and hashcode method while StringBuffer does not cover the Equals method and hashcode method, so there will be problems when storing the StringBuffer object in the Java Set class.

String x = “a” +4 + “c”Wait for compilationString x = new StringBuffer (). append(“a”). append(4).append(“c”). toString();

The string constant is a private anonymous object
s1 string = “hello”;
s2 string = “hello”;
then S1 == S2;-> Correct
Because they refer to the same unknown.
String s1 = new String(“hello”);
String s2 = new String(“hello”);
then S1 == S2;-> Error

Interview questions:

1. String S = new String (“xyz”); What is the difference between the number of body lines?
Two or one, “xyz”, corresponds to a single object. This object is placed in the static string buffer. The “xyz” constant is the one in the buffer, no matter how many times it appears. newString() is written each time a new object is created. If you used ‘XYZ’ before, this statement will not create ‘xyz’ itself and will take it out directly from the buffer.

2. String s = “hello”; s = s + “world!” ; After executing these two lines of code, the contents of the original String object?

no. Since String is designed as an immutable class, all its objects are immutable objects.

In this code, S initially pointed to a String object, the content was “hello”, and then we did + spec in S. Currently, S does not point to the original object, but to another String object. The content was “Hello World!” The original object is still in memory, but the reference variable S no longer points to it.

Thanks to the above instructions, we can easily export different outputs. If you change the string frequently or make unexpected modifications, using a string to represent the string will cause the memory size to increase. At this time, you should consider using the StringBuffer class, which allows modifications to be made instead of a new object to create a new object. In addition, these two types of objects are very simple.

At the same time, we can also know that if you want to use a row of the same content, you don’t need a new one every time. For example, we want to initialize a string reference variable called S in the constructor. Set it to its initial value and we should be done:

public class demo { private strings; … public demo { s = “initial? value”; } … }

not s = new String(“initial value”);

The latter calls the constructor every time, creates new objects, has poor performance, has a lot of memory, and is irrelevant. Since a String object cannot be modified, it must only define a String of the same content.

For a static string, if the contents are the same, Java considers it to represent the same String object.The constructor is used to call the constructor with the new keywords, whether the content is the same or not.

As for why the String class is designed to be an unreachable class, it is determined by its purpose. In fact, not only strings, but also classes in many Java standard libraries are immutable. When designing a system, we sometimes need to develop unreachable classes that pass in a set of related values, which is also a reflection of object ideas. There are some advantages to inaccessible classes. For example, since its object is read-only, multiple concurrent accesses will not be a problem. Of course, there are some drawbacks. For example, each different state must be represented by an object, which can cause performance issues. So the Java Standard Library also provides a variable version, such as StringBuffer.

3. How many items are created in the following sentences: string s = “a” + “b” + “c” + “d”;
To get the following code:
string s1 = “a”;
string s2 = s1 + “b”;
s3 string = “a” + “b”;
System.out.println(s2 == “ab”);
System.out.println(s3 == “ab”);
The print result of the first statement is false, and the print result of the second statement is true. This shows thatJavac compilation can improve expression directly appended to a static string. No need to wait for the work period to perform additional operations. Instead, remove the extra number at compile timesum them directly in the result of these constants.
The first line of code is compiled into the header and optimized at compile time, which is equivalent to the line directly marked ‘ABCD’. For thisOnly one String object is createdentity type the following two lines of code,
String s = “a” + “b” + “c” + “d”;
System.out.println(s == “abcd”);
The final printed result should be correct.


 /*Прочитайте ввод клавиатуры на линию до тех пор, пока вход не станет «пока», и прекратить программу
   Примечание. Для возвращения автомобиля, под окнами, есть два двух, '\ r' и '\ n', и только '\ n' под Unix, но при написании программы вы должны различать его отдельно

public class ReadLine {
	public static void main(String[] args) {
		System.out.println("Please input a String:");
		byte[] buf=new byte[1024];
		int pos=0;
		int ch=0;
		String strInfo=null;
			try {;
			} catch (IOException e) {
			case '\r':
			case '\n':
				strInfo=new String(buf,0,pos);

Common String class methods
construction method:
1、String (bytes[] byte, int offset, int length);This was used above.
2、equals to ignore case:Ignore the lowercase comparison. If you enter the above example, it will not exit because the size is different, but if you use this method, it will exit because you exit.
3、indexOf(int ch);The carriage return CH appears first in the string
4、substring(int benginIndex);
5、substring(int beginIndex, int endIndex);

Returns the string support, 4 returns the support from the position of bengIndex to the end, and 5 returns the segment between BeginIndex and Endindex-1.

The role of basic data type packages is to package basic data types into objects. Because some methods cannot directly deal with basic data types and can only deal with objects, such as the vector addition method, parameters can only be objects. They currently need to use their own wrapper classesBoxes to package them into things.

// Пример: распечатайте прямоугольник, состоящий из*на экране. Ширина и высота прямоугольника передают спецификацию параметра, передаваемую методу main () при запуске программы.
public class TestInteger {
	public static void main(String[] args) {
		 // main () параметры представляют собой массив типа строки, которые используются дольше. Когда они широко преобразуются в целое число.
		int w = new Integer(args[0]).intValue();
		int h = Integer.parseInt(args[1]);
		// int h=Integer.valueOf(args[1]).intValue();
		 // вышеуказанное метод преобразования струны в пластическую хирургию.
		for (int i = 0; i < h; i++) {
			 StringBuffer sb = new StringBuffer (); // Использовать StringBuffer, потому что он дополнительно.
			for (int j = 0; j < w; j++) {
			 System.out.println (sb.toString ()); // Перед печати, StringBuffer должен быть преобразован в тип строки.


Compare the performance of the following two codes:


String sb = new String();
for (int j = 0; j < w; j++) {
	sb = sb + '*';


StringBuffer sb = new StringBuffer();
for (int j = 0; j < w; j++) {

This is the same as (2) in terms of performance, but the efficiency is very different.
In each loop, the String type needs to be converted to a StringBuffer type, and then a “*” is added, and then the toString() method is called on the String type, which is very inefficient.
In each loop, the original StringBuffer object only calls the original StringBuffer object. There is no new facility, so the efficiency is relatively high.

Interview questions:

4. Can a String class be inherited?
String classes cannot be inherited.

5. The difference between StringBuffer and StringBuilder
StringBuffer and StringBuilder both represent a string that can be modified.StringBuilder is thread safe and high performanceIf a string variable is defined in a method, this situation can only be obtained by streaming. There are no unsafe operators then use StringBuilder. If an element variable is defined in a class and an instance object of that class will be used in multiple environments, StringBuffer is the best choice.

[Статья воспроизводится, отсортирована и модифицирована, чтобы облегчить изучение себя. Поскольку в некоторых статьях нет заявления об авторском праве во время коллекции, источник не указан. Если нарушение, укажите, пожалуйста, укажите]

Leave a Comment