当前位置:网站首页>9 common classes
9 common classes
2022-06-26 05:18:00 【Air transport Alliance】
1. Inner class
Java Classification of inner classes in :
- Member inner class : Define a class in another class , As a member of another class
- Static inner class :static
- Local inner classes : Define a class inside a method
- Anonymous inner class :
The concept of inner classes : Define a complete class inside a class
( A class will generate its own class file , An inner class will also )

characteristic :
- After compilation, an independent bytecode file can be generated
- The inner class has direct access to the private members of the outer class , Without destroying encapsulation
- It can provide necessary internal functional components for external classes
1.1 Member inner class
(1) Define inside the class , And instance variables 、 Class at the same level as instance method
(2) An inner class is an instance part of an outer class , When creating inner class objects , Must rely on external class objects .
- Outer out = new Outer();
- Inner in = out.new Inner();
Simple use of member inner classes :
package com.song.demo01;
// External class
public class Outer {
// Instance variables
private String name="zhangsan";
private int age=20;
// Inner class
class Inner{
private String address="Beijing";
private String phone="110";
// Method
public void show(){
// Print the properties of the external class
System.out.println(name);
System.out.println(age);
// Print the properties of the inner class
System.out.println(address);
System.out.println(phone);
}
}
}
package com.song.demo01;
import com.song.demo01.Outer.Inner;
public class TestOuter {
public static void main(String[] args) {
//1. Create an external class object
Outer outer = new Outer();
//2. Create inner class objects
Inner inner = outer.new Inner();
//Outer.Inner inner = outer.new Inner();
inner.show();
//1 And 2 Merge into one step , One step in place
Inner inner1=new Outer().new Inner();
inner1.show();
}
}
(3) When the inner class 、 When an external class has an attribute with the same name , Will access the properties of the inner class first .
- If you want to access external class properties , Add external class name .this. Property name
- Internal class properties , The default is this. Property name
package com.song.demo01;
// External class
public class Outer {
// Instance variables
private String name = "zhangsan";
private int age = 20;
// Inner class
class Inner {
private String address = "Beijing";
private String phone = "110";
// If the inner class attribute name is exactly the same as the outer class name , If you want to access external class properties , You need to add the external class name .this
private String name = "lisi";
// Method
public void show() {
// Print the properties of the external class
System.out.println(Outer.this.name);
System.out.println(Outer.this.age);
// Print the properties of the inner class ,this It refers to the inner class itself
System.out.println(this.name);
System.out.println(this.address);
System.out.println(this.phone);
}
}
}
(4) Member inner classes cannot define static members
package com.song.demo01;
// External class
public class Outer {
// Instance variables
private String name = "zhangsan";
private int age = 20;
// Inner class
class Inner {
private String address = "Beijing";
private String phone = "110";
// If the inner class attribute name is exactly the same as the outer class name , If you want to access external class properties , You need to add the external class name .this
private String name = "lisi";
//private static String country = "china";// Static members cannot be included in an inner class
private static final String country = "china";// But it can contain static constants
// Method
public void show() {
// Print the properties of the external class
System.out.println(Outer.this.name);
System.out.println(Outer.this.age);
// Print the properties of the inner class ,this It refers to the inner class itself
System.out.println(this.name);
System.out.println(this.address);
System.out.println(this.phone);
}
}
}
1.2 Static inner class
Static keywords :static
Tips : Only static inner classes can be used static modification , Normal classes cannot be used static Embellished !
- Static inner classes do not depend on outer class objects , You can create it directly or access it through the class name , You can declare static members
package com.song.demo02;
// External class
public class Outer {
private String name = "songsong";
private int age = 18;
// Static inner class , The level is the same as the external class ; Different from the member inner class, the member variable level is the same
static class Inner {
private String address = "shanghai";
private String phone = "111";
private static int count = 100;
public void show() {
// Calling properties of external classes ?( Consider how an outside class uses another class )
//1. First, create an external class object
Outer outer = new Outer();
//2. Calling properties of an external class object
System.out.println(outer.name);
System.out.println(outer.age);
// Call static inner class properties
System.out.println(address);
System.out.println(phone);
// Call the static internal class static attribute ( Static properties are accessed through the class name )
System.out.println(Inner.count);
}
}
}
package com.song.demo02;
public class TestOuter {
public static void main(String[] args) {
//1. Create static inner class objects directly
// Ahead Outer. It represents an inclusive relationship , did not new Outer(), There are no brackets , Not created Outer object
Outer.Inner inner = new Outer.Inner();
//2. Calling method
inner.show();
}
}
3. Local inner classes
Local : Means in a method
- Local inner classes are defined in outer class methods , Scope and create objects are limited to the current method .
- When a local inner class accesses a local variable in the current method of an outer class , Because the life cycle of variable cannot be guaranteed to be the same as itself , Variables must be decorated final, Become constant .
- The use of local inner classes is limited , Can only be used in the current method .
Static methods cannot directly access non static properties ( Static methods –> Class method ; Non static properties –> Object properties )
package com.song.demo03;
public class Outer {
private String name = "Lisa";
private int age = 20;
public void show() {
// Defining local variables ( Default final)
// Why it has to be final? Local variables will disappear after execution , however inner The object does not immediately disappear ,Inner Classes will not disappear , A method in a class cannot reference a variable that has disappeared , So we need to add final, Make it a constant ( Don't disappear )
String address = "Shandong";
//final String address = "Shandong";
// Define local inner classes , Same level as local variable .( Note that no access modifiers can be added )
class Inner {
// Local inner class properties
private String phone = "1230";
private String email = "[email protected]";
//private static int count=100;// Local inner classes cannot define static members
private static final int count = 100;// But you can define static constants
public void show2() {
// Access the properties of the external class , Same level as local variable . For non static methods , You can directly access ( It is also equivalent to omitting Outer.this.
System.out.println(name);
//System.out.println(Outer.this.name);
System.out.println(age);
// Access the properties of the inner class ( Equivalent to omitting this.)
System.out.println(phone);
System.out.println(email);
// Accessing local variables ,jdk1.7 The variable must be a constant final;jdk1.8 Automatically added by default final
// Constant final It means that he cannot be modified later
System.out.println(address);
}
}
// Create local inner class objects
Inner inner = new Inner();
inner.show2();
}
}
package com.song.demo03;
public class TestOuter {
public static void main(String[] args) {
Outer outer = new Outer();
outer.show();// Methods of external classes
}
}
4. Anonymous inner class
- Local inner classes without class names ( All features are the same as local inner classes ).
- Must inherit a Parent class ( It can be an abstract class ) Or implement a Interface
- Anonymous inner classes are actually defining classes 、 Implementation class 、 Create a syntax merge of objects , Only one object of this class can be created , Suitable for classes that are used only once .
- advantage : Reduce the amount of code
- shortcoming : Poor readability
- Anonymous inner classes actually have names , It's just not a name , It is assigned by the program .
package com.song.demo06;
// Interface
public interface Usb {
// Method
void service();
}
package com.song.demo06;
// Implementation class of interface
public class Mouse implements Usb {
@Override
public void service() {
System.out.println(" The connection to the computer is successful , The mouse is working ");
}
}
package com.song.demo06;
public class TestUsb {
public static void main(String[] args) {
// Create variables of interface type
/*Usb usb = new Mouse();// Create a variable with an interface ---> polymorphic usb.service();*/
// Local inner classes
class Fan implements Usb {
@Override
public void service() {
System.out.println(" The connection to the computer is successful , The fan starts to work ");
}
}
// Use local inner classes to create objects
Usb usb = new Fan();
usb.service();
// For classes that are used only once , Use anonymous inner classes ( It's equivalent to creating a local inner class )
Usb usb2 = new Usb() {
@Override
public void service() {
System.out.println(" The connection to the computer is successful , Fan 2 start-up ");
}
};
usb2.service();
}
}
2.Object class
- Superclass 、 Base class , The direct or indirect parent of all classes , At the top of the inheritance tree .
- Any class , If there is no writing extends Show inheriting a class , They all default to direct inheritance Object class , Otherwise, it is indirect inheritance .
- Object Methods defined in class , It's a method that all objects have
- Object Type can store any object
- As a parameter , Any object can be accepted
- As return value , You can return any object
2.1 getClass Method
- public final Class<?> getClass() {}
- Returns the actual object stored in the reference type
- application : It is usually used to determine whether the actual storage object types in two references are consistent .
package com.song.demo07;
public 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;
}
}
package com.song.demo07;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18);
Student s2 = new Student("songsong", 20);
// Judge s1 and s2 Is it the same type
Class class1 = s1.getClass();
Class class2 = s2.getClass();
if (class1 == class2) {
System.out.println("s1 and s2 In the same category ");
} else {
System.out.println("s1 and s2 Not of the same type ");
}
}
}
2.2 hasCode() Method
- public int hasCode() {}
- Returns the hash code value of the object
- The hash value is based on Address of the object or character string or Numbers Use hash The algorithm works out int Type value .
- In general Same object Returns the same hash code .— It can be used to determine whether it is the same object
package com.song.demo07;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18);
Student s2 = new Student("songsong", 20);
//getClass() Method
// Judge s1 and s2 Is it the same type
Class class1 = s1.getClass();
Class class2 = s2.getClass();
if (class1 == class2) {
System.out.println("s1 and s2 In the same category ");
} else {
System.out.println("s1 and s2 Not of the same type ");
}
//hasCode() Method
//s1,s2 It's two different objects , Different spaces are created in the heap of memory
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
Student s3 = s1;
System.out.println(s3.hashCode());
}
}
2.3 toString() Method
- public String toString() {}
- Returns the string representation of the object ( form )
- Can be covered according to program requirements ( rewrite ) The method , Such as : Display each attribute value of the object .– Methods inherited from the parent class cannot meet the requirements , Can be rewritten .
package com.song.demo07;
public 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 + "]";
}
}
package com.song.demo07;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18);
Student s2 = new Student("songsong", 20);
//getClass() Method
// Judge s1 and s2 Is it the same type
Class class1 = s1.getClass();
Class class2 = s2.getClass();
if (class1 == class2) {
System.out.println("s1 and s2 In the same category ");
} else {
System.out.println("s1 and s2 Not of the same type ");
}
//hasCode() Method
//s1,s2 It's two different objects , Different spaces are created in the heap of memory
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
Student s3 = s1;
System.out.println(s3.hashCode());
//toString() Method
System.out.println(s1.toString());// Before rewriting :[email protected](@ Later, it was also Hashimoto , Same as above
System.out.println(s2.toString());// Before rewriting :[email protected]
//toString() Method
System.out.println(s1.toString());// After rewriting :Student--[name=zhangsan, age=18]
System.out.println(s2.toString());// After rewriting :Student--[name=songsong, age=20]
}
}
2.4 equals() Method
- public boolean equals(Object obj) {}
- The default implementation is (this==obj), Compare the two Object address Are they the same? .
- It can be covered ( rewrite ), Compare the contents of two objects .
package com.song.demo07;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18);
Student s2 = new Student("songsong", 20);
//getClass() Method
// Judge s1 and s2 Is it the same type
Class class1 = s1.getClass();
Class class2 = s2.getClass();
if (class1 == class2) {
System.out.println("s1 and s2 In the same category ");
} else {
System.out.println("s1 and s2 Not of the same type ");
}
//hasCode() Method
//s1,s2 It's two different objects , Different spaces are created in the heap of memory
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
Student s3 = s1;
System.out.println(s3.hashCode());
//toString() Method
System.out.println(s1.toString());
System.out.println(s2.toString());
//equals() Method -- Before rewriting , Compare object addresses
System.out.println(s1.equals(s2));// Before rewriting , Compare addresses --false
System.out.println(s1.equals(s3));//true
Student s4 = new Student("lisa", 24);
Student s5 = new Student("lisa", 24);
System.out.println(s4.equals(s5));//fasle--s4 and s5 These are two objects in the heap
}
}
equals() Method override step :
- Compare whether two references point to the same object
- Judge obj Is it null
- Determine whether the actual object types pointed to by two references are consistent
- Cast
- Compare the values of each attribute in turn
package com.song.demo07;
public 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. Determine whether two object types are the same reference
if (this == obj) {
return true;
}
//2. Judge obj Whether it is null
if (obj == null) {
return false;
}
//3. Determine whether it is the same type
//if (this.getClass() == obj.getClass()) {
//instanceof You can determine whether an object is of a certain type
if (obj instanceof Student) {
//4. Cast
Student s = (Student) obj;
// String comparison with equals
if (this.name.equals(s.getName()) && this.age == s.getAge())
return true;
}
return false;
}
}
package com.song.demo07;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18);
Student s2 = new Student("songsong", 20);
//getClass() Method
// Judge s1 and s2 Is it the same type
Class class1 = s1.getClass();
Class class2 = s2.getClass();
if (class1 == class2) {
System.out.println("s1 and s2 In the same category ");
} else {
System.out.println("s1 and s2 Not of the same type ");
}
//hasCode() Method
//s1,s2 It's two different objects , Different spaces are created in the heap of memory
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
Student s3 = s1;
System.out.println(s3.hashCode());
//toString() Method
System.out.println(s1.toString());
System.out.println(s2.toString());
//equals() Method -- Before rewriting , Compare object addresses
System.out.println(s1.equals(s2));// Before rewriting , Compare addresses --false
System.out.println(s1.equals(s3));//true
Student s4 = new Student("lisa", 24);
Student s5 = new Student("lisa", 24);
System.out.println(s4.equals(s5));//fasle--s4 and s5 These are two objects in the heap
//equals() Method -- After rewriting , Compare object addresses , Object value, etc
System.out.println(s1.equals(s2));//false
System.out.println(s1.equals(s3));//true
System.out.println(s4.equals(s5));//true
}
}
2.5 finalize() Method
- When an object is determined to be a garbage object , from JVM Call this method automatically , To mark junk objects , Enter the recycle queue
- Garbage object : When no valid reference points to this object , For the garbage
- Garbage collection : from GC Destroy garbage objects , Free up data storage space
- Automatic recycling mechanism :JVM Run out of memory , Recycle all junk objects at once
- Manual recycling mechanism : Use System.gc(); notice JVM Carry out garbage collection .– Whether to implement recycling , It still depends on the program's own judgment , It is not necessary to recycle after notification
package com.song.demo07;
public 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. Determine whether two object types are the same reference
if (this == obj) {
return true;
}
//2. Judge obj Whether it is null
if (obj == null) {
return false;
}
//3. Determine whether it is the same type
//if (this.getClass() == obj.getClass()) {
//instanceof You can determine whether an object is of a certain type
if (obj instanceof Student) {
//4. Cast
Student s = (Student) obj;
// String comparison with equals
if (this.name.equals(s.getName()) && this.age == s.getAge())
return true;
}
return false;
}
@Override
protected void finalize() throws Throwable {
System.out.println(this.name+" The object is recycled ");
}
}
package com.song.demo08;
import com.song.demo07.Student;
public class TestStudent2 {
public static void main(String[] args) {
// Student s1 = new Student("aaa",12);
// Student s2 = new Student("bbb",14);
// Student s3 = new Student("ccc",16);
// Student s4 = new Student("ddd",18);
// Student s5 = new Student("eee",20);
new Student("aaa", 12);
new Student("bbb", 14);
new Student("ccc", 16);
new Student("ddd", 18);
new Student("eee", 20);
// Recycling waste
System.gc();
System.out.println(" Recycling waste ");
}
}
3. Packaging
Java Eight basic types in :byte、short、int、long、float、double、char、boolean
The basic data types are stored on the stack ; Other objects are stored in the heap , Only the address is stored in the stack .
The basic data type itself has no method , The corresponding reference types are designed for the eight data types ( Objects in the heap ), Provide methods to use
The reference data type corresponding to the basic data type .
Object Can unify all data , The default value for wrapper classes is null
Packaging class corresponds to – stay java The core of the package java.lang in

