String test site

String String constant
StringBuffer String variable (thread-safe)
StringBuilder String variable (non-thread-safe)

Performance is usually StringBuilder> StringBuffer> String.

String is an immutable object. Every time the String type is changed, it is equivalent to generating a new String object, and then pointing the pointer to the new String object, so the performance is the worst, and String is not used for strings that frequently change content. .

StringBuffer is a string variable. When operating on it, it does not generate a new object, but directly changes the object, so the performance is better.
StringBuilder, like StringBuffer, is a string variable, but it does not carry the synchronized keyword and does not guarantee thread safety, so it has the best performance. In the case of a single thread, it is recommended to use StringBuilder.

In general:
String: Suitable for a small number of string operations.
StringBuilder: Suitable for a large number of operations in the character buffer under a single thread.
StringBuffer: Applicable to the situation where a large number of operations are performed on the character buffer under multithreading.

== vs equals

What is the output of the following code?

String a = "helloworld";
String b = "hello" + "world";
System.out.println((a == b));

The output result is: True.
The reason is that the direct addition of String to string will be optimized at compile time . That is, hello+world is optimized to helloworld at compile time, so at runtime, they point to the same object . We can also infer that for the addition of direct strings, String is not necessarily slower than the other two.

What is the output of the following code?

String a = "helloworld";
String b = "hello";       
String c = b + "world";       
System.out.println((a == c));

The output result is: False.
The reason is that c is not a direct addition of two strings, it contains a string reference , so compile- time optimization will not be done at this time . Therefore, a and c finally generate two objects , and his efficiency is low at this time.

Transfer from Java basic interview questions and answer analysis (9)

== Interpretation

The effect of the basic type and the reference type == is different, as shown below:

Basic type: compare whether it is the same;
reference type: compare 引用whether it is the same ( ie memory address );
code example:

String x = "string";
String y = "string";
String z = new String("string"); //(“string”)会被首先创建,放入字符串常量池中,然后new出的对象z放在堆中
System.out.println(x==y); // true
System.out.println(x==z); // false
System.out.println(x.equals(y)); // true
System.out.println(x.equals(z)); // true

Code interpretation: Because x and y point to the same reference, == is also true, and new String()方法则重写开辟了内存空间so the result of == is false, and the comparison of equals is always the value, so the result is true.

equals interpretation

Equals is essentially ==, it's just thatString 和 Integer 等重写了 equals 方法,把引用比较改成了值比较 .

String equals method:

public boolean equals(Object anObject) {   	
if (this == anObject) {
    return true;
}
if (anObject instanceof String) {
    String anotherString = (String)anObject;
    int n = count;
    if (n == anotherString.count) {
	char v1[] = value;
	char v2[] = anotherString.value;
	int i = offset;
	int j = anotherString.offset;
	while (n-- != 0) {
	    if (v1[i++] != v2[j++])
		return false;
	}
	return true;
    }
}
return false;

First, let’s look at equals comparing an object with the same value by default . The code is as follows:

class Cat {
    public Cat(String name) {
		this.name = name;
    }
    
    private String name;
    
    public String getName() {
		return name;
    }
    
    public void setName(String name) {
		this.name = name;
    }
}

Cat c1 = new Cat("王磊");
Cat c2 = new Cat("王磊");
System.out.println(c1.equals(c2)); // false

The output is beyond our expectations, it turns out to be false? What's going on, you can see the source code of equals. The source code is as follows:

public boolean equals(Object obj) {
	return (this == obj);
}

It turns out that equals is essentially == .

Summary: == For basic types is value comparison, for reference types, it is comparison; and equals is reference comparison by default, but many classes have renewed the equals method, such as String, Integer, etc. to turn it into Value comparison, so in general, equals compares whether the values ​​are equal.

Dog dog = new Dog()
Under normal circumstances, comparing two objects is to compare whether their values ​​are consistent, so it must be done 重写.
The age attribute in the Dog class

@override
public boolean equals(Object obj) {
		if (this == obj)//引用的值(地址)是否相同【相等表示指向同一个对象】
			return true;
		if (obj == null)//不会比较2个null对象的 一个为null一个不为null肯定不相等
			return false;
		if (getClass() != obj.getClass())//判断2个对象的类型
			return false;
		Dog other = (Dog) obj;
		if (age != other.age)//属性值比较
			return false;
		return true;
	}

Object of the class: information about the attribute value of the object-----data information.
Class object: code information of the class (attributes, variable names, methods)
Class object and class object

The difference between the intern() method of String in JDK6 and JDK6+

JDK6: When the intern() method is called, if the string constant pool has previously created the string object, then a reference to the string in the pool will be returned. Otherwise, this string object is added to the string constant pool, and a reference to the string is returned.

JDK6+: When the intern() method is called, if the string object has been created in the string constant pool before, the reference to the string in the pool will be returned. Otherwise 如果该字符串对象已经存在于Java堆中,则将堆中此对象的引用添加到字符串常量池中,并且返回该引用,; if it does not exist in the heap, create the string in the pool and return its reference.

Note: In JDK1.6, the string constant pool was stored in Perm Space (Perm Space and the heap were separated), and in 1.6+, it was moved to the heap memory

Why is String Final?

Security and performance considerations (string constant pool) are the main reasons for the immutability of the String class.

  1. String object is cached in a string pool , the cache strings are multiple clients to share , then if the string variable. Then a client changes the value of the string will affect other clients. For performance reasons, it is very important to design the string cache to be immutable.
  2. Strings are widely used in many java classes. In the network connection, you can pass the host name and port number as characters; in the database connection, you can pass the database address as a string; in File I/O, you can open any file by the string file name.
    In this case, if the string is not immutable, it will cause serious security problems. Some people can access any file. Once he has authorization, he can deliberately modify the file name, or unintentionally gain access to another file.
  3. In multithreaded programming, because String is immutable, you don't need to consider string synchronization . Immutability makes strings thread-safe.

Note: Although the memory leak caused by SubString is not a thread problem, it should be noted

Guess you like

Origin blog.csdn.net/eluanshi12/article/details/95633951