java learning notes

Keywords: Java Hibernate

1, Object oriented

1. Object oriented

Object Oriented (OO) is also called Object Oriented thought. It is not only a programming thinking, but also a way of thinking.

The basic idea is the three characteristics of object-oriented, inheritance, encapsulation and polymorphism.

2. Cumulative sum object

Class: is the abstraction of object! Object is the concrete of class!

Class: it is the description or address of a class of specific things with the same characteristics or attributes and the same behavior ability.
Object: an individual or instance of this kind of things with attribute values and specific behaviors.

3. Class definition and use

According to the hump structure, if it is a variable, the first letter of each word should be lowercase; if it is a class name, the first letter of each word should be uppercase

stay Java Define a class using class Keyword, a legal identifier and a pair of braces representing the body of the program.

The syntax is as follows:

[Access modifier ] class <classname>{          --class keyword       --classname   A valid identifier
<body of the class>
}
class Is the keyword used to create the class
<classname> Represents the name of the class, abbreviated as the class name. It is a reference for writing specifications [Alibaba Java Development Manual]
<body of the class> Contains properties and methods

What are the properties (characteristics) of a class?

       //What are the attributes of a car called a class
		//brand
		private String brand;
		//name
		private String name;
		//colour
		private String color;
		//Frame number
		private String vin;

Summary:

The attributes in the class definition are described by specific data types and names. Attributes describe what all the specific objects represented by this class have, that is, the attributes of this class

What about the method?
What does a class's method (behavior) do?

 //What can a car do?
		public void canRun(){
			System.out.println("Cars can run!");
		}

Summary:

The method in a class describes what all the specific objects represented by the class can do, that is, the behavior (method) of the class.

How are classes used?

The definition of a class is a description of something. It is an abstraction. If you want to use a class, you need to generate the object of the class.

How to generate objects, you can use the new keyword, which can create objects

  Car car = new Car();

