Hello, everyone! I'm Xiao Sheng! I learned the knowledge of classes and objects from Mr. Han Shunping and gained a lot! Now let's share our notes!
Common class
Wrapper class
Classification of packaging
Packaging | Basic data type | Direct parent class |
---|---|---|
boolean | Boolean | Object |
char | Character | Object |
byte | Byte | Number |
short | Short | Number |
int | Int | Number |
long | Long | Number |
float | Float | Number |
double | Double | Number |
Boolean
Character
Number is the direct subclass under the parent class
Packing & unpacking
- Automatic disassembly box
- Manual disassembly and assembly box
public class Wrapper01 { public static void main(String[] args) { // Jdk5 previous manual packing & manual unpacking; After jdk5, the box can be disassembled automatically // Take Character as an example char name = 'n'; // Manual packing Character ch1 = new Character(name); // Not recommended Character ch2 = Character.valueOf(name); // Manual unpacking char name2 = Character.valueOf(ch2); // The essence is to use the charValue method char name3 = ch1.charValue(); // Automatic packing Character ch3 = name; // Essentially, the valueOf method is used // Automatic unpacking char CH4 = ch3; // The essence is to use the charValue method } }
Next, I track the bottom layer of the automatic disassembly box
First, hit four breakpoints to explore the jump of these four breakpoints
The following are the functions that jump in turn
summary
- There is no essential difference between manual disassembly and automatic disassembly of the bottom layer of the box
- Package class to < = > basic data type
- Basic data type -- > Packing class packing essence: valueOf function
- Packing class -- > basic data type unpacking essence: charValue function
exercises
// What are the following output results Exercise 1 Object obj = true? new Integer(1):new Double(2.0); // Ternary operators are a whole System.out.println(obj); // 1.0 Exercise 2 Object obj1; if(true){ obj1 = new Integer(1); }else{ obj1 = new Double(2.0); } System.out.println(obj); // 1
Packing class < = > string class
Wrapper Vs String
public class WrapperVsString { public static void main(String[]args){ // Convert String class to wrapper class String age = "120"; Integer age2 = Integer.valueOf(age); // Method 1: valueOf function is essentially parseInt() method Integer a2 = Integer.parseInt(age); // Mode 2: parseInt function Integer age3 = new Integer(age); //The essence of the recommended method is the insert method // Convert wrapper class to String class Integer height = 180; // Automatic packing String h = String.valueOf(height); // Method 1: the essence of valueOf function is to call the toString() method String h2 = height + ""; // Method 2: type conversion Integer + "" String h3 = height.toString(); // Method 3: toString() function /* * String.valueOf()Source code * public static String valueOf(Object obj) { * return (obj == null) ? "null" : obj.toString(); * } * * Integer.valueOf()Source code * public static Integer valueOf(String s) throws NumberFormatException { * return Integer.valueOf(parseInt(s, 10)); // 10 Refers to that the number passed in is a decimal number * } * * new Integer()Source code * @Deprecated(since="9") * public Integer(String s) throws NumberFormatException { * this.value = parseInt(s, 10); * } */ } }
Common methods of Wrapper class
Official Integer documentation
Take Integer wrapper class as an example
Packaging related interview questions
public class Wrapper02 { public static void main(String[] args) { /* * Source code: integercache low -128 IntegerCache. high 127 * public static Integer valueOf(int i) { * if (i >= IntegerCache.low && i <= IntegerCache.high) * return IntegerCache.cache[i + (-IntegerCache.low)]; * return new Integer(i); * } * If valueof (value) value > - 128 & & value < 127, integercache is returned cache[i + (-IntegerCache.low)] * Otherwise, the new object Integer is returned */ System.out.println(new Integer(1) == new Integer(1)); // false Integer a = 1; Integer b = 1; System.out.println(a==b); // true Integer m = 128; Integer n = 128; System.out.println(m==n); // false Integer x = 128; int y = 128; System.out.println(x==y); // true } }
String class
Overview of String class
public static void main(String[] args) { /** * String * Concept: it is a set of character sequences, which is essentially the implementation of char[] value character array * "Al_tair"A sequence of characters called a character constant enclosed in double quotes * One character occupies two bytes (each character does not distinguish between letters and Chinese characters) * public final class String Indicates that the final class of String cannot be inherited by other classes * private final byte[] value The value used to store the string is a type decorated with final. The array cannot point to a new address, but its value can be modified */ String name = "Al_tair"; }
Interfaces and constructors
String memory graph
// Run the code, and the memory diagram is as follows class code{ public static void main(String[] args){ String a = "Al_tair"; String b = new String("Al_tair"); } }
Memory graph: String VS character array
Combined with code and memory diagram analysis
class Text{ String str = new String("lns"); // final means that the address of char type data storage cannot be changed, but the value can be changed final char[] ch = {'j','a','v','a'}; public void change(String str,char[] ch){ str = "zlr"; ch[1] = 'c'; } public static void main(String[] args) { Text text = new Text(); text.change(text.str,text.ch); System.out.println(text.str.toString()+" and "+text.ch[1]); // lnsandc } }
Common methods of String class
- equals is case sensitive to determine whether the contents of the string are the same
- equalsIgnoreCase ignores case to determine whether the contents of the string are the same
- Length gets the number of strings, or string length
- indexOf gets the index of the first occurrence of the character in the string. The index starts from 0 and returns - 1 if it is not found
- lastindexOf gets the index of the last occurrence of the character in the string. The index starts from 0 and returns - 1 if it is not found
- substring intercepts the string in the specified range
- trim removes the spaces before and after the string
- charAt gets the character at an index
- compareTo compares the size of two strings. If the former is greater than or equal to the latter, it returns a natural number; If the latter is greater, a negative number is returned
- intern if the constant pool already contains a String with the same value, the String reference address in the constant pool is returned. Otherwise, the String object is added to the constant pool and the reference of the String object is returned
// equals() method source code public boolean equals(Object anObject) { if (this == anObject) { // Are the addresses the same return true; } if (anObject instanceof String) { // Is it a String class or a String parent class String aString = (String)anObject; if (!COMPACT_STRINGS || this.coder == aString.coder) { return StringLatin1.equals(value, aString.value); } } return false; } @HotSpotIntrinsicCandidate public static boolean equals(byte[] value, byte[] other) { if (value.length == other.length) { for (int i = 0; i < value.length; i++) { if (value[i] != other[i]) { return false; } } return true; } return false; } // The explanation of placeholder involves the method format < = > C language output // %s,%d,%.3f,%c String name = "lns"; int age = 18; double height = 185.35; char gender = 'male'; String Info = "full name:%s\t Age:%d\t Height:%.3f\t Gender:%c"; String show = String.format(Info,name,age,height,gender); System.out.println(show); // Name: lns Age: 18 Height: 185.350 Gender: Male
Related exercises
// Exercise 1 String a = "l"; String b = new String("l"); System.out.println(a.equals(b)); // true System.out.println(a == b); // false System.out.println(a == b.intern()); // true System.out.println(b == b.intern()); // false // Exercise 2 // 2.1 create several objects a: 2 String s = "hello"; s = "haha"; // 2.2 created several objects a: 1 conclusion: the compiler will optimize to determine whether the constant pool object has reference points String str = "hello" + "haha"; // Equivalent to String str = "hellohaha"; // 2.3 create several objects a: 3 conclusion: the addition address of String constant is stored in the constant pool, and the addition address of String variable is stored in the String object // sum points to value[](String object), and then points to the "HelloString" string in the constant pool public static void main(String[]args){ String m = "Hello"; String n = "String"; /* * Interpretation: * 1. Create a new object new StringBuilder(); * 2. Add the string "Hello" through the append function * 3. Add the String "String" through the append function * 4. Return new String("HelloString"); */ String sum = m + n; } // Analyze the direction of sum and the underlying source code // debug test // first insert public StringBuilder() { super(16); } //secong insert str = "Hello" public StringBuilder append(String str) { super.append(str); return this; } // third insert str = "String" public StringBuilder append(String str) { super.append(str); return this; } // last one public String toString() { // Create a copy, don't share the array return isLatin1() ? StringLatin1.newString(value, 0, count): StringUTF16.newString(value, 0, count); }
StringBuffer class
Concept: it represents a variable character sequence. It can add or delete the string content. It is a container
Construction method
Constructor and Description |
---|
StringBuffer() constructs a string buffer without characters, with an initial capacity of 16 characters. |
StringBuffer(CharSequence seq) constructs a string buffer CharSequence containing the same characters as specified. |
StringBuffer(int capacity) constructs a string buffer without characters and the specified initial capacity. |
StringBuffer(String str) constructs a string buffer initialized to the specified string content. |
/* * Constructs a string buffer with no characters in it and an * initial capacity of 16 characters. * StringBuffer()constructor */ @HotSpotIntrinsicCandidate public StringBuffer() { super(16); // The initial capacity is 16 characters, which is stored in the value array of the parent class }
String class < = > StringBuffer class
The difference between String class and StringBuffer class
- String saves a string constant. The value in it cannot be changed. Each update of the value actually changes the address, which is inefficient
- Stringbuffer saves string variables, and the values in it can be changed. There is no need to change the address every time, which is efficient
Conversion between String class and StringBuffer class
public static void main(String[] args) { // Conversion between String and StringBuffer // String => StringBuffer String str = "lns"; StringBuffer stringBuffer = new StringBuffer(str); // Method 1: use StringBuffer constructor StringBuffer append = new StringBuffer().append(str); // Method 2: the append method is used // StringBuffer => String StringBuffer sbr = new StringBuffer("zlr"); String s = sbr.toString(); // Method 1: use toString method String s1 = new String(sbr); // Using the String constructor }
common method
public static void main(String[] args) { // common method // append add StringBuffer stringBuffer = new StringBuffer(""); stringBuffer.append("lns"); // lns /* * append Source code * No matter what data type is passed in, the StringBuffer type is returned * public synchronized StringBuffer append(String str) { * toStringCache = null; * super.append(str); * return this; * } */ // Delete delete // Delete index range [start, end] stringBuffer.delete(0,1); // Delete first character ns // Replace replace // Replace range [start, end] stringBuffer.replace(0, 1,"ln"); // lns // indexOf lookup // Find the index that appears in the string for the first time. If it is found, it will return the first letter index of the string you are looking for. If it is not found, it will return - 1 stringBuffer.indexOf("ns"); // 1 // length System.out.println(stringBuffer.length()); // 3 }
Related exercises
// Exercise 1 String str = null; StringBuffer sb = new StringBuffer(); sb.append(str); System.out.println(sb); // null System.out.println(sb.length()); // 4 /* * // Bottom analysis * // StingBuffer class * public synchronized StringBuffer append(String str) { * toStringCache = null; * super.append(str); // Jump to parent class * return this; * } * // AbstractStringBuilder abstract class * public AbstractStringBuilder append(String str) { * if (str == null) { * return appendNull(); // Jump to this method * } * int len = str.length(); * ensureCapacityInternal(count + len); * putStringAt(count, str); * count += len; * return this; * } * // appendNull method * private AbstractStringBuilder appendNull() { * ensureCapacityInternal(count + 4); * int count = this.count; * byte[] val = this.value; * if (isLatin1()) { * val[count++] = 'n'; * val[count++] = 'u'; * val[count++] = 'l'; * val[count++] = 'l'; * } else { * count = StringUTF16.putCharsAt(val, count, 'n', 'u', 'l', 'l'); * } * this.count = count; * return this; * } */ StringBuffer sb = new StringBuffer(str); // Throw null pointer exception NullPointerException /* * AbstractStringBuilder(String str) { * int length = str.length(); // str null * int capacity = (length < Integer.MAX_VALUE - 16) * ? length + 16 : Integer.MAX_VALUE; * final byte initCoder = str.coder(); * coder = initCoder; * value = (initCoder == LATIN1) * ? new byte[capacity] : StringUTF16.newBytesFor(capacity); * append(str); * } */
StringBuilder class
Concept: a variable character sequence. Thread unsafe. This design is used as a simple replacement for StringBuffer where a single thread string buffer is being used. Where possible, it is recommended that this category take precedence over StringBuffer because it will be faster in most implementations.
Most of them are similar to StringBuffer
Special point: it is not mutually exclusive, so it is used under single thread
// The difference of source code analysis is that the keyword synchronized ensures thread safety // append method of StringBuffer @Override @HotSpotIntrinsicCandidate public synchronized StringBuffer append(String str) { toStringCache = null; super.append(str); return this; } // append method of StringBuilder @Override @HotSpotIntrinsicCandidate public StringBuilder append(String str) { super.append(str); return this; }
The difference between String, StringBuffer and StringBuilder
- String: immutable character sequence, low efficiency, but high reuse rate due to constant pool
- StringBuffer: variable character sequence, high efficiency (addition and deletion), thread safety
- StringBuilder: variable character sequence, with the highest efficiency and unsafe thread
Use principle
- If there are a lot of modification operations for strings, StringBuffer or StringBuffer is generally used
- If there are a lot of modification operations on the string, and in the case of single thread, use StringBuilder
- If there are a lot of string modification operations, and in the case of multithreading, use StringBuffer
- If the String is rarely modified and referenced by multiple objects, use String, such as configuration information
Math class
Concept: the Math class contains methods that perform basic mathematical operations
common method
public static void main(String[] args) { // Most of Math classes are static methods, which can be directly through the class name Method name access // abs absolute value int abs = Math.abs(-10); System.out.println(abs); // 10 // pow exponentiation double pow = Math.pow(2,4); System.out.println(pow); // 16.0 // ceil rounds up and returns > = the smallest integer of the parameter (the integer will be converted to double) double ceil = Math.ceil(-3.002); System.out.println(ceil); // -3.0 // floor rounded down and returns < = the maximum integer of the parameter (the integer will be converted to double) double floor = Math.floor(3.2); System.out.println(floor); // 3.0 // Round round < = > math Floor (parameter + 0.5) double round = Math.round(3.24); System.out.println(round); // 3.0 // sqrt square double sqrt = Math.sqrt(4); System.out.println(sqrt); // 2.0 // random number [0,1) int random = (int)(Math.random()*50+50); System.out.println(random); // Integer range [50100) }
Arrays class
Concept: this class contains various methods for manipulating arrays (such as sorting and searching), and most of them are also static methods
common method
toString method
Function: output array
Integer[] array = {3,5,6,47,8}; // toString output array System.out.println(Arrays.toString(array)); // [3, 5, 6, 47, 8] /* * // toString Method source code * public static String toString(int[] a) { * if (a == null) * return "null"; * int iMax = a.length - 1; * if (iMax == -1) * return "[]"; * * StringBuilder b = new StringBuilder(); * b.append('['); * for (int i = 0; ; i++) { * b.append(a[i]); * if (i == iMax) * return b.append(']').toString(); * b.append(", "); * } * } */
sort method
Function: sort the array from small to large by default
// sort overload, you can pass in an interface Comparator to realize customized sorting Integer[] array = {3,5,6,47,8}; Arrays.sort(array); System.out.println(Arrays.toString(array)); // [3, 5, 6, 8, 47] Arrays.sort(array,new Comparator(){ @Override public int compare(Object o1, Object o2) { Integer i1 = (Integer)o1; Integer i2 = (Integer)o2; return i2 - i1; // Decide whether to order in ascending or descending order } }); System.out.println(Arrays.toString(array)); // [47, 8, 6, 5, 3] /** * MySort Bubble realization of * public class MySort { * public static void main(String[] args) { * int[] arr = {6,4,5,6,845,4,51}; * bubble(arr, new Comparator() { * @Override * public int compare(Object o1, Object o2) { * int i1 = (Integer)o1; * int i2 = (Integer)o2; * return i1 - i2; * } * }); * System.out.println(Arrays.toString(arr)); * } * * public static void bubble(int[] arr, Comparator c){ * int temp = 0; * for (int i = 0; i < arr.length - 1; i++) { * for (int j = 0; j < arr.length - 1 - i; j++) { * if(c.compare(arr[j],arr[j+1]) >= 0){ * temp = arr[j]; * arr[j] = arr[j+1]; * arr[j+1] = temp; * } * } * } * } * } */
binarySearch method
Function: search through binary search method. It is required to be in ascending order. If it does not exist in the array, it will return - (the index position that should be + 1)
Integer[] array = {3,5,6,47,8}; Arrays.sort(array); // [3, 5, 6, 8, 47] int index = Arrays.binarySearch(array,9); System.out.println(index); // -5 should be at index 4 (between 8 and 471), return - (4 + 1) /** * binarySearch Source code * private static int binarySearch0(Object[] a, int fromIndex, int toIndex, Object key) { * int low = fromIndex; * int high = toIndex - 1; * * while (low <= high) { * int mid = (low + high) >>> 1; * @SuppressWarnings("rawtypes") // Suppress warning * Comparable midVal = (Comparable)a[mid]; * @SuppressWarnings("unchecked") * int cmp = midVal.compareTo(key); * * if (cmp < 0) * low = mid + 1; * else if (cmp > 0) * high = mid - 1; * else * return mid; // key found * } * return -(low + 1); // key not found. * } */
Other methods
// Assignment of copeOf array if the length of the assignment is greater than the length of the original array, the redundant data will be filled in with null Integer[] integers = Arrays.copyOf(array, array.length-1); System.out.println(Arrays.toString(integers)); // [3, 5, 6, 8] // The fill of the fill array replaces all the data in the array int[] fillNum = {2,45,78,85,15}; Arrays.fill(fillNum,2); System.out.println(Arrays.toString(fillNum)); // [2, 2, 2, 2, 2] // equals compares whether the contents of two array elements are the same int[] equalsNum = {2,45,78,85,15}; int[] equalsNum2 = {2,45,78,85,15}; System.out.println(Arrays.equals(equalsNum,equalsNum2)); // true
System class
Concept: the System class contains several useful class fields and methods. It cannot be instantiated.
common method
public static void main(String[] args) { // gc method garbage collector new System01(); System.gc(); // I've been destroyed // The difference between the current time and midnight of the currentTimeMillis method between January 1, 1970 UTC, in milliseconds. System.out.println(System.currentTimeMillis()); // 1645776480314 // The arraycopy method copies an array int[] src = {1,2,3}; int[] desc = {0,0,0}; /* * Five parameter descriptions from left to right * src the source array. Array of copied contents * srcPos starting position in the source array. Source array index location (from which location to copy) * dest the destination array. Array obtained by copying contents * destPos starting position in the destination data. Index position of the target array * length the number of array elements to be copied. Length of copied array */ System.arraycopy(src,0,desc,0,3); System.out.println(Arrays.toString(desc)); //[1, 2, 3] System.out.println(src == desc); // false // Exit method exit System.out.println("Program start"); /* * status Illustrative examples * In an if else judgment, if our program runs as we expect, * In the end, we need to stop the program, so we use system exit(0), * And system Exit (1) is usually placed in the catch block. When an exception is caught, the program needs to be stopped, * We use system exit(1). status=1 is used to indicate that the program is not normal. */ System.exit(0); // System.exit(0) is a normal exit program, while system Exit (1) or non-zero indicates abnormal exit from the program System.out.println("Program end"); // Do not execute } @Override protected void finalize(){ System.out.println("I've been destroyed..."); }
Biginger and BigDecimal classes
Concept: biginger is suitable for storing large integer data; BigDecimal is suitable for saving floating-point data with higher precision
// Biginger is suitable for storing large integer data. long data type cannot be stored BigInteger bigInteger = new BigInteger("998456349564561256465489"); System.out.println(bigInteger); // 998456349564561256465489 // +- * / operation = > the method implements add subtract multiply divide bigInteger = bigInteger.add(new BigInteger("1")); System.out.println(bigInteger); // 998456349564561256465490 bigInteger = bigInteger.divide(new BigInteger("2")); System.out.println(bigInteger); // 499228174782280628232745 bigInteger = bigInteger.subtract(new BigInteger("2")); System.out.println(bigInteger); // 499228174782280628232743 bigInteger = bigInteger.multiply(new BigInteger("2")); System.out.println(bigInteger); // 998456349564561256465486 // BigDecimal is suitable for saving floating-point numbers with higher precision. double data type cannot be stored BigDecimal bigDecimal = new BigDecimal("9980.2561295645485648548485646541"); System.out.println(bigDecimal); // 9980.2561295645485648548485646541 // +- * / operation = > the method implements add subtract multiply divide bigDecimal = bigDecimal.add(new BigDecimal("1")); System.out.println(bigDecimal); // 9981.2561295645485648548485646541 bigDecimal = bigDecimal.divide(new BigDecimal("2")); // If the division is not complete, an arithmetic exception is returned System.out.println(bigDecimal); // 4990.62806478227428242742428232705 bigDecimal = bigDecimal.subtract(new BigDecimal("2")); System.out.println(bigDecimal); // 4988.62806478227428242742428232705 bigDecimal = bigDecimal.multiply(new BigDecimal("2")); System.out.println(bigDecimal); // 9977.25612956454856485484856465410 // Solve the abnormal problem of decimal division: specify the precision (not recommended after JDK9) bigDecimal = bigDecimal.divide(new BigDecimal("2.3326"),BigDecimal.ROUND_CEILING); System.out.println(bigDecimal); // 4277.31121047952866537548167909376
Date class
First generation date class
Date: accurate to milliseconds, representing an instant
SimpleDateFormat: format and parse date class (date < = > text)
public static void main(String[] args) throws ParseException { // Date date class Date date = new Date(); // current date System.out.println(date); // Fri Feb 25 16:58:51 CST 2022 Date date2 = new Date(4564956); // Enter the number of milliseconds from January 1, 1970 System.out.println(date2); // Thu Jan 01 09:16:04 CST 1970 // SimpleDateFormat format and parsing date class use their own format of date, month, day, hour, minute, second, week (as shown in the figure below) SimpleDateFormat sdf = new SimpleDateFormat("YYYY year MM month DD day hh:mm:ss E"); System.out.println(sdf.format(date)); // Friday, February 56, 2022, 05:07:32 String dateStr = "2021 February 56, 2005:07:32 Monday"; System.out.println(sdf.format(sdf.parse(dateStr))); // There will be compilation exceptions on Monday, December 363, 2021, at 05:07:32 }
Specified format of SimpleDateFormat
Second generation date class
The Calendar class (Calendar) is an abstract class
// Abstract classes can obtain instances through the getInstance method Calendar calendar = Calendar.getInstance(); System.out.println(calendar); System.out.println("year:"+calendar.get(calendar.YEAR)); // Year: 2022 System.out.println("month:"+calendar.get(calendar.MONTH)+1); // Month: 2 source code: JANUARY} which is 0 System.out.println("day:"+calendar.get(calendar.DAY_OF_MONTH)); // Date: 25 System.out.println("hour:"+calendar.get(calendar.HOUR)); // Hours: 8 System.out.println("minute:"+calendar.get(calendar.MINUTE)); // Minutes: 11 System.out.println("second:"+calendar.get(calendar.SECOND)); // Seconds: 46
Third generation date class (JDK8)
LocalDate date: mm / DD / yy
LocalTime: hour, minute and second
LocalDateTime: month, day, hour, minute and second
LocalDateTime localDateTime = LocalDateTime.now(); LocalTime localTime = LocalTime.now(); LocalDate localDate = LocalDate.now(); // localDateTime: 2022-02-25T20:30:19.250574 LocalTime: 20:30:19.250574 LocalDate: 2022-02-25 System.out.println("localDateTime: "+localDateTime+" LocalTime: "+ localTime+" LocalDate: "+localDate); System.out.println("year: "+localDateTime.getYear()); // Year: 2022 System.out.println("month: "+localDateTime.getMonth()); // Month: FEBRUARY System.out.println("day: "+localDateTime.getDayOfMonth()); // Date: 25 System.out.println("Time: "+localDateTime.getHour()); // Hour: 20 System.out.println("branch: "+localDateTime.getMinute()); // Score: 33 System.out.println("second: "+localDateTime.getSecond()); // Seconds: 45
DateTimeFormatter format date class
// DateTimeFormatter format date class LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYY year MM month DD day hh:mm:ss E"); System.out.println(dateTimeFormatter.format(localDateTime)); // Friday, February 56, 2022, 08:39:43
// All letters "a" to "Z" and "a" to "Z" remain as pattern letters. The following pattern letters are defined: Symbol Meaning Presentation Examples ------ ------- ------------ ------- G era text AD; Anno Domini; A u year year 2004; 04 y year-of-era year 2004; 04 D day-of-year number 189 M/L month-of-year number/text 7; 07; Jul; July; J d day-of-month number 10 Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter Y week-based-year year 1996; 96 w week-of-week-based-year number 27 W week-of-month number 4 E day-of-week text Tue; Tuesday; T e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T F week-of-month number 3 a am-pm-of-day text PM h clock-hour-of-am-pm (1-12) number 12 K hour-of-am-pm (0-11) number 0 k clock-hour-of-am-pm (1-24) number 0 H hour-of-day (0-23) number 0 m minute-of-hour number 30 s second-of-minute number 55 S fraction-of-second fraction 978 A milli-of-day number 1234 n nano-of-second number 987654321 N nano-of-day number 1234000000 V time-zone ID zone-id America/Los_Angeles; Z; -08:30 z time-zone name zone-name Pacific Standard Time; PST O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00; X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15; x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15; Z zone-offset offset-Z +0000; -0800; -08:00; p pad next pad modifier 1 ' escape for text delimiter '' single quote literal ' [ optional section start ] optional section end # reserved for future use { reserved for future use } reserved for future use
Instant timestamp
// Instant -> Date Instant instant = Instant.now(); System.out.println(instant); // 2022-02-25T14:48:47.557358800Z java.util.Date from = Date.from(instant); System.out.println(from); // Fri Feb 25 22:48:47 CST 2022 // Date -> Instant Instant instant1 = from.toInstant(); System.out.println(instant1); // 2022-02-25T14:55:27.377Z
Relevant interview questions
1. What methods does the string class have?
String class is the most commonly used API in Java. It contains a large number of methods to process strings. The more commonly used are:
- char charAt(int index): returns the character at the specified index;
- String substring(int beginIndex, int endIndex): intercepts a molecular string from this string;
- String[] split(String regex): divide the string into arrays according to the specified rules;
- String trim(): delete the leading and trailing spaces of the string;
- int indexOf(String str): returns the index of the substring that appears for the first time in this string;
- int lastIndexOf(String str): returns the index of the substring at the end of this string;
- boolean startsWith(String prefix): judge whether this string starts with the specified prefix;
- boolean endsWith(String suffix): judge whether the string ends with the specified suffix;
- String toUpperCase(): capitalize all characters in this string;
- String toLowerCase(): lowercase all characters in this string;
- String replaceFirst(String regex, String replacement): replace the first matching substring with the specified string;
- String replaceAll(String regex, String replacement): replaces all matching substrings with the specified string.
2. Can string be inherited?
String class is decorated by final, so it cannot be inherited.
Extended reading
In Java, the String class is designed as an immutable class, which is mainly reflected in that the member variable that holds the String is final.
- Before Java 9, char [] array was used to save characters for strings, i.e. private final char[] value;
- Java 9 has made improvements, using byte [] array to save characters, that is, private final byte[] value;
The reason why the String class is designed as an immutable class is mainly for security and performance considerations, which can be summarized as follows.
- Since String is widely used in any Java system and will be used to store sensitive information, such as account, password, network path, file processing and other scenarios, it is particularly important to ensure the security of String class. If the String is variable and easy to be usurped and modified, we cannot guarantee that it is safe when using String for operation, SQL injection, access to dangerous files and other operations are likely to occur.
- In multithreading, only constant objects and values are thread safe, and data can be shared among multiple threads. Due to the natural immutability of String, when a thread "modifies" the value of String, it will only produce a new String object, which will not have side effects on the access of other threads. What is accessed is the same String data, and no synchronization operation is required.
- As the basic data structure, String is widely used in some set containers, especially in some hash sets. In the hash set, the location of the elements should be determined according to the hashCode() method of the object. Because the hashcode attribute of the String will not be changed to ensure uniqueness, containers such as HashMap and HashSet can realize the corresponding caching function. Due to the immutability of String, double calculation of hashcode can be avoided. Just use the cached hashcode, which greatly improves the performance of using String objects in hash sets.
- When the string is immutable, the string constant pool makes sense. The emergence of string constant pool can reduce the creation of strings with the same literal amount, and make different references point to the same string in the pool, saving a lot of heap memory for runtime. If the string is variable, the string constant pool is meaningless. String based on the constant pool The intern () method also fails. Each time a new string is created, it will open up new space in the heap and occupy more memory.
To ensure the immutability of the String class, it is easy to define this class as final. If there is no final modification, there will be subclasses of String. These subclasses can override the methods of String class and forcibly change the value of String, which is contrary to the original intention of String class design.
3. What is the difference between String and StringBuffer
String class is immutable, that is, once a string object is created, the character sequence contained in the object cannot be changed until the object is destroyed.
The StringBuffer object represents a String with variable character sequence. After a StringBuffer is created, the character sequence of the String object can be changed through the methods provided by StringBuffer, such as append(), insert(), reverse(), setCharAt(), setLength(). Once the final desired String is generated through StringBuffer, its toString() method can be called to convert it into a String object.
4. What is the difference between StringBuffer and StringBuilder
Both tringBuffer and StringBuilder represent variable string objects. They have a common parent class AbstractStringBuilder, and the construction methods and member methods of the two classes are basically the same. The difference is that StringBuffer is thread safe, while StringBuilder is non thread safe, so the performance of StringBuilder is slightly higher. In general, to create a string with variable content, it is recommended to give priority to the StringBuilder class.
5. When using strings, which method is recommended for new and ""?
Let's look at the difference between "hello" and new String("hello"):
- When the Java program directly uses the string quantity of "hello", the JVM will use the constant pool to manage the string;
- When using new String("hello"), the JVM will first use the constant pool to manage the "hello" direct quantity, and then call the constructor of String class to create a new String object, which is saved in heap memory.
Obviously, using the new method will create one more object, which will occupy more memory. Therefore, it is generally recommended to use the direct method to create strings.
6. How is the bottom layer of adding two strings realized?
If the spliced strings are all direct quantities, the compiler will directly optimize them into a complete string at compile time, which is the same as writing a complete string directly.
If the spliced string contains variables, the compiler uses StringBuilder to optimize it at compile time, that is, automatically create an instance of StringBuilder and call its append() method to splice these strings together.
7. Have you encountered any exceptions and how to deal with them?
In Java, you can handle exceptions in the following three steps:
-
Catch exception
Wrap the business code inside the try block. When any exception occurs in the business code, the system will create an exception object for this exception. After creating the exception object, the JVM will look for the catch block that can handle it after the try block, and hand over the exception object to the catch block for processing.
-
Handling exceptions
When handling exceptions in the catch block, you should first record the log to facilitate tracing the exception later. Then, according to the type of exception and the current business situation, carry out corresponding processing. For example, giving a default value to a variable, directly returning a null value, throwing a new business exception to the caller for processing, and so on.
-
Recycling resources
If the business code opens a resource, such as database connection, network connection, disk file, etc., you need to close the resource after the execution of the business code. Also, try to close the resource regardless of whether an exception occurs. Writing the code to close the resource in the finally block can meet this requirement, that is, the code in the finally block will always be executed whether an exception occurs or not.
8. Please introduce the exception interface of Java
Throwable is the top-level parent class of an Exception and represents all abnormal conditions. It has two direct subclasses, Error and Exception.
Error is an error, which generally refers to the problems related to the virtual machine, such as system crash, virtual machine error, dynamic link failure, etc. this error cannot be recovered or captured, which will lead to the interruption of the application. Generally, the application cannot handle these errors, so the application should not try to catch the error object using the catch block. When defining a method, there is no need to declare in its throws clause that the method may throw error and any subclasses thereof.
Exceptions are exceptions, which are divided into two categories: Checked exceptions and runtime exceptions. All instances of the RuntimeException class and its subclasses are called runtime exceptions; An Exception instance that is not a RuntimeException class and its subclasses is called a Checked Exception. Java believes that Checked exceptions are exceptions that can be handled (repaired), so Java programs must explicitly handle Checked exceptions. If the program does not handle the Checked Exception, the program will have an error during compilation and cannot be compiled. Runtime exceptions are more flexible. There is no need to explicitly declare and throw runtime exceptions. If the program needs to catch runtime exceptions, it can also use the try... Catch block.
9. What is the difference between int and Integer? What results will they get when they do = = operation?
Int is the basic data type and Integer is the wrapper class of int. When they perform = = operation, Integer will automatically unpack to type int, and then compare. At that time, if the two int values are equal, it will return true, otherwise it will return false.
10. Talk about the application scenario of automatic packing and unpacking
Automatic packing and unpacking is jdk1 5 functions provided.
Automatic packing: data of a basic type can be directly assigned to the corresponding packing type;
The corresponding packing type can be directly assigned to a basic packing type;
Through the functions of automatic packing and unpacking, the conversion process between basic type variables and packaging objects can be greatly simplified. For example, if the parameter type of a method is a wrapper type and the data we hold when calling is the value of the basic type, we can directly pass the value of the basic type to the method without any special processing.
11. Why packaging?
Java language is an object-oriented language, and its design concept is "everything is an object". However, there are exceptions to the eight basic data types, which do not have the characteristics of objects. To solve this problem, Java defines a corresponding reference type for each basic data type, which is the wrapper class.