3.1 Type conversion and Boxing 、 Unpacking
Packing : Put the objects in the stack into the heap ( Basic type to reference type )
Unpacking : Put the objects in the heap on the stack ( Convert reference type to base type )
8 There are three kinds of packaging classes that provide the conversion between different types :
- Number Of the parent class 6 Methods for unpacking ( Convert reference type to base type )– It is byte、int、short、long、float、double Parent class of , You can convert the reference type to the basic type directly by its method
- parseXXX() Provide static methods – It can realize the conversion between string and basic type
- valueOf() Static methods
Be careful : Type compatibility is required , Otherwise throw NumberFormatException abnormal .

package com.song.demo09;
public class Demo01 {
public static void main(String[] args) {
//jdk1.5 The previous packing and unpacking methods
// Type conversion : Boxing operation , Basic type to reference type
// Basic types
int num1 = 18;// Basic types , Store in the stack
// Use Integer Class creation object
Integer integer1 = new Integer(num1);
Integer integer2 = Integer.valueOf(num1);
// Type conversion : Unpacking operation , Convert reference type to base type
Integer integer3 = new Integer(100);// The object is in the pile
int num = integer3.intValue();
//jdk1.5 Later packing and unpacking methods ,java It provides automatic packing and unpacking function -- The compiler automatically invokes method conversions
int age = 24;
// Automatic boxing
Integer integer4 = age;
// Automatic dismantling
int age2 = integer4;
}
}
- parseXXX() Provide static methods – It can realize the conversion between string and basic type
package com.song.demo09;
public class Demo02 {
public static void main(String[] args) {
// Conversion between basic types and strings
//1. Basic type converted to string
int n1 = 15;
// The way 1: Use + Number
String s1 = n1 + "";
// The way 2: Use Integer Medium toString() Method
String s2 = Integer.toString(n1);
String s3 = Integer.toString(n1, 16);// heavy load , Turn into 16 Base number
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
//2. String to basic type
String str = "150";
// Use Integer.parseXXX()
int n2 = Integer.parseInt(str);
//boolean Convert string to basic type ,“true"-->true; Not "true"-->false
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
}
}
3.2 Integer buffer
- Java Pre created 256 A commonly used integer wrapper type object ( Range :-128~127)
- In practical application , Reuse the created objects .
low=-128; high=127