How do I use the object I just created-- That is, how to access properties and methods

		public class Car {
		//What does the car have? 	---- Called class properties
		//brand
		private String brand;
		//name
		private String name;
		//colour
		private String color;
		//Frame number
		private String vin;
		//What can a car do? 	--- method
		public void canRun(){
			System.out.println("Cars can run!");	
		}
  
		public static void main(String[] args) {
			//1. Create object new
			Car car=new Car();
			//2. How to use attributes
			//2.1. Set values for attributes
			car.brand="Tesla";
			car.name="Model3";
			car.color="silver";
			car.vin="13525738475";
			//2.2. Get attribute value
			System.out.println(car.brand);
			System.out.println(car.name);
			System.out.println(car.color);
			System.out.println(car.vin);
			//3. How to call a method
			car.canRun();	
		}
The default value of the property. If no value is set for the property, the obtained property is null
attributeDefault value
byte0
charThe default value of char is null character
short0
int0
long0
float0.0
double0.0
booleanfalse
Stringnull

4. Construction method

Construction method definition:

For constructors, there is no return value

Construction method: it is a special method used to create objects. It is divided into nonparametric construction method and parametric construction method

Parameter free construction method

 There is a parameter free construction method in each class, that is, it can be used directly without writing
        Car car=new Car();

Construction method with parameters

If we define a construction method with parameters, the system will no longer provide a grinding parameter free construction method
        public Car(String name){
            this.name=name;
        }

If the parameter constructor is used, an error will be reported when the default parameter free constructor is used

   	    Car car=new Car("ModelX");  
        Car car=new Car();        --An error will be reported at this time; I can't write that

solve

1.Because he doesn't know
        Car car=new Car(); method
2.Create a new parameterless construction method
        public Car(){
        	
        		}

5. this keyword

Used in construction methods with parameters

 this A keyword is a reference to the current object    
         public Car (String name){
            this.name=name;
        }

this keyword is generally used in construction methods

6. Method overloading

Definition: if there are multiple methods with the same name in a class (method names are the same), but the number of parameters or parameter types are different, this is called method overloading
The purpose of method overloading is that methods with similar functions use the same name, which is easier to remember, so it is easier and simpler to call.

Note: the return value type of method overloading is usually the same, that is, the return value is not used as the judgment basis of overloading

7. static keyword

It has two functions
static modified variable

Static variables, which can be accessed directly through the class name

static modification method

Static method, which can be called directly through the class name

difference:
Can I use common attribute static variable common method static method ok in common method
Can ordinary attributes be used in static methods( ×) Static variable (√) general method( ×) Static method (√)

Access in the main method

    //First statement
    // Normal member variables
	int a;
	// Static member variables
	static int b;
	// Common method
	public void ceshifangfa() {
         System.out.println("General test methods");
	}
 	// Static method
	public static void ceshijingtaifangfa() {
		System.out.println("Test static method");
	}

Access in the main method

	public static void main(String[] args) {
    //Common variable
    //1. Create an object first, and then a default parameterless construction method will be called 
    StaticDemo staticDemo = new StaticDemo();
    //2. Output the object and variable names 	  staticDemo.a
    System.out.println(staticDemo.a);
    
    // How to access static variables
    // 1. Directly use the variable name defined by the class name
    staticDemo.b=5;
    System.out.println(staticDemo.b);

    // How do I access it by ordinary methods
    // 1. Use object name and method name
    staticDemo.ceshifangfa();

    // How are static methods accessed
    // 1. Use class name and method name
     StaticDemo.ceshijingtaifangfa();
}

In the common method

	// Common method
     public void ceshifangfa() {
		// Ordinary variables
		System.out.println(a);

		// Static variable
		System.out.println(b);

		// Common method
		text();

		// Static method
		ceshijingtaifangfa();

		System.out.println("General test methods");
	}

In static methods

          public static void main(String[] args) {
              //Ordinary variables
		 System.out.println(a);            //  Error reporting red
				
		 //Static variable
		 System.out.println(b);
				
		 //Common method
        	 text();                           //  Error reporting red
		 ceshifangfa();
				
		 //Static method
		 ceshijingtaifangfa();
   }
 package static_text;
    public class StaticDemo {
     // Normal member variables
	int a;
	// Static member variables
	static int b;

	// Common method
	public void ceshifangfa() {
		// Ordinary variables
		System.out.println(a);
		// Static variable
		System.out.println(b);
		// Common method
		text();
		// Static method
		ceshijingtaifangfa();
		System.out.println("General test methods");
	}
	
	// Common method 2
	public void text() {
		System.out.println("Common method 2");
	}
	
	// Static method
	public static void ceshijingtaifangfa() {
		System.out.println("Test static method");
	}
	
	public static void main(String[] args) {
		// How to access ordinary member variables -- attribute access
		// 1. Create an object first, and then a default parameterless construction method will be called
		// 2. Output 	 Object. Variable name 	  staticDemo.a
		StaticDemo staticDemo = new StaticDemo();
		// staticDemo.a=10;
		// System.out.println(staticDemo.a);

		// How to access static variables
		// 1. Directly use the variable name defined by the class name
		// staticDemo.b=5;
		// System.out.println(staticDemo.b);

		// How do I access it by ordinary methods
		// 1. Use object name and method name
		staticDemo.ceshifangfa();

		// How are static methods accessed
		// 1. Use class name and method name
		// StaticDemo.ceshijingtaifangfa();

		// difference
		// Can I use common attribute static variables common methods static methods ok
		// Can ordinary attributes be used in static methods( ×)  Static variable (√) general method( ×)  Static method (√)

		// //Ordinary variables
		// System.out.println(a);
		//		
		// //Static variable
		// System.out.println(b);
		//		
		// //Common method
		// text();
		// ceshifangfa();
		//		
		// //Static method
		// ceshijingtaifangfa();
  }
  }

2, Inheritance and polymorphism

1. Master the meaning and usage of inheritance

1.1. What is inheritance? extends - inheritance keyword.

Inheritance: it is a cornerstone of java object-oriented programming technology because it allows the creation of hierarchical classes.

1.2 concept of inheritance

Inheritance is that a subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the properties and methods of the parent class, or the subclass inherits methods from the parent class, so that the subclass has the same behavior as the parent class.

1.3. Analysis of inheritance

Car(Motor vehicles) and Truck(Truck class) classes have some of the same properties and methods. We will create a new class with these common properties and methods Vehicle(Vehicle class), so that Car and Truck Both classes inherit
 since Vehicle class,have Vehicle Class.

1.4 role of inheritance

Inheritance is an important mechanism of object-oriented language. With inheritance, the original code can be extended and applied to other programs without rewriting these codes, that is, the code can be reused

1.5 examples

Vehicle(Vehicle class) has basic attributes and methods.
Truck(Truck type) inherited from Vehicle(Vehicle class) has a parent class Vehicle Properties and methods, and we only need to care Vehicle A separate property or method.

1.6 format of inheritance

 [ public ] class Parent class{
       
   }
   [ public ] class Subclass extends Parent class{
       
   }

1.7 type of inheritance

java Multiple inheritance is not supported, but multiple inheritance is supported

graphic

1.8 characteristics of inheritance

  1. Subclasses have non private member properties and member methods of the parent class (do not inherit the constructor of the parent class)
  2. Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
  3. Subclasses can implement the methods of their parent classes in their own way.
  4. java inheritance is single inheritance, but it can be multiple inheritance.
  5. It improves the coupling between classes (the disadvantage of inheritance, the higher the coupling will cause the closer the connection between codes, the worse the code independence).

2. Master method rewriting

2.1 method rewriting (overwriting)

Override in the inheritance relationship, the subclass improves the method inherited from the parent class and becomes its own method. This phenomenon is called method override or method coverage.

2.2 requirements for rewriting

  1. Three same principles: the same method name, the same return type and the same parameter table. The method body can be different
  2. Overridden methods in subclasses cannot use more stringent access rights than overridden methods in parent classes.

2.3 difference between method overloading and Rewriting:

  1. Methods in a class that meet the same method name and parameter list are called method overloading.
  2. Subclasses override methods inherited from the parent class as needed.

3. Understanding polymorphism and its application

3.1 introduction and examples of polymorphism

Polymorphism refers to a variety of forms. For example, it is also a component of water, but it also has a variety of forms of liquid water and ice. The same carbon dioxide has a variety of forms such as gas and liquid. The same cat has the difference between cat and tiger

3.2. The performance of inheritance is polymorphism.

A parent class can have multiple subclasses,In a subclass, you can override the methods of the parent class,The code rewritten by each subclass is different,The form of natural expression is different. If you use the variables of the parent class to refer to different subclass objects,In call
 When the same method is used, the results and forms are different,This is polymorphism.

be careful:

One more thing to note is,An object created by a parent class reference,Only methods that a subclass inherits from a parent class can be called,You cannot call your own extended methods.

4. Master super keyword

super keyword
Super (super class): in ava terms, the inherited class is called super class, and the inherited class is called subclass.

At some point,The subclass needs to call some methods of the parent class,We need it at this time super. 
super Key and this Similar function,Is a masked member variable or member method or becomes visible,Or used to reference masked member variables and member methods super Is used in subclasses,The purpose is to visit
 Masked member in direct parent class,Note that it is a direct parent class(Is the nearest superclass above the class)

5. Understanding Object classes

The Object class is the superclass (parent class) of all classes in Java

  • All classes inherit from the Obejct class by default
  • Each class can use the methods of the Object class
toString()     Returns the string representation of the object. Usually, the modified method will return the string of an object "represented in text".
hashCode()     Returns the hash code value of the object.
equals()       Indicates whether some other object is "equal" to this object.

6. Master the final keyword

  1. flnal represents the final, which can be used to modify classes, methods, attributes (variables).
  2. flnal decorated classes cannot be inherited.
  3. flnal decorated methods cannot be overridden.
  4. flnal decorated attributes (variables) cannot be changed - that is, the way constants are defined.

3, Package, abstract class, interface

1. Master the use of package

1.1 meaning of package

Java One of package(Package) is a class library unit. A package contains a group of classes. They are organized together under a single namespace, which is the package name.

Common package names in projects are classified by function and layer

Name of the packageDescription and interpretation
daoIt deals with databases
modelGenerally physical content
serviceBusiness layer
utilTool class
testTest class

1.2 what is the function of the package?

  1. Organize similar or related classes or interfaces in the same package to facilitate the search and use of classes.
  2. Like folders, packages are stored in a tree directory. The class names in the same package are different, and the class names in different packages can be the same. When calling classes with the same class name in two different packages at the same time, the package name should be added to distinguish them. Therefore, packages can avoid name conflict.
  3. Packages also limit access rights. Only classes with package access rights can access classes in a package.

1.3 declaration of package

Syntax structure:

package pkg1 [.pkg2 [.pkg3...] ];
pkg1 pkg2 pkg3 Is the folder name in the file system, and there is a parent-child directory relationship.
The purpose of the package declaration is to describe this Java Which package or file directory does the class file belong to   

Use of packages

import pkg1 [.pkg2 [.pkg3...] ].<classname>|*;                 impor It is used by introducing classes in the package
    pkg1 pkg2 pkg3 Is the folder name in the file system, and there is a parent-child directory relationship.
    classname Represents the specified class to be introduced. Or
    * Represents all classes under the imported sub package.
The use of packages is actually in a Java Class that uses other packages Java Class.

2. Master abstract classes

1.1 concept of abstract class

In the object-oriented domain, everything is an object,At the same time, all objects are described by classes,But not all classes are just to describe objects.
The description of things in our abstract class is not specific enough. What is not specific enough? We have no way to describe this thing.

give an example

such as new Animal(),We all know that this is to produce an animal Animal object,But this Animal We don't know what it looks like,It doesn't have a specific animal concept,So he is one
 abstract class,Need a specific animal,Such as dogs and cats,WeオKnow what it looks like.

1.2 abstract method

Abstract method is that we have no method body and no way to implement this method concretely.

Specific performance

That's what we use abstract This keyword, we are class Add before abstract  ,So this is the abstract class

Abstract method

  1. No method body
  2. Have abstract
    If we have abstract methods, this class must be an abstract class.

1.3. How to write abstract classes

stay Java Use in language abstract    stay class Add before  abstract To define abstract classes, you can also define abstract methods.

How to use abstract classes?

An abstract class must instantiate an object through its subclasses.

1.4 precautions for abstract classes:

  1. Classes that contain abstract methods are abstract classes.
  2. Abstract classes do not necessarily have abstract methods.
  3. Abstract classes cannot create objects directly and must be implemented through subclasses, so abstract and final cannot modify classes together.
  4. abstract cannot modify the same method in parallel with static and final.

3. Understand the use of interfaces

1.1 interface

An interface is a structure or class that is more abstract than an abstract class. It is usually described by interface.

1.2 abstract classes and interfaces

nameabstract classinterface
inheritOnly one class can be extendedMultiple interface s can be implemented
fieldYou can define instance fieldsInstance fields cannot be defined
Abstract methodAbstract methods can be definedAbstract methods can be defined
Non abstract methodYou can define non abstract methodsYou can define the defau method

4. Master the use of access modifiers

Access modifiers: in Java, access modifiers can be used to protect access to classes, variables, methods, and constructor methods

categoryAccess rightsUse object
Default (i.e. default, write nothing):Visible in the same package.Class, interface, variable, method
private:Visible within the same category.Variables, methods. Note: you cannot decorate classes (external classes)
public:Visible to all classes.Class, interface, variable, method
protected:Visible to classes and all subclasses within the same package.Using objects: variables, methods. Note: classes (external classes) cannot be decorated

Access modifier range

keywordIn the same classIn the same packageIn derived classesIn other packages
private:
default
protected:
public:

be careful

We usually write public Generally, write entity classes, and attributes are generally private  The method is generally public 

4, Common classes in java (1)

1, Packaging

1.1 what is packaging?

Byte,Boolean,Character,Short Integer Long,Float Double, They are all packaging.

1.2 functions of packaging

  • Java language is an object-oriented language, but the basic data types in Java are not object-oriented.
  • That is, you cannot use some methods provided by the Object class, such as toString(), or have some Object-oriented features. You cannot participate in the process of transformation, genericity, reflection, etc,
  • Similarly, it cannot participate in the operation of collections, so in order to make up for these shortcomings, Java provides wrapper classes.

1.3 what are the packaging types?

Basic typePackaging type
byteByte
booleanBoolean
charCharachte
chortShort
intInteger
longLong
floatFloat
doubleDouble

1.4 how to use packaging?

Packing basic data type - > packing type this process is called packing.
Unpacking packing type - > basic data type. This process is called unpacking.
Wrapper class Integer for int

//int Integer
		int a=7;
		Integer b=new Integer(7);  //Packaging
		Integer c=new Integer("7");
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);

		//Conversion between int and Integer
		//Int -- > integer boxing operation
		int i1=8;
		Integer i2=new Integer(i1);  //Packing operation
		Integer i3=i1;  //Automatic packing operation
		System.out.println("--int ---> Integer Packing operation");
		System.out.println(i1);
		System.out.println(i2);
		System.out.println(i3);
		
		//Integer -- > int unpacking operation
		int i4=i2.intValue();//("-- integer - > int unpacking operation");
		int i5=i2;//Automatic unpacking operation
		System.out.println("Integer--->int Unpacking operation");
		System.out.println(i4);
		System.out.println(i5);

