Common classes and methods
1.1 concept of class
Class: a class is a template that describes the behavior and state of a class of objects.
Problem: explain the base class, subclass, derived class, parent class and superclass in the class
A: base class, parent class and superclass all mean the same thing, but they are just different terms. The same is true for subclasses and derived classes.
For example:
class A{}; class B extends A{}; //Here, B is called the parent or base class, and A is called the child or derived class
1.2. Object class
Object class is the direct or indirect parent class of all classes (including superclass and base class), which is located at the top of the inheritance tree. If any class explicitly inherits a class without writing extensions, it inherits the object class directly by default, otherwise it inherits indirectly. The method defined in it is the method that all objects have. Any object can be stored in the object class. When it is used as a parameter, it can accept any object; As a return value, any object can be returned.
1.2.1. getClass() method
The getClass() method returns the actual objects stored in the reference, which is usually used to judge whether the types of the actual objects in multiple references are consistent.
public class test { static class Student{ private String name; private int age; public Student(String name, int age) { this.name=name; this.age=age; } } public static void main(String[] args) { Student stu1 = new Student("aaa", 20); Student stu2 = new Student("bbb", 22); //Judge whether stu1 and stu2 are of the same type Class class1 = stu1.getClass(); Class class2 = stu2.getClass(); if (class1 == class2) { System.out.println("Both belong to the same type"); } else { System.out.println("They are not of the same type"); } } }
1.2.2. hashCode() method
The hashCode() method returns the hash code value of the object. Hash value is an int type value calculated by using hash short message according to the address or number of the object. Generally, the same object will return the same hash code.
public class test { static class Student{ private String name; private int age; public Student(String name, int age) { this.name=name; this.age=age; } } public static void main(String[] args) { Student stu1 = new Student("aaa", 20); Student stu2 = new Student("bbb", 22); System.out.println(stu1.hashCode()); System.out.println(stu2.hashCode()); Student stu3=stu1; System.out.println(stu3.hashCode()); } }
1.2.3 toString() method
The toString() method will return the string representation of the object. We can override this method according to program requirements, such as displaying the values of various properties of the object
Test 1: do not override the toString() method of the Object class (the Student class inherits Object by default)
package com.Sam; public class test { static class Student{ private String name; private int age; public Student(String name, int age) { this.name=name; this.age=age; } } public static void main(String[] args) { Student stu1 = new Student("aaa", 20); Student stu2 = new Student("bbb", 22); System.out.println(stu1.toString()); System.out.println(stu2.toString()); } }
Explanation: the toString() method of the Object class itself will return a string, that is:
Package name + class name + @ + unsigned hexadecimal representation of the hash code of this object
getClass().getName() + ‘@’ + Integer.toHexString(hashCode()); I can't understand xd.
Test 2: override the toString() method of the Object class
package com.Sam; public class test { static class Student{ private String name; private int age; public Student(String name, int age) { this.name=name; this.age=age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public static void main(String[] args) { Student stu1 = new Student("aaa", 20); Student stu2 = new Student("bbb", 22); System.out.println(stu1.toString()); System.out.println(stu2.toString()); } }
1.2.4. equals() method
The default implementation of this method is (this==obj), that is, compare whether the addresses of two objects are the same, or override it to compare whether the contents of two objects are the same.
package com.Sam; public class test { static class Student{ private String name; private int age; public Student(String name, int age) { this.name=name; this.age=age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public static void main(String[] args) { Student stu1 = new Student("aaa", 20); Student stu2 = new Student("bbb", 22); Student stu3=stu1; System.out.println(stu1.equals(stu2)); System.out.println(stu1.equals(stu3)); } }
Here, the return value type of the equals() method is boolean. If the addresses of the two objects compared are the same, it returns true, and vice versa.
Override the equals() method
Rewrite steps:
- 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 each attribute value is the same at one time
@Override public boolean equals(Object obj) { //1. Judge whether two objects are the same reference if (this==obj){ return true; } //2. Judge whether obj is null if (obj==null){ return false; } //3. Determine whether it is the same type // if (this.getClass()==obj.getClass()) if(obj instanceof Student){ //4. Cast type Student s=(Student)obj; if (this.name.equals(s.getName())&&this.age==s.getAge()){ return true; } } return false; }
package com.Sam; public class test { static class Student{ private String name; private int age; public Student(String name, int age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object obj) { //1. Judge whether two objects are the same reference if (this==obj){ return true; } //2. Judge whether obj is null if (obj==null){ return false; } //3. Determine whether it is the same type // if (this.getClass()==obj.getClass()) if(obj instanceof Student){ //4. Cast type Student s=(Student)obj; if (this.name.equals(s.getName())&&this.age==s.getAge()){ return true; } } return false; } } public static void main(String[] args) { Student stu1 = new Student("aaa", 20); Student stu2 = new Student("bbb", 22); Student stu3=new Student("aaa",20); Student stu4=stu1; System.out.println(stu1.equals(stu2)); System.out.println(stu1.equals(stu3)); System.out.println(stu1.equals(stu4)); } }
1.2.5. finalize() method
- When an 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: this object is garbage when there is no valid reference to it
- Garbage collection: gc destroys garbage objects to free up data storage space
- Automatic recycling mechanism: JVM runs out of memory and recycles all garbage objects at one time
- Manual recycling mechanism: use system Gc() notifies the JVM to perform garbage collection
//finalize() method override @Override protected void finalize() throws Throwable { System.out.println(this.name+"The object was recycled"); }
package com.Sam; public class test { static class Student{...} public static void main(String[] args) { //finalize() //The following five states are not recycled Student stu1=new Student("aaa",20); Student stu2=new Student("bbb",20); Student stu3=new Student("ccc",20); Student stu4=new Student("ddd",20); Student stu5=new Student("eee",20); System.gc(); } }
The JVM does not recycle these objects because they have valid references.
package com.Sam; public class test { static class Student{...} public static void main(String[] args) { //finalize() new Student("aaa",20); new Student("bbb",20); new Student("ccc",20); new Student("ddd",20); new Student("eee",20); System.gc(); } }
1.3 packaging
- The default values of wrapper types are null, and Object can unify all data
Type conversion and boxing, unpacking
package com.Sam; public class Demo01 { public static void main(String[] args) { //Type conversion (boxing operation): convert a basic type to a reference type //Basic type int num1=18; //Creating objects using the Integer class Integer integer1=new Integer(num1); Integer integer2=Integer.valueOf(num1); System.out.println(integer1); System.out.println(integer1.getClass()); System.out.println(integer2); System.out.println(integer2.getClass()); //Type conversion (unpacking): convert reference type to basic type Integer integer3=new Integer(100); int num2=integer3.intValue(); System.out.println(num2); //JDK1. After 5, it provides the function of automatic packing and unpacking int age=30; //Automatic packing Integer integer4=age; System.out.println(integer4.getClass()); //Automatic unpacking int age2=integer4; System.out.println(age2); } }
- The Number superclass provides the conversion method between different types
- Six common methods provided in the Number parent class
- parseXXX() static method
- valueOf() method
- Note: ensure the compatibility of types, otherwise the NumberFormatException exception will be thrown
1.4. String class
- String is a constant and cannot be changed after creation
- String literals are stored in the string pool and can be shared
- String s=“hello”; Generate an object and store it in the constant pool
- String s=new String(“hello”); Two objects are generated, one in heap and one in pool
package com.Sam; public class Demo01 { public static void main(String[] args) { String name="hello";//"hello" is stored in the string constant pool name="zhangsan";//Reopen space String name2="zhangsan"; //Another way to create strings is to create space in the heap. Strings are stored in the constant pool, objects are stored in the heap, and STR -- > heap String str1=new String("java"); String str2=new String("java"); //Using the comparison method of "= =" will compare whether the two variables refer to the same String object, so the result is false System.out.println(str1==str2); //Use the ". equals()" method to compare whether the String contents of two String types are the same System.out.println(str1.equals(str2)); } }
String common methods
- public int length(); Return string length
- public cahr charAt(int index); Get the string according to the following table
- public boolean contains(String str); Judge whether the current string contains the given characters
package com.Sam; public class Demo01 { public static void main(String[] args) { String content="java It is the best programming language in the world"; String flag="Long live the people's Republic of China, long live the people"; System.out.println(content.length()); System.out.println(flag.length()); System.out.println(content.charAt(0)); System.out.println(content.charAt(content.length()-1)); System.out.println(content.contains("java")); System.out.println(content.contains("php")); } }
- public char[] toCharArray(): convert string to array
- public int indexOf(String str): find the subscript of str for the first time. If it exists, it returns the modified subscript. If it does not exist, it returns - 1
- public int lastIndexOf(String str): find the index of the last occurrence of the string in the current string
import java.util.Arrays; public class Demo01 { public static void main(String[] args) { String content="java Is the best in the world java Language, java Really fragrant"; //Use of string methods //toCharArray(): returns the array corresponding to the string //indexOf(): returns the position where the string first appears //lastIndexOf(): returns the position of the last occurrence of a string // System.out.println(content.toCharArray()); System.out.println(Arrays.toString(content.toCharArray())); System.out.println(content.indexOf("java")); //Starting from the position where the index of the string is equal to 4, return the position where "java" appears System.out.println(content.indexOf("java",4)); System.out.println(content.lastIndexOf("java")); } }
- public String trim(): remove the spaces before and after the string
- public String toUpperCase(): convert lowercase to uppercase
- public boolean endWith(String str): determines whether the string ends with str
package com.Sam; public class Demo01 { public static void main(String[] args) { //trim(): remove the spaces before and after the string //toUpperCase(): convert lowercase to uppercase //endWith(String str): determines whether the string ends with str //startWith(String str): determines whether to end with str String content1 = " hello world "; String content2 =content1.trim(); System.out.println(content1); System.out.println(content2); System.out.println(content1.toUpperCase()); System.out.println(content1); System.out.println(content1.toLowerCase()); System.out.println(content1); String filename = "hello.java"; System.out.println(filename.endsWith(".java")); System.out.println(filename.startsWith("hel")); } }
Note: neither of the above methods changes the value of the original string.
- public String replace(char oldChar,char newChar): replace the old string with the new one
- public String[] split(String str): split according to str
package com.Sam; public class Demo01 { public static void main(String[] args) { //replace(char oldChar,char newChar): replace the old string with the new one //split(String str): split according to str String content="java Is the best in the world java programing language, java Really fragrant"; System.out.println(content.replace("java","php")); String say="java is the best programming language,java xiang"; String[] arr=say.split("[ ,]+");//Split with spaces and commas // , followed by + means "space" or "," which can appear continuously System.out.println(arr.length); for (String s:arr ) { System.out.println(s); } } }
supplement
package com.Sam; public class Demo01 { public static void main(String[] args) { //supplement String s1="hello"; String s2="HELLO"; System.out.println(s1.equals(s2)); System.out.println(s1.equalsIgnoreCase(s2));//Ignore case comparison //The length is the same as ASCII code, and the length is different than length String s3="abc";//a:97; String s4="xyz";//x:120; System.out.println(s3.compareTo(s4)); String s5="abc"; String s6="abcxyz"; System.out.println(s5.compareTo(s6)); } }
Case presentation:
Known String str = "this is a text";
Get the words in str separately
Replace text in str with practice
Insert an easy before text
Change the first letter of each word to uppercase
package com.Sam; import java.util.Arrays; public class Demo01 { public static void main(String[] args) { //Known String str = "this is a text"; // Get the words in str separately // Replace text in str with practice // Insert an easy before text // Change the first letter of each word to uppercase String str="this is a text"; String[] arraystr=str.split("[ ]+"); System.out.println(Arrays.toString(arraystr)); String newstr=str.replace("text","practice"); System.out.println(newstr); String newerstr=str.replace("text","easy text"); System.out.println(newerstr); String news=""; for (int i = 0; i < arraystr.length; i++) { char first=arraystr[i].charAt(0); char upperfirst=Character.toUpperCase(first); news=news+(upperfirst+arraystr[i].substring(1))+" "; } System.out.println(news); }
1.5. StringBuffer and StringBuilder
- StringBuffer: variable length string, jdk1 0, slow running efficiency, thread safety
- StringBuilder: variable length string, jdk1 5, fast running efficiency and unsafe thread
package com.Sam; public class Demo01 { public static void main(String[] args) { //StringBuffer and StringBuilder StringBuffer sb=new StringBuffer();//It's the same with StringBuilder //append(); Add sb.append("java World first"); System.out.println(sb.toString()); sb.append("java Really fragrant"); System.out.println(sb.toString()); sb.append("java not bad"); System.out.println(sb.toString()); //insert(); add to sb.insert(0,"I'm in front"); System.out.println(sb.toString()); //replace(); sb.replace(0,4,"hello"); System.out.println(sb.toString()); //delete(); delete sb.delete(0,5); System.out.println(sb.toString()); //delete(); empty sb.delete(0,sb.length()); System.out.println(sb.length()); } }
1.6,BigDecimal
Interview question: explain the output of the next code
package com.Sam; public class Demo01 { public static void main(String[] args) { double d1 = 1.0; double d2 = 0.9; System.out.println(d1 - d2); //Interview questions double result = (1.4 - 0.5) / 0.9; System.out.println(result); } }
If the calculation indicated by the above code is calculated manually, the results are undoubtedly 0.1 and 1. The result shown in the figure above is because double is stored as an approximate value and cannot be calculated accurately. It needs to be calculated with the help of BigDecimal class.
BigDecimal class:
- Location: Java In math
- Purpose: accurately calculate floating point numbers
- Creation method: BigDecimal bd=new BigDecimal("1.0");
The above code can be rewritten:
import java.math.BigDecimal; public class Demo01 { public static void main(String[] args) { BigDecimal bd1=new BigDecimal("1.0"); BigDecimal bd2=new BigDecimal("0.9"); System.out.println(bd1.subtract(bd2)); //Interview questions BigDecimal bd3=new BigDecimal("0.5"); BigDecimal bd4=new BigDecimal("1.4"); BigDecimal bd5=bd4.subtract(bd3).divide(bd2); System.out.println(bd5); } }
package com.Sam; import java.math.BigDecimal; public class Demo01 { public static void main(String[] args) { //BigDecimal: exact operation of large floating point numbers BigDecimal bd1=new BigDecimal("1.0"); BigDecimal bd2=new BigDecimal("0.9"); BigDecimal r1=bd1.subtract(bd2);//reduce System.out.println(r1); BigDecimal r2=bd1.add(bd2);//plus System.out.println(r2); BigDecimal r3=bd1.multiply(bd2);//ride System.out.println(r3); BigDecimal r4=new BigDecimal("1.4") .subtract(new BigDecimal("0.5")) .divide(new BigDecimal("0.9"));//except System.out.println(r4); //10 / 3 keep two decimal places and round BigDecimal r5=new BigDecimal("10") .divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP); System.out.println(r5); } }
1.7,Date
- Date represents a specific moment, accurate to milliseconds. Most of the methods in the date class have been nearly replaced by those in the Calendar class
- Time unit:
- 1 second = 1000 milliseconds
- 1 MS = 1000 microseconds
- 1 microsecond = 1000 nanoseconds
1.8,Calendar
Construction method: protected Calendar(): the object cannot be created directly because it is a protected modifier
package com.Sam; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo01 { public static void main(String[] args) { // SimpleDateFormat sdf=new SimpleDateFormat("yyyy MM dd HH:mm:ss"); SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd"); Date date1=new Date(); String str=sdf.format(date1); System.out.println(str); try { Date date2=sdf.parse("1990/05/01"); System.out.println(date2); } catch (ParseException e) { e.printStackTrace(); } } }
1.9,System
The System class is mainly used to obtain System properties and other operations. The construction method is private
package com.Sam; import java.util.Arrays; public class Demo01 { public static void main(String[] args) { //arrcopy: array copy //src: source array //srcPos: where to start replication //destPos: location of the target array //Length: the length of the copy int[] arr={20,18,15,8,35,26,45,90}; int[] dest=new int[8]; System.arraycopy(arr,0,dest,0,arr.length); for (int i = 0; i < dest.length; i++) { System.out.println(dest[i]); } //Arrays.copyOf(original,newLength); int[] arrr={1,2,3,4,5,6,7}; int[] arrrr= Arrays.copyOf(arrr,7); for (int a:arrrr ) { System.out.print(a); } System.out.println(); System.out.println(System.currentTimeMillis());//Milliseconds since 1970 long start=System.currentTimeMillis(); for (int i=0;i<99999999;i++){ for (int j=0;j<99999999;j++){ int result=i+j; } } long end=System.currentTimeMillis(); System.out.println("Time use:"+(end-start)); // System.gc(); System.exit(0);//Exit JVM System.out.println("The program is over");//The JVM exits without printing this sentence } }