package com.song.demo09;
public class Demo03 {
public static void main(String[] args) {
// Interview questions
Integer integer1 = new Integer(100);// Reference type
Integer integer2 = new Integer(100);// Reference type
System.out.println(integer1 == integer2);//false
// Reference type , Objects are stored in the heap ; Here we compare the addresses of two objects stored in the stack
//Integer integer3 = 100;// Automatic boxing , It's using Integer.valueOf() Method
//Integer integer4 = 100;
Integer integer3 = Integer.valueOf(100);
Integer integer4 = Integer.valueOf(100);
System.out.println(integer3 == integer4);//true
//100 stay -128 To 127 Buffer between , The object returned is the buffer interval
Integer integer5 = 200;// Automatic boxing
Integer integer6 = 200;
System.out.println(integer5 == integer6);//false
//200 be not in -128 To 127 Between , Not a buffer , The actual object address is returned
}
}
4.String class
- Strings are constants , After creating It can't be changed
- String literals are stored in String pool in , Sure share
Space :
- Stack
- Pile up
- Method area
Not to modify the original data , Is to open up a new space .–> Immutability

package com.song.demo09;
public class Demo04 {
public static void main(String[] args) {
String name = "hello";//"hello" Constants are stored in the string pool
name = "zhangsan";//“zhangsan” Assign a value to name--- Is a new space in the string pool , It's not about putting “hello” modify
String name2 = "zhangsan";
}
}
Realize the sharing in the string pool