Wrapper class of byte

  byte b = 3;
            Byte b2 = 3;
            Byte b3 = new Byte((byte) 3);
            Byte b4 = new Byte("3");
            System.out.println(b);
            System.out.println(b2);
            System.out.println(b3);
            System.out.println(b4);
            
            // Byte to byte conversion
            // Byte -- > byte boxing operation
            Byte b5 = new Byte((byte) 8);//Packing operation
            Byte b6 = (byte) 8;//Automatic packing operation
            
            //Byte -- > byte unpacking operation
            byte b7 = b5.byteValue();//Unpacking operation
            byte b8 = b6;//Automatic unpacking operation
            
            System.out.println(b5);
            System.out.println(b6);
            System.out.println(b7);
            System.out.println(b8);

Wrapper class of Boolean

   boolean b=false;
		Boolean b2=new Boolean(false);
		Boolean  b3=new Boolean("false");
		System.out.println(b);
		System.out.println(b2);
		System.out.println(b3);
		
		//Boolean to Boolean conversion
		//Boolean -- > Boolean boxing operation
		Boolean b4=new Boolean(b);//Packing operation
		Boolean b5=b;			//Automatic packing operation
		System.out.println("--Boolean ---> Boolean Packing operation--");
		System.out.println(b4);
		System.out.println(b5);
		
		//Boolean -- > unpacking operation
		boolean b6=b4.booleanValue();//Unpacking operation
		boolean b7=b4;//Automatic unpacking operation
		System.out.println("--Boolean--->boolean Unpacking operation--");
		System.out.println(b6);
		System.out.println(b7);

