1. Object class
-
Superclasses, base classes, direct or indirect parent classes of all classes, are located at the top of the inheritance tree
-
If extensions is not written for any class, it will inherit a class directly by default. Otherwise, it will inherit indirectly
-
The methods defined in the Object class are the methods that all objects have
-
The Object type can store any Object.
-
As a parameter, any object can be accepted
-
As a return value, any object can be returned.
-
1.1. getClass() method
-
public final Class<?> getClass(){}
-
Returns the actual object type stored in the reference
-
Application: it is usually used to judge whether the actual storage object types in two references are consistent.
-
public class TestgetClass { public static void main(String[] args) { Student student1 = new Student("Zhang San",15); Student student2 = new Student("Li Si",18); Square square = new Square(12); Class class1 = student1.getClass(); System.out.println(class1); Class class2 = student2.getClass(); Class class3 = square.getClass(); if(class1 == class2){ System.out.println("s1 and s2 Is the same type"); }else { System.out.println("s1 and s2 Not the same type"); } if(class1 == class3){ System.out.println("s1 and Square Is the same type"); }else { System.out.println("s1 and Square Not the same type"); } } } //Output results class com.qf.day12_2.Student(Student student1 = new Student("Zhang San",15); Class class1 = student1.getClass();) s1 and s2 Is the same type //(class1 == class2) s1 and Square Not the same type //(class1 == class3)
1.2hashCode() method
-
public int hashCode(){}.
-
Returns the hash code value of the object.
-
Hash value a numeric value of type int calculated using the hash algorithm based on the address or string or number of the object.
-
Generally, the same object returns the same hash code.
-
The hash value returned by objects of the same type is different.
-
public class TestgetClass { public static void main(String[] args) { Student student1 = new Student("Zhang San",15); Student student2 = new Student("Li Si",18); int hashCode1 = student1.hashCode(); int hashCode2 = student1.hashCode(); int hashCode3 = student2.hashCode(); if(hashCode1 == hashCode2){ System.out.println("s1 The hash value returned twice is the same"); }else { System.out.println("s1 The hash value returned twice is different"); } if(hashCode1 == hashCode3){ System.out.println("s1 and s2 Same hash value as"); }else { System.out.println("s1 and s2 The hash value of is different"); } } } //Output results s1 The hash value returned twice is the same s1 and s2 The hash value of is different
1.3. toString() method
-
public String toString (){}
-
Returns the string representation (representation) of the object
-
This method can be overridden according to program requirements. For example, display each attribute of the object.
Student student2 = new Student("Li Si",18); System.out.println(student2.toString()); //Output results com.qf.day12_2.Student@73035e27(Hash value)
1.4. equals () method
-
==(basic data type comparison value, reference type comparison address)
-
public Boolean equals(Object obj){}
-
The default implementation is (this = = obj). Compare whether the addresses of two objects are equal.
-
You can overwrite and compare whether the contents of two objects are equal. (override step)
-
Compares whether two references point to the same object
-
Judge whether obj is null
-
Judge whether the actual object types pointed to by the two references are consistent
-
Cast type
-
Compare whether the attribute values are equal in turn
-
@Override public boolean equals(Object obj) { //Determine whether two references point to the same object if(this == obj){ return true; } //Judge whether obj is null if(obj == null){ return false; } //Judge whether the actual objects pointed by the two applications are consistent if(obj instanceof Student) { //Cast type Student s = (Student)obj; //Compare whether the attribute values are equal in turn if(this.name.equals(s.getName()) && this.age == s.getAge()){ return true; } } return false; }
1.5. finalize() method
-
When the object is determined to be a garbage object, the JVM automatically calls this method to mark the garbage object and enter the collection queue
-
Garbage object: garbage object when there is no valid reference to this object
-
Garbage collection: GC destroys garbage objects to free up data storage space
-
Automatic recycling mechanism: the JVM runs out of memory and recycles all garbage objects at one time.
-
Manual recycling mechanism: use system gc(); Notify the JVM to perform garbage collection.
2. Packaging
2.1. What is packaging
-
The reference data type corresponding to the basic data type. (the basic data type is directly stored in stack memory, and the reference type is stored in heap memory)
-
Object can unify all data, and the default value of the wrapper class is null;
-
Packaging class correspondence
Basic data type | Packaging type |
---|---|
int | Integer |
short | Short |
long | Long |
double | Double |
char | Character |
boolean | Boolean |
float | Float |
byte | Byte |
2.2 type conversion, packing and unpacking
-
Packing: replace the basic data type with the reference data type
-
int i = 100; Integer integer = new Integer(100);
-
Unpacking: convert reference data type to basic data type
-
int n2 = integer.intValue();
-
JDK1. After 5, automatic packing and unpacking shall be provided
-
num = integer3.valueOf() //Automatic unpacking
-
parseXXX() static method, (replace with XXX type)
-
valueOf() static method.
-
Note: type compatibility needs to be guaranteed, otherwise NumberFormatException exception will be thrown.
2.3 Integer buffer
-
JAVA creates 256 commonly used integer wrapper type objects in advance. [- 128 ~ 127], 256 common integers have been created in advance, and the memory address has been allocated. In actual development, the created objects are reused. Save memory consumption
public static void main(String[] args) { Integer integer1 = new Integer(100); Integer integer2 = new Integer(100); System.out.println(integer1 == integer2);//false Integer integer3 = Integer.valueOf(127); Integer integer4 = Integer.valueOf(127); System.out.println(integer3 == integer4);//true Integer integer5 = Integer.valueOf(-128); Integer integer6 = Integer.valueOf(-128); System.out.println(integer5 == integer6);//true Integer integer7 = Integer.valueOf(128); Integer integer8 = Integer.valueOf(128); System.out.println(integer7 == integer8);//false, the memory addresses are different }
3. String class
-
String is a constant and cannot be changed after creation
-
Convert base type to string
-
//Convert String to String type int num = 10; //1.: use+ String s = num + ""; //Output: 10 //2. Use the method provided by Integer String s2 = Integer.toString(num); //Output: 10 //Binary string type String s3 = Integer.toBinaryString(num);//Output: 1010 //Hexadecimal string type String s4 = Integer.toHexString(num); //Output: A //Convert string to base type String s5 = "1000"; int n = Integer.parseInt(s5); //Output: 1000 //Special Boolean type conversion String s6 = "true"; // Except for true, all strings converted to Boolean are false boolean b = Boolean.parseBoolean(s6); //Output: true
-
-
String literals are stored in the string pool and can be shared. JDk1. 7 was previously stored in the method area, jdk1 After 7, move to the heap
-
String name = "hello";//"hello" constants are stored in the string pool
-
String name = "hello";//"hello" constants are stored in the string pool name = "zhangsan";//"zhangsan" is assigned to the name variable. When assigning a value to a string, the data is not modified, but a new space is assigned to name
-
String name = "hello";//"hello" constants are stored in the string pool name = "zhangsan";//"zhangsan" is assigned to the name variable String name2 = "zhangsan";//First, look for "zhangsan" in the string pool. If yes, then / / give the address of "zhangsan" to name2. If not, create a storage space
-
String s = "Hello "; Generate an object and store it in the string pool
-
String str = new String("java "); Create two objects, one in heap and one in pool.
-
==The equal in the comparison address String is rewritten, and the char array is compared. If the content is the same, it returns true
-
String address = "Beijing"; String address1 = new String("Beijing"); System.out.println(address==address1); //Output result: false System.out.println(address.equals(address1);//Output result: true String address2 = new String("Beijing"); System.out.println(address2==address1);//Output result: false System.out.println(address2.equals(address1);//Output result: true
-
String str = new String("java ");
String str2 = new String("java ");
System.out.println(str == str2); //false
3.1 common methods
-
public int length() returns the length of the string (spaces are also characters)
-
String test = "adSHOqwno45668asdas"; int i = test.length(); System.out.println("Length of string:"+i); //Output result: length of string: 19
-
public char charAt (int index) gets characters based on subscripts
-
char c = test.charAt(5); System.out.println("test The fifth subscript character of is:"+c); //Output result: the fifth subscript character of test is: q
-
public boolean contains (String str) determines whether the current string contains str
boolean b = test.contains("wno456"); System.out.println("test Contains wno456: "+ b); //Output result: test contains wno456: true
-
public char[] toCharArray() converts a string to an array
-
System.out.println(Arrays.toString(test.toCharArray())); //Output result: [a, d, s, h, o, q, w, n, o, 4, 5, 6, 6, 8, a, s, d, a, s]
-
public int indexOf (String str) finds the subscript of str for the first time. If it exists, it returns the subscript. If it does not exist, it returns - 1
-
System.out.println(test.indexOf("wno456")); //Output result: 6
-
public int lastIndexOf (String str) finds the index of the last occurrence of a string in the current string.
-
System.out.println(test.lastIndexOf("as")); //Output result: 17
-
public String trim() removes spaces before and after the string
-
System.out.println(test.trim()); //Output result: adSHOqwno45668asdas
-
public String toUpperCase() converts lowercase to uppercase
-
System.out.println(test.toUpperCase()); //Output result: ADSHOQWNO45668ASDAS
-
public boolean endWith(String str) determines whether the string ends with str
-
System.out.println(test.endsWith("as")); //Output result: true
-
public String replace (char oldchar, char newchar) replaces the old string with the new one
-
System.out.println(test.replace("6","@")); //Output result: adSHOqwno45@@8asdas
-
public String[] split(String str) splits the string according to str, [a,] can select multiple separators and use two segmentation markers, [a,] + "+" indicates that multiple A's can appear, or split + regular expression indicates that the preceding space can appear one or more times
-
System.out.println(Arrays.toString(test.split("a"))); //Output result: [, dSHOqwno45668, sd, s]
-
equalsIgnoreCase: ignore case comparison
-
String s1 = "hello"; String s2 = "HELLO"; System.out.println(s1.equalsIgnoreCase(s2)); //Output result: true
-
compareTo() compares sizes through a dictionary
String s3 = "abc"; //a in dictionary 97 String s4 = "xyz"; //z in dictionary 122 System.out.println(s3.compareTo(s4)); //Output result: - 23
-
compareTo() compares sizes through dictionaries. The first one is smaller than the second one. If s4 is as like as two peas, and s3 is the same as s4, then the difference in length is returned. The two are exactly the same: 0.
-
String s3 = "abc"; String s4 = "abczty"; System.out.println(s3.compareTo(s4)); //Output result: - 3
public static void main(String[] args) { String string = "java It is the best language in the world,I love java,java Really fragrant"; //Returns the character of the specified subscript char c = string.charAt(string.length()-1); System.out.println(c); //Output result: Fragrance //Determine whether the passed parameter is in the string boolean b = string.contains("best"); boolean b1 = string.contains("PHP"); System.out.println(b); //Output result: true System.out.println(b1); //Output result: false //Convert string to string array char[] chars = string.toCharArray(); System.out.println(chars); //Output result: java is the best language in the world. I love java. java is really fragrant System.out.println(chars.length); //Output result: 26 //Returns the parameter string starting with subscript 6 at the first occurrence of the string int pos=string.indexOf("java",6); System.out.println(pos); //Output result: 15 //Requirement: print all positions where Java appears //Returns the length of the string System.out.println(string.length());26 //trim(), remove the spaces before and after the string. String str2 = " hello word "; System.out.println(str2); //Output result: Hello word System.out.println(str2.trim()); //Output result: Hello word //Convert the string to uppercase and lowercase System.out.println(str2.trim().toUpperCase()); //Output result: Hello word //Determines whether the string ends with a parameter String filename = "HelloWord.java"; System.out.println(filename.endsWith(".java")); //Output result: true //Determines whether the string starts with a parameter System.out.println(filename.startsWith("Hello")); //Output result: true //replace to convert the old string to a new string String str3 = string.replace("java","PHP"); System.out.println(str3); //Output result: PHP is the best language in the world. I love PHP. PHP is really fragrant //Split: split String city = "Beijing, Shanghai, Nanjing, Zhengzhou"; String[] cities = city.split(","); for(String c1 : cities){ System.out.print(c1+"\t"); //Output: Beijing, Shanghai, Nanjing, Zhengzhou } //subString interception (including header but not tail) String str4 = string.substring(string.indexOf("I")); System.out.println(str4); //Output result: I love java. java smells good }
4. StringBuilder and StringBuffer (variable length string)
-
Concept: variable cache space can be created in memory to store frequently changed strings. The efficiency is much higher than that of String
-
StringBuilder: variable length string, jdk5 0, which is fast and thread unsafe
-
StringBuffer: variable length character string, jdk1 0, slow running efficiency and thread safety
-
Common methods of StringBuffer and StringBuffer
public static void main(String[] args) { StringBuilder sb = new StringBuilder(); //append sb.append("java Is the best language"); sb.append(",I love PHP"); sb.append(",I hate C language"); System.out.println(sb); //java is the best language. I love PHP and I hate C //Add (insert) sb.insert(0,"hello,"); System.out.println(sb); //hello,java is the best language. I love PHP and I hate C //replace with head and no tail sb.replace(0,1,"H"); System.out.println(sb);//Hello,java is the best language. I love PHP and I hate C //delete with header and no tail, starting from 0 sb.delete(0,6); System.out.println(sb); //java is the best language. I love PHP and I hate C //empty sb.delete(0,sb.length()); System.out.println(sb.length()); //0 //Reverse reverse StringBuilder sb = new StringBuilder("java It is the best language in the world,I love java,java Really fragrant"); System.out.println(sb); //java is the best language in the world. I love java. java really smells good System.out.println(sb.reverse()); //Xiangzhen avaj, avaj loves me. The best world of words is avaj }
-
StringBuilder running efficiency
-
long start = System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); for(int i=0 ;i<99999;i++){ sb.append(i); } long end = System.currentTimeMillis(); System.out.println("Time:"+ (end-start)); //Time: 10
String sb = ""; long start = System.currentTimeMillis(); for(int i=0 ;i<99999;i++){ sb = sb +i; } long end = System.currentTimeMillis(); System.out.println("Time:"+ (end-start)); //Time: 4138
5. BigDecimal class
-
Many practical applications require accurate calculation, but double is approximate value storage, which does not meet the requirements, so BigDecimal is used to improve the accuracy.
-
double d1 = 1.0; double d2 = 0.9; System.out.println(d1-d2); //0.09999999999999998 double result = (1.4-0.5)/0.9; System.out.println(result); //0.9999999999999999
-
Location: Java In math package
-
Purpose: accurately calculate floating point numbers
-
Creation method:
BigDecimal bd = new BigDecimal (" 1.0 ") ;
-
common method
-
//add addition System.out.println((new BigDecimal("1.0")).add(new BigDecimal("0.9"))); //1.9 //subtract System.out.println((new BigDecimal("1.0")).subtract(new BigDecimal("0.9"))); //0.1 //multiply multiplication System.out.println((new BigDecimal("1.0")).multiply(new BigDecimal("0.9"))); //0.90 //divide BigDecimal ROUND_ HALF_ Up rounded to two decimal places System.out.println((new BigDecimal("20")).divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP)); //6.67 //For the problem of division, it is necessary to keep the number of decimal places (scale), round (roundingMode.HALF_UP) and round (roundingMode.HALF_DOWN) BigDecimal bd3 = new BigDecimal("10"); BigDecimal bd4 = new BigDecimal("3"); BigDecimal result5 = bd3.divide(bd4,21, RoundingMode.HALF_UP); System.out.println(result5);
6. Math class
System.out.println(Math.E); // 2.718281828459045 //PI System.out.println(Math.PI); //3.141592653589793 //Cube root System.out.println(Math.cbrt(27)); //3.0 //square root System.out.println(Math.sqrt(9)); //3.0 //Returns the smallest integer greater than or equal to this number System.out.println(Math.ceil(3.8)); //4.0 //Returns the largest integer less than or equal to this number System.out.println(Math.floor(5.5)); //5.0 //pow returns the b-th power of a number System.out.println(Math.pow(2,10)); //1024.0 //random returns a decimal between 0 and 1, which is not equal to 1, but can be equal to 0 System.out.println(Math.random()); //0.9454350386657077 //Requirement: return a decimal from 0 to 9 System.out.println((int)(Math.random()*10)); //4 //It is required to return a random number between 50 and 100 (Math.random() * (b-a+1) + a) System.out.println((int)(Math.random()*51)+50); //85 //The demand returns a random number between 100-999 (999-100 + 1) System.out.println((int)(Math.random()*(999-100+1))+100); //466 //round() returns an integer rounded System.out.println(Math.round(3.1415926)); //3 System.out.println(Math.round(3.6663)); //4 //round() keeps two decimal places System.out.println(Math.round(3.1415926*100)/100.0); //3.14 //Summarize the method of rounding // (1)System.out.printf %.2f // (2)Math.round(); // (3) DecimalFormat class implementation DecimalFormat df = new DecimalFormat("#.00"); //#Represents the position of an integer, and 00 represents two decimal places System.out.println(df.format(3.1415926)); //3.14 // (4)BigDecimal class implementation BigDecimal bd = new BigDecimal("3.1415926"); System.out.println(bd.setScale(2, RoundingMode.HALF_UP)); //3.14
7. Date class, Calenda r Class
-
Date represents a specific moment, accurate to milliseconds. Most of the methods in the date class have been replaced by those in the Calender class.
-
Event unit
-
1 second = 1000 milliseconds
-
1 MS = 1000 microseconds
-
1 microsecond = 1000 nanoseconds
//today Date date = new Date(); System.out.println(date.getTime()); System.out.println(date.toString()); //yesterday Date yes = new Date(date.getTime()-60*60*24*1000); System.out.println(yes.toString()); System.out.println("________________________________________________________"); //Create calendar object Calendar calendar = Calendar.getInstance(); //Acquisition year System.out.println(calendar.get(Calendar.YEAR)); //2021 //Get month System.out.println(calendar.get(Calendar.MONTH)+1); //6 //Acquisition day System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); //5 //Get hours System.out.println(calendar.get(Calendar.HOUR_OF_DAY)); //15 //Get minutes System.out.println(calendar.get(Calendar.MINUTE)); //31 //Get seconds System.out.println(calendar.get(Calendar.SECOND)); //10 //Set time //Create 2010-10-1 15:30:20 Calendar calendar1 = Calendar.getInstance(); calendar1.set(2010,9,1,15,30,20); System.out.println(calendar1.getTime().toString()); //Fri Oct 01 15:30:20 CST 2010 //add adds or reduces the specified time Calendar yes1 = Calendar.getInstance(); yes1.add(Calendar.DAY_OF_MONTH,-1); System.out.println(yes1.getTime().toString()); //Fri Jun 04 15:31:10 CST 2021 Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DAY_OF_MONTH,1); System.out.println(tomorrow.getTime().toString()); //Sun Jun 06 15:31:10 CST 2021 //Minimum number and maximum days of the current month System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); //30 System.out.println(calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); //1
-
8. System class
//Systrm: use of system classes //arraycopy(): copy array //src copied original array srcPos: where to start copying dest: target array //destPos: store from the location of the target array. Length: the length of the copy int[] arr = {10,8,20,4866,6541,51}; int[] dest = new int[arr.length*2]; System.arraycopy(arr,0,dest,4,5); System.out.println(Arrays.toString(dest)); //[0, 0, 0, 0, 10, 8, 20, 4866, 6541, 0, 0, 0] //currentTimeMillis(); Return a good description from 1790.1.1 (the emergence of Unix) to the present, which is used to calculate the execution time of the code System.out.println(System.currentTimeMillis()); //1622880403100 //System.gc(); Tell the garbage collector to recycle garbage //System.exit(status); 0 indicates normal exit and non normal exit System.exit(0); System.out.println("Program end....."); //No output
9. SimpleDateFormat class
Date date = new Date(); System.out.println(date.toString()); //Sat Jun 05 16:11:24 CST 2021 //Format time SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(sdf.format(date)); //2021-06-05 04:12:05 //Parsing time (string to time) String s = "2020-05-06 17:20:30"; Date date1 = sdf.parse(s); System.out.println(date1); //Wed May 06 17:20:30 CST 2020
10. Runtime class
// Get runtime object Runtime runtime = Runtime.getRuntime(); System.out.println(runtime); //exec(); Execute commands in a separate process Process p = runtime.exec("notepad"); //Open Notepad Thread.sleep(5000); //Destruction process p.destroy(); //Close Notepad //Exit() exits the exit in the JVM system and calls the exit of the runtime //gc() tells the garbage collector to collect garbage. The gc in the System calls the runtime gc //Memory space occupied by the printer (heap) System.out.println("Total memory size:"+ runtime.totalMemory()/1024/1024 + "MB"); //Total memory size: 128MB System.out.println("Free memory size:"+ runtime.freeMemory()/1024/1024 + "MB"); //Free memory size: 124MB System.out.println("Maximum memory size:"+ runtime.maxMemory()/1024/1024 + "MB"); //Maximum memory size: 2018MB