String creation :
- String s=“Hello”;// Produce an object , String pool
- String s=new String(“Hello”);// Produce two objects , Pile up 、 Each pool stores one .( Actually run , Objects in the string pool are pointed to in the heap )

package com.song.demo09;
public class Demo04 {
public static void main(String[] args) {
String name = "hello";//"hello" Constants are stored in the string pool
name = "zhangsan";//“zhangsan” Assign a value to name--- Is a new space in the string pool , It's not about putting “hello” modify
String name2 = "zhangsan";
// Another way to create a string
String str = new String("Java Is the best language in the world ");// It's a waste of space
String str2 = new String("Java Is the best language in the world ");
System.out.println(str == str2);//false
System.out.println(str.equals(str2));//true
}
}
Tips : String comparison with equals
- == The comparison is the address
- equals The comparison is data (String Rewrite the equals Method )

4.1 Common methods
- public int length(): Returns the length of the string
- public char charAt(int index): Get the character from the subscript
- public boolean contains(String str): Determine if the current string contains str
- public char[] toCharArray(): Convert string to char Array
- public int indexOf(String str): lookup str First time subscript , There is , The subscript is returned ; non-existent , Then return to -1
- public int lastIndexOf(String str): lookup str Last occurrence of subscript , There is , The subscript is returned ; non-existent , Then return to -1
- public String trim(): Remove the space before and after the string
- public String toUpperCase(): Convert lowercase to uppercase
- public boolean endsWith(String str): Determine whether the string is based on str ending
- public String replace(char oldChar,char newChar): Replace the old string with the new one
- public String[] split(String str): according to str Make a split
- equals(); More equal
- compareTo(); Compare the order and size of strings in the dictionary table
package com.song.demo09;
import java.util.Arrays;
import java.util.Locale;
public class Demo04 {
public static void main(String[] args) {
String name = "hello";//"hello" Constants are stored in the string pool
name = "zhangsan";//“zhangsan” Assign a value to name--- Is a new space in the string pool , It's not about putting “hello” modify
String name2 = "zhangsan";
// Another way to create a string
String str = new String("Java Is the best language in the world ");// It's a waste of space
String str2 = new String("Java Is the best language in the world ");
System.out.println(str == str2);//false
System.out.println(str.equals(str2));//true
System.out.println("------------------ The use of string methods ---------------");
// The use of string methods
//1.length(); Returns the length of the string
//2.charAt(int index); Returns a character in a position
//3.contains(String str); Determine whether to include a string
String content = "Java Is the best language in the world ,Java It's delicious ,Java splendid ";
System.out.println(content.length());
System.out.println(content.charAt(content.length() - 1));
System.out.println(content.contains("Java"));
System.out.println(content.contains("PHP"));
System.out.println("-----------------------");
//4.toCharArray(); Returns the array corresponding to the string
//5.indexOf(); Returns the first occurrence of a string
//6.lastIndexOf(); Returns the last occurrence of a string
System.out.println(content.toCharArray());
System.out.println(Arrays.toString(content.toCharArray()));
System.out.println(content.indexOf("Java"));
System.out.println(content.indexOf("Java", 4));
System.out.println(content.lastIndexOf("Java"));
System.out.println("----------------------");
//7.trim(); Remove the space before and after the string
//8.toUpperCase(); Change lowercase to uppercase toLowerCase(); Turn upper case into lower case
//9.endsWith(str); Judge whether str ending startsWith(str); Judge whether str start
String content2 = " Hello World ";
System.out.println(content2.trim());
System.out.println(content2.toUpperCase());
System.out.println(content2.toLowerCase());
String filename = "Hello.java";
System.out.println(filename.endsWith(".java"));
System.out.println(filename.startsWith("Hello"));
System.out.println("----------------------");
//10.replace(old,new); Replace old with new characters or strings
//11.split(); Split the string
System.out.println(content.replace("Java", "PHP"));
String say = "Java is the best programming language";
String[] arr = say.split(" ");
System.out.println(arr.length);
for (String string : arr) {
System.out.println(string);
}
String say2 = "Java is the best programming language,java is good";
String[] arr2 = say2.split("[ ,]");//[] Express choice ,
System.out.println(Arrays.toString(arr2));
String say3 = "Java is the best programming language,java is good";
String[] arr3 = say2.split("[ ,]+");//+ Indicates that the preceding space and comma can appear one or more consecutively
System.out.println(Arrays.toString(arr3));
// Supplementary methods
//equals(); More equal
//compareTo(); Compare the order and size of strings in the dictionary table
String s1 = "hello";
String s2 = "HELLO";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));// Ignore size comparisons
String s3 = "abc";//a--> 97
String s4 = "xyz";//x--> 120
String s5 = "acb";
System.out.println(s3.compareTo(s4));//-23 The first character is different , Just compare the first , Difference between -23, There will be no comparison later
System.out.println(s3.compareTo(s5));//-1 The first character is the same , Compare the second , Difference between -1, The latter is no longer difficult
String s6 = "abc";
String s7 = "abcxyz";
System.out.println(s6.compareTo(s7));//-3 The previous part is exactly the same , Compare the length
}
}
4.2 example