2, String class

1.1. Writing of String class

String class is a character class and a class we often use. We generally store all kinds of character data

Common writing:

String str = "This is a string";

In addition to this, there are:

String str = new String("This is how a class should create objects");

In fact, the String is represented by a char [] array inside the String. Therefore, it is possible to write it as follows:

String str = new String(new char[]{'this','yes','one','species','create','build','square','type'});

1.2. Characteristics of string class: String invariance

  • Because strings are so commonly used, Java provides the first way to express literals
  • The String class is internally implemented by private final char [] and does not provide any method to modify char [], so the String is invariant,
  • That is, we usually say that the string is immutable

1.3 common methods:

1.3.1. char charAt(int index) returns the char value at the specified index

String str = "This is the first test string";
char c1 = str.charAt(0);//this
char c2 = str.charAt(1);//yes
char c3 = str.charAt(2);//The first

1.3.2 String concat(String str) connects the specified string str to the end of the current string and returns the new string object

String name = "Zhang San";
String newName = name.concat("-teacher");
System.out.println(name);//Zhang San
System.out.println(newName);//Zhang San - teacher

1.3.3. Boolean contains (charsequences) whether the string object contains the specified character sequence (generally considered as a string)

String str = "abcdefghijkzhangsanlmnopk";
boolean isContains = str.contains("zhangsan")
System.out.println(isContains);//true

