java.lang package common classes
Classes in the java.lang package will be automatically imported, and there is usually no need to write import statements when using them.
Object class
Object is the root class of the Java class hierarchy, and all classes inherit it directly or indirectly.
toString() method
toString() returns a string representation of the object. The default format usually consists of the class name, @, and the hexadecimal form of the hash code, but it is not a reliable memory address.
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
equals() method
Object.equals() has the same effect as == by default, comparing whether two references point to the same object. Subclasses can override this and compare object content instead.
When rewriting equals(), you usually rewrite hashCode() to ensure that objects with equal content have the same hash code.
hashCode() method
hashCode() returns an integer hash value, commonly used in hash structures such as HashMap and HashSet. The same hash code does not mean that objects must be equal, but equals() Objects with equal values must have the same hash code.
clone() method
clone() is used to copy objects. Classes that directly call Object.clone() usually need to implement the Cloneable interface, otherwise CloneNotSupportedException will be thrown. The default clone is a shallow copy, and the reference field may still point to the same object.
finalize() method
finalize() does not guarantee when it will be executed and is not suitable for releasing resources such as files and network connections. Resources should be managed using try-with-resources or the explicit shutdown method and not relying on finalize().
wrapper class
All eight basic types have corresponding packaging categories.
| Basic Type | Packaging Type |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
char | Character |
float | Float |
double | Double |
boolean | Boolean |
Wrapper classes encapsulate basic type values into objects for easy use in scenarios such as generic collections that only accept reference types.
Integer Common methods
It is recommended to use Integer.valueOf() to create or obtain Integer objects and Integer.parseInt() to convert strings to int.
Integer value1 = Integer.valueOf(3);
Integer value2 = Integer.valueOf("3");
int number1 = value1.intValue();
int number2 = Integer.parseInt("100");
Integer.valueOf() will reuse cache objects of some commonly used values. The Java specification requires caching at least -128 to 127, and a larger caching range may be determined by JVM configuration.
Integer value1 = Integer.valueOf(3);
Integer value2 = Integer.valueOf(3);
System.out.println(value1 == value2); // 通常为 true
Integer value3 = Integer.valueOf(300);
Integer value4 = Integer.valueOf(300);
System.out.println(value3 == value4); // 不应依赖该结果
equals() should be used when comparing packaging numerical content, and == should not be used to judge the object content.
Automatic boxing and automatic unpacking
JDK 5 begins to support automatic boxing and automatic unpacking.
Integer value = 3; // 自动装箱,相当于 Integer.valueOf(3)
int number = value; // 自动拆箱,相当于 value.intValue()
If the packaging class is quoted as null during automatic unpacking, NullPointerException will be thrown.
Integer value = null;
// int number = value; // 运行时抛出 NullPointerException
String class
String represents an immutable character sequence. After a string object is created, its character content cannot be modified; what appears to be modifying a string will actually return a new string.
String text = "abcdefg";
String result = text.replace("bcd", "BCD");
System.out.println(text); // abcdefg
System.out.println(result); // aBCDefg
String implements the CharSequence interface, so a string can be passed in where the CharSequence parameter is needed.
Internal storage of String
Different JDK versions have different implementations. Java 8’s String mainly uses char[] to save content; newer JDK uses byte[] with encoding tags to achieve compact strings. Learning and using the String API should not rely on specific internal array types.
String constant pool
String literals are put into the string constants pool, and the same literals are usually reused on the same object. Using new String() will explicitly create new objects.
String s1 = "ab";
String s2 = "ab";
System.out.println(s1 == s2); // true
String s3 = new String("ab");
String s4 = new String("ab");
System.out.println(s3 == s4); // false
System.out.println(s3.equals(s4)); // true
String constant expressions that can be determined during compilation time are collapsed.
String s1 = "ab";
String s2 = "a" + "b";
System.out.println(s1 == s2); // true
Splices containing variables usually produce result objects during runtime, and == should not be used to compare string content.
String Common methods
Get length and characters
String text = "abcdefg";
System.out.println(text.length());
System.out.println(text.charAt(2));
compare strings
Whether the comparison contents of equals() are equal, compareTo() compares them in dictionary order. compareTo() returns negative, zero or positive numbers, and there is no guarantee that only -1, 0, and 1 will be returned.
System.out.println("abc".equals("abc"));
System.out.println("abc".compareTo("abd"));
Find and judge
String text = "abcdefgabc";
System.out.println(text.contains("cde"));
System.out.println(text.startsWith("abc"));
System.out.println(text.endsWith("abc"));
System.out.println(text.indexOf("abc"));
System.out.println(text.lastIndexOf("abc"));
When the specified content cannot be found, indexOf() and lastIndexOf() return -1.
intercept string
The ending index of substring() is not included in the results.
String text = "abcdefg";
System.out.println(text.substring(2));
System.out.println(text.substring(2, 5)); // cde
Replacement, splitting and case conversion
String text = "abcbc";
System.out.println(text.replace("bc", "BC"));
System.out.println(Arrays.toString(text.split("b")));
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
System.out.println(" Java ".trim());
The argument to split() is a regular expression. When splitting special characters such as dots and vertical lines, you need to escape them according to regular expression rules.
Strings and byte arrays
Character sets should be clearly specified when encoding and decoding.
String text = "你好";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String result = new String(bytes, StandardCharsets.UTF_8);
System.out.println(text.equals(result));
StringBuffer class
StringBuffer is a character sequence with variable content. It maintains an expandable buffer internally, and when appending, inserting or deleting content, it usually does not require repeated creation of a large number of intermediate objects like String splicing.
StringBuffer buffer = new StringBuffer("a");
for (int i = 0; i < 10_000; i++) {
buffer.append('a');
}
String result = buffer.toString();
Constructors usually reserve extra capacity based on the initial string length. When the buffer space is insufficient, it will be automatically expanded, and the specific expansion strategy belongs to the implementation details.
Common StringBuffer Methods
StringBuffer buffer = new StringBuffer("Java");
buffer.append(" SE");
buffer.insert(4, " 8");
buffer.delete(4, 6);
buffer.reverse();
System.out.println(buffer);
Common methods include append(), insert(), delete(), replace() and reverse().
StringBuilder class
StringBuilder and StringBuffer provide similar APIs and also belong to variable character sequences.
- The main method of
StringBufferhas synchronous control, which is suitable for scenarios where multiple threads share the same instance and modify it at the same time. StringBuilderdoes not provide this synchronization guarantee, and the overall overhead is lower in single-threaded scenarios.
StringBuilder is preferred for most local string splicing scenarios. Thread safety cannot be judged solely based on the class name, but also based on whether the object is shared by multiple threads and whether the overall operation is atomic.
If you enjoyed this, leave a comment~