package com.song.demo09;
public class Test {
public static void main(String[] args) {
String str = "this is a text";
//1. Put the word alone
String[] arr = str.split(" ");
for (String a : arr) {
System.out.println(a);
}
//2. Replace
System.out.println(str.replace("text", "practice"));
//3. Insert
System.out.println(str.replace("text", "easy text"));// Workarounds !!
//4. title case
for (int i = 0; i < arr.length; i++) {
char first = arr[i].charAt(0);// Word initials
// Capitalize the first letter
char upperfirst = Character.toUpperCase(first);
String newstr = upperfirst + arr[i].substring(1);//subs Intercepting string
System.out.println(newstr);
}
}
}
4.3 Variable string
- StringBuffer: Variable length string ,JDK1.0 Provide , Slow operation efficiency 、 Thread safety .
- StringBuilder: Variable length string ,JDK5.0 Provide , It's very efficient , Thread unsafe
package com.song.demo09;
/* StringBuffer and StringBuilder Use : and String The difference between :1) Than String Efficient ;2) Than String Save memory */
public class Demo05 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
//StringBuilder sb =new StringBuilder();//StringBuilder And StringBuffer The method is the same
//1.append(); Additional
sb.append("java is best");
System.out.println(sb.toString());
sb.append(" Java It's delicious ");
System.out.println(sb.toString());
sb.append(" Java splendid ");
System.out.println(sb.toString());
//2.insert(); Add insert
sb.insert(0, "first");
System.out.println(sb.toString());
//3.replace(); Replace
sb.replace(0, 5, "hello");
System.out.println(sb.toString());
//4.delete(); Delete
sb.delete(0, 5);
System.out.println(sb.toString());
//5. Empty
sb.delete(0, sb.length());
System.out.println(sb.length());
}
}
Efficiency comparison :StringBuilder>StringBuffer>String
package com.song.demo09;
// verification StringBuilder Efficiency is higher than String
public class demo06 {
public static void main(String[] args) {
/*long start = System.currentTimeMillis(); String str = ""; for (int i = 0; i < 99999; i++) { str += i; } System.out.println(str); long end = System.currentTimeMillis(); System.out.println(" when :" + (end - start));//38879 */
long start = System.currentTimeMillis();
StringBuilder str = new StringBuilder();
for (int i = 0; i < 99999; i++) {
str.append(i);
}
System.out.println(str);
long end = System.currentTimeMillis();
System.out.println(" when :" + (end - start));//49
}
}
5.BigDecimal class
package com.song.demo10;
public class TestBigDecimal {
public static void main(String[] args) {
double d1 = 1.0;
double d2 = 0.9;
System.out.println(d1 - d2);//0.0999999999
// Interview questions
double result=(1.4-0.5)/0.9;
System.out.println(result);//0.9999999
// The above questions are answered by double The approximate value storage method of the results in , To see is 1 Maybe what's actually stored is 0.9999999
}
}
Many practical applications require precise operations , and double yes Approximate value storage , Unqualified , You need to use an exact class ——BigDecimal.
- Location :java.math
- effect : accurate Calculate floating point number
- How it was created :BigDecimal b2 = new BigDecimal(“0.9”);
- Method :
- add() Add
- subtract() reduce
- multiply() ride
- divide() except