1.3.4. boolean startsWith(String prefix) whether the string starts with the specified prefix
1.3.5. boolean endsWith(String suffix) whether the string ends with the specified suffix

String str = "This is a text file.txt";
boolean b1 = str.startsWith("t");//false
boolean b2 = str.startsWith("This is");//true
boolean b3 = str.endsWith("txt");//true
boolean b4 = str.endsWith("t");//true

1.3.6 boolean equals(Object anObject) compares the contents of this string object with the specified object

String str = "This is the first string";
String str2 = "This is the second string";
String str3 = new String("This is the first string");
System.out.println(str.equals(str2));//false
System.out.println(str.equals(str3));//true
System.out.println(str2.equals(str3));//false

1.3.7. Boolean equalsignorecase (string otherstring) compares the string object with the specified content, ignoring case

String str = "abcd";
String str2 = "aBCd";
System.out.println(str.equals(str2));//false
System.out.println(str.equalsIgnoreCase(str2));//true

1.3.8. int indexOf(int ch) returns the index of the first occurrence of the specified character in the string object
1.3.9. int indexOf(String str) returns the index of the first occurrence of the specified string in the string object
1.3.10. int lastIndexOf(int ch) returns the index of the last occurrence of the specified character in the string object
1.3.11. int lastIndexOf(String str) returns the index of the last occurrence of the specified string in the string object

String str = "I am a test string,This is a real string";
System.out.println(str.indexOf('strand'));//8
System.out.println(str.indexOf("character string"));//6
System.out.println(str.lastIndexOf('strand'));//16
System.out.println(str.lastIndexOf("character string"));//14

1.3.12. int length() returns the length of this string
1.3.13. boolean isEmpty() is the string empty

String str = "";
String str1 = "This is not an empty string";
System.out.println(str.length());//0
System.out.println(str1.length());//5
System.out.println(str.isEmpty());//true
System.out.println(str1.isEmpty());//false

1.3.14 String replace(char oldChar, char newChar) returns the new String object after replacing oldChar with newChar

1.3.15 String replace(CharSequence oldString, CharSequence newString) returns a new String object after replacing newString with oldString

String str = "Zhang San is a Java Cheng xuape!";
String newStr = str.replace('ape','member');
String newStr2 = str.replace("Java","C#");
System.out.println(str);//Zhang San is a Java program ape!
System.out.println(newStr);//Zhang San is a Java programmer!
System.out.println(newStr2);//Zhang San is a C# programmer!

1.3.16 String[] split(String regex) splits strings according to a given string or regular expression

String str ="The flowers are similar year after year,People are different from year to year!";
String[] strs = str.split("year");
for (String s : strs) {
	System.out.println(s);//{"every year", "flowers are similar", "people are different every year!"}
}

String[] strs2 = str.split("every year");
for (String s : strs2) {
	System.out.println(s);//{"every year", "flowers are similar", "people are different every year!"}
}

1.3.17. String substring(int beginIndex) returns the string at the specified starting position

1.3.18. String substring(int beginIndex,int endIndex) returns the string with the specified starting position and the specified ending position

String str ="The flowers are similar year after year,People are different from year to year!";
System.out.println(str.substring(3));//Flowers are similar, but people are different from year to year!
System.out.println(str.substring(3, 10));//Years are like flowers

1.3.19. String toLowerCase() returns the lowercase characters of this string

1.3.20. String toUpperCase() returns the uppercase characters of this string

String str ="Hello World!";
System.out.println(str.toLowerCase());//hello world!
System.out.println(str.toUpperCase());//HELLO WORLD!

1.3.21. String trim() returns a new string with all spaces before and after the string removed

String str ="  Hello World!  ";
System.out.println(str);//"  Hello World!  "
System.out.println(str.trim());//"Hello World!"

1.3.22. static String valueOf(...) converts parameter contents into String objects

Integer i = new Integer(4);
char[] charArray = {'H','e','l','l','o',' ','w','o','r','l','d','!'};
String s =String.valueOf(i);
String s2 =String.valueOf(charArray);
System.out.println(s);//4
System.out.println(s2);//Hello world!

3, String int Integer conversion

1. String int Integer conversion

1.1,String –> int

String str = "123";
int i = Integer.parseInt(str);

1.2,String –> Integer

String str = "123";
Integer i = new Integer(str);
Integer i2 = Integer.valueOf(str);

1.3,int –> Integer

int i = 123;
Integer i2 = i;
Integer i3 = new Integer(i);

1.4,int –> String

int i = 123;
String s1 = i + "";
String s2 = String.valueOf(i);

** 1.5,Integer –> int**

Integer i = new Integer(123);
int i2 = i;
int i3 = i.intValue();

1.6,Integer –> String

Integer i = new Integer(123);
String s1 = i + "";
String s2 = String.valueOf(i);

4, StringBuffer class

  • In practice, we often use string related operations, which leads to a problem, which is still serious,
  • Due to the invariance of the string, any operation such as adding, deleting and replacing a string will produce a new string object,
  • If the order of magnitude of this operation is very large, it will consume a lot of system memory and delay the execution time of the program,
  • Therefore, in order to solve this problem, a StringBuffer class - string buffer class appears

This class also provides a chained access mode:

StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
    sb.append(',').append(i);//Chain operation
//   sb.append(',');
//   sb.append(i);
}
String s = sb.toString();
System.out.println(s);//Output string buffer class as string type

The return value of the append method is this, that is, the current object, so you can continue to use the return value of this method to call other related methods

5, StringBuilder class

  • The StringBuilder class also represents variable string objects. In fact, StringBuilder and StringBuffer are basically similar,
  • The constructors and methods of the two classes are also basically the same.
    The difference is:
  • StringBuffer is thread safe,
  • StringBuilder does not implement thread safety, so its performance is slightly higher.
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
    sb.append(',').append(i);//Chain operation
//   sb.append(',');
//   sb.append(i);
}
System.out.println(sb.toString());//Output string buffer class as string type

The methods in the StringBuffer class are locked with the synchronized keyword, so it is safer to use StringBuffer in multithreading,
Using StringBuilder in a single thread provides better performance.

Posted by devarishi on Wed, 22 Sep 2021 21:30:12 -0700