package com.song.demo10;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.xml.bind.SchemaOutputResolver;
import java.math.BigDecimal;
public class demo01 {
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("1.0");// Be sure to use the string construction method !! To guarantee accuracy
BigDecimal b2 = new BigDecimal("0.9");
// Subtraction
BigDecimal r1 = b1.subtract(b2);
System.out.println(r1);
// Add
BigDecimal r2 = b1.add(b2);
System.out.println(r2);
// Multiplication
BigDecimal r3 = b1.multiply(b2);
System.out.println(r3);
// division
BigDecimal r4 = new BigDecimal("1.4")
.subtract(new BigDecimal("0.9"))
.divide(new BigDecimal("0.5"));
System.out.println(r4);
// Particular attention , For division , When there is no end to it , You should specify how many decimal places to keep and how to keep them , Otherwise, the report will be wrong
BigDecimal r5 = new BigDecimal("10")
.divide(new BigDecimal("3"), 2, BigDecimal.ROUND_HALF_UP);// Round to two decimal places
System.out.println(r5);
}
}
6. Date related classes
6.1Date class
- Date Represents a specific moment , Accurate to milliseconds .Dtae Most of the methods in the class have been Calendaer Class .
- Location :java.util.Date
- Time unit
- 1 second =1000 millisecond
- 1 millisecond =1000 Microsecond
- 1 Microsecond =1000 nanosecond
Many methods are out of date , By Calendar Class substitution .
package com.song.demo10;
import java.util.Date;
public class demo02 {
public static void main(String[] args) {
//1. establish Date object
Date date1 = new Date();// Today's time
System.out.println(date1.toString());
System.out.println(date1.toLocaleString());// obsolete
Date date2 = new Date(date1.getTime() - 60 * 60 * 24 * 1000);// Yesterday's time
System.out.println(date2.toString());
//2. Method after before
boolean b1 = date1.after(date2);
System.out.println(b1);
boolean b2 = date1.before(date2);
System.out.println(b2);
//3. Compare compareTo(); Compare in milliseconds , Big return 1, Small return -1, Equal return 0
System.out.println(date1.compareTo(date2));
System.out.println(date1.compareTo(date1));
//4. Comparison is equal equals() Method
boolean b = date1.equals(date2);
System.out.println(b);
}
}
6.2Calendar class
Calendar Provides methods to get and set various calendar fields
Construction method
protected Calander(): Because the modifier is protected, So you can't create the object directly .
Other methods

package com.song.demo10;
import java.util.Calendar;
public class demo03 {
public static void main(String[] args) {
//1. establish Calendar object
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime().toString());
System.out.println(calendar.getTimeInMillis());
//2. Get time information
// Year of acquisition
int year = calendar.get(Calendar.YEAR);
// Get the month 0-11, The actual display can +1, It is the month of normal understanding
int month = calendar.get(Calendar.MONTH);
// Acquisition date
int day = calendar.get(Calendar.DATE);
// For hours
int hour = calendar.get(Calendar.HOUR_OF_DAY);//HOUR_OF_DAY--24 Hours ;HOUR--12 Hours
// Get minutes
int minute = calendar.get(Calendar.MINUTE);
// Get seconds
int second = calendar.get(Calendar.SECOND);
System.out.println(year + " year " + (month + 1) + " month " + day + " Japan " + hour + ":" + minute + ":" + second);
//3. Modification time
Calendar calendar2 = Calendar.getInstance();
System.out.println(calendar2.getTime().toString());
calendar2.set(Calendar.DAY_OF_MONTH, 5);// Revision date
System.out.println(calendar2.getTime().toLocaleString());
calendar2.set(Calendar.MONTH, 2);// Modify the month
System.out.println(calendar2.getTime().toLocaleString());
calendar2.set(Calendar.HOUR, 8);// When modifying
System.out.println(calendar2.getTime().toLocaleString());
//4. Modify based on the current time , increase
Calendar calendar3 = Calendar.getInstance();
System.out.println(calendar3.getTime().toLocaleString());
calendar3.add(Calendar.HOUR, 1);// Based on the current time , Plus an hour
System.out.println(calendar3.getTime().toLocaleString());
calendar3.add(Calendar.HOUR, -2);// Based on the current time , reduce 2 Hours
System.out.println(calendar3.getTime().toLocaleString());
//5. Supplementary methods
// Get the maximum value of the month in which the current time is located
int max = calendar3.getActualMaximum(Calendar.DAY_OF_MONTH);
int min = calendar3.getActualMinimum(Calendar.DAY_OF_MONTH);
System.out.println(max);
System.out.println(min);
}
}
6.3SimpleDateFormat class
- SimpleDateFormat Is a concrete class that formats and parses dates in a locale dependent manner
- format ( date -> Text )、 analysis ( Text -> date )
- Common time pattern letters

package com.song.demo10;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class demo04 {
public static void main(String[] args) throws ParseException {
//1. establish SimpleDateFormat object y year M month ( Custom format )
SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan HH:mm:ss");
//2. establish Date Time
Date date = new Date();
// format ( Convert date to string )
String str = sdf.format(date);
System.out.println(str);
// analysis ( Convert string to date )
Date date2 = sdf.parse("1998 year 01 month 08 Japan 08:12:12");// Must completely follow one of the above custom formats
System.out.println(date2);
}
}
7.System class
- System System class , It is mainly used to obtain system attribute data and other operations , The constructor is private .

package com.song.demo10;
public 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 int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ",age=" + age + "]";
}
//finalize Is the method that will be executed during garbage collection
@Override
protected void finalize() throws Throwable {
System.out.println(" Recycled "+name);
}
}
package com.song.demo10;
import java.util.Arrays;
public class demo05 {
public static void main(String[] args) {
//1.arraycopy Implement array copy ,
//src: Source array
//srcpos: Where to start copying
//des: Target array
//despos: Where to start placing
//length: The length of the copy
int[] src = {
20, 18, 16, 14, 12, 88};
int[] des = new int[6];
System.arraycopy(src, 0, des, 0, src.length);
System.out.println(Arrays.toString(des));
System.arraycopy(src, 2, des, 0, src.length - 2);
System.out.println(Arrays.toString(des));
//2.currentTimeMillis() Get the current time , Often used to time
System.out.println(System.currentTimeMillis());
//3.gc();// Garbage collection , Just suggest , It doesn't have to be recycled
// Student s1 = new Student("aaa", 18);
// Student s2 = new Student("bbb", 18);
// Student s3 = new Student("ccc", 18);
new Student("aaa", 18);
new Student("bbb", 18);
new Student("ccc", 18);
System.gc();
// here s1 s2 s3 No longer used , Determined as garbage object , Being recycled
//4.exit(); sign out jvm
System.exit(0);// state 0 Indicates normal exit
System.out.println(" Did the program exit ?");// The program has exited and will not execute the statement again
}
}
summary
Inner class :
- Define a complete class inside a class
- Member inner class 、 Static inner class 、 Local inner classes 、 Anonymous inner class
Object class
Direct or indirect parent of all classes , Can store any object
Packaging
The reference data type corresponding to the basic data type , You can make Object Unify all data
String class
Strings are constants , It cannot be modified after creation , Literal values are stored in the string pool , Can be Shared .
BigDecimal class
Floating point numbers can be calculated accurately
Date class – At a certain time
Calendar class – The calendar
SimpleDateFormat– Format time
System– System class
System.out.println(“ Recycled ”+name);
}
}
```java
package com.song.demo10;
import java.util.Arrays;
public class demo05 {
public static void main(String[] args) {
//1.arraycopy Implement array copy ,
//src: Source array
//srcpos: Where to start copying
//des: Target array
//despos: Where to start placing
//length: The length of the copy
int[] src = {20, 18, 16, 14, 12, 88};
int[] des = new int[6];
System.arraycopy(src, 0, des, 0, src.length);
System.out.println(Arrays.toString(des));
System.arraycopy(src, 2, des, 0, src.length - 2);
System.out.println(Arrays.toString(des));
//2.currentTimeMillis() Get the current time , Often used to time
System.out.println(System.currentTimeMillis());
//3.gc();// Garbage collection , Just suggest , It doesn't have to be recycled
// Student s1 = new Student("aaa", 18);
// Student s2 = new Student("bbb", 18);
// Student s3 = new Student("ccc", 18);
new Student("aaa", 18);
new Student("bbb", 18);
new Student("ccc", 18);
System.gc();
// here s1 s2 s3 No longer used , Determined as garbage object , Being recycled
//4.exit(); sign out jvm
System.exit(0);// state 0 Indicates normal exit
System.out.println(" Did the program exit ?");// The program has exited and will not execute the statement again
}
}
summary
Inner class :
- Define a complete class inside a class
- Member inner class 、 Static inner class 、 Local inner classes 、 Anonymous inner class
Object class
Direct or indirect parent of all classes , Can store any object
Packaging
The reference data type corresponding to the basic data type , You can make Object Unify all data
String class
Strings are constants , It cannot be modified after creation , Literal values are stored in the string pool , Can be Shared .
BigDecimal class
Floating point numbers can be calculated accurately
Date class – At a certain time
Calendar class – The calendar
SimpleDateFormat– Format time
System– System class
边栏推荐
- Technical past: tcp/ip protocol that has changed the world (precious pictures, caution for mobile phones)
- cartographer_ pose_ graph_ 2d
- 2. < tag dynamic programming and conventional problems > lt.343 integer partition
- 国务院发文,完善身份认证、电子印章等应用,加强数字政府建设
- 【Unity3D】人机交互Input
- Zuul 實現動態路由
- AD教程系列 | 4 - 创建集成库文件
- How to make your big file upload stable and fast?
- LeetCode 19. 删除链表的倒数第 N 个结点
- Decipher the AI black technology behind sports: figure skating action recognition, multi-mode video classification and wonderful clip editing
猜你喜欢

Install the tp6.0 framework under windows, picture and text. Thinkphp6.0 installation tutorial

Codeforces Round #802 (Div. 2)(A-D)

Wechat team sharing: technical decryption behind wechat's 100 million daily real-time audio and video chats

Leetcode513.找出树的左下角的值
![C# 40. Byte[] to hexadecimal string](/img/3e/1b8b4e522b28eea4faca26b276a27b.png)
C# 40. Byte[] to hexadecimal string

Henkel database custom operator '~~‘

Yunqi lab recommends experience scenarios this week, free cloud learning

Replacing domestic image sources in openwrt for soft routing (take Alibaba cloud as an example)

Decipher the AI black technology behind sports: figure skating action recognition, multi-mode video classification and wonderful clip editing

百度API地图的标注不是居中显示,而是显示在左上角是怎么回事?已解决!
随机推荐
6.1 - 6.2 公钥密码学简介
Introduction to GUI programming to game practice (I)
Muke.com actual combat course
Two step processing of string regular matching to get JSON list
【红队】要想加入红队,需要做好哪些准备?
Gd32f3x0 official PWM drive has a small positive bandwidth (inaccurate timing)
Chapter 9 setting up structured logging (I)
Classic theory: detailed explanation of three handshakes and four waves of TCP protocol
cartographer_fast_correlative_scan_matcher_2d分支定界粗匹配
AD教程系列 | 4 - 创建集成库文件
Yunqi lab recommends experience scenarios this week, free cloud learning
Pycharm package import error without warning
LeetCode_二叉搜索树_简单_108.将有序数组转换为二叉搜索树
6.1 - 6.2 introduction to public key cryptography
百度API地图的标注不是居中显示,而是显示在左上角是怎么回事?已解决!
data = self._data_queue.get(timeout=timeout)
Implementation of IM message delivery guarantee mechanism (II): ensure reliable delivery of offline messages
skimage. morphology. medial_ axis
Tensorflow and deep learning day 3
thread priority