Java Notes: Fundamentals

Java Notes (1)

1 Basic Grammar

  1. Case Sensitive: Java is case sensitive, which means the identifier Hello and hello are different.
  2. Class name: For all classes, the first letter of the class name should be capitalized. If the class name consists of several words, the first letter of each word should be capitalized, for example, MyFirstJavaClass.
  3. Method name: All method names should begin with a lowercase letter. If the method name contains several words, each subsequent word will be capitalized.
  4. Source File Name: The source file name must be the same as the class name. When saving a file, you should use the class name as the file name (remember that Java is case sensitive) and the suffix of the file name is. java. (This will cause compilation errors if the file name and class name are not the same).
  5. Main method entry: All Java programs are started by the public static void main(String[] args) method.

1.1 Keyword (Mastery)

  1. Words given specific meaning by the Java language
  2. Features: All lower case.
  3. Matters needing attention:
    A:goto and const exist as reserved words.
    B: Advanced notebooks like Notepad++ have special color tags for keywords

1.2 Identifier (Master)

  1. All identifiers should start with a letter (A-Z or a-z), a dollar sign ($), or an underscore ()
  2. Any combination of characters that can be followed by a letter (A-Z or a-z), a dollar sign ($), an underscore (), or a number
  3. Keyword cannot be used as an identifier
  4. Identifiers are case sensitive
Examples of legal identifiers: age,$salary,_value,__1_value
 Illegal identifier example: 123 abc,-salary
  1. Common naming rules (see Name Consciousness)
    A: All lower case packages
    _Single-level package: lowercase
    Example: liuyi,com
    _Multilevel package: lowercase and separated by.
    Example: cn.itcast,
    B:Class or interface
    _A word: first letter uppercase
    Example: Student,Demo
    _Multiple words: capitalize the first letter of each word
    Example: HelloWorld,StudentName
    C: Method or variable
    _One word: lowercase first letter
    Example: name,main
    _Multiple words: start with the second word and capitalize the first letter of each word
    Example: studentAge,showAllNames()
    _All capitals
    _One word: uppercase
    Example: PI
    _Multiple words: uppercase, separated by _
    Example: STUDENT_MAX_AGE

1.3 Comments (Master)

  1. Is the text explaining the program
  2. Classification:
    A: Single line comment//
    B: Multiline comments/* */
    C: Document comments (later)/** */
  3. Write a commented version of the HelloWorld case.
    Later we'll write a procedure.
    Requirements, analysis, implementation, code representation;
  4. The role of notes
    A: Explain the program to improve the readability of the code.
    B: Can help us debug programs.

1.4 Java Modifier

Like other languages, Java can use modifiers to modify methods and properties in classes. There are two main types of modifiers:

Access control modifiers: default, public, protected, private
Non-access control modifiers: final, abstract, static, synchronized

1.5 Constant (Master)

  1. The amount by which the value of a program will not change during execution
  2. Classification:
    _A: Literal value constant
    _B: Custom constants (later)
  3. literal constant
    _A: String constant "hello"
    _B:Integer constant 12,23
    _C: Decimal constant 12.345
    _D: Character constants'a','A','0'
    _E:Boolean constant true,false
    _F: empty constant null (later)
  4. Four representations of integer constants are provided in Java
    _A:Binary consists of 0,1. Begins with 0b (zero).
    _B:Octal consists of 0, 1,... 7. Begins with 0.
    C: Decimal is composed of 0, 1,... 9. Integers default to decimal.
    D: Hexadecimal is composed of 0, 1,... 9, a, b, c, d, e, f (both case-sensitive). Begins with 0x.

1.6 Variables (Master)

  1. The amount by which a program's value can change in a range during execution
  2. Definition format for variables:
A:Data type variable name = initialize value;
B:Data type variable name;
  Variable Name = initialize value;
  1. There are several main types of variables in Java
    Local variable: A variable defined in a method, construction method, or statement block is called a local variable. Variable declaration and initialization are in the method, and the variable is destroyed automatically after the method is completed.
    Member variables: Member variables are variables that are defined in a class, outside the body of a method. These variables are instantiated when an object is created. Member variables can be accessed by methods, constructors, and statement blocks in a class.
    Class variables: Class variables are also declared in the class, outside the method body, but must be declared as static type.

1.7 Data Types (Master)

Variables are requests for memory to store values. That is, when you create a variable, you need to request space in memory.
The memory management system allocates storage space for a variable based on its type, which can only be used to store that type of data.

Therefore, by defining different types of variables, you can store integers, decimals, or characters in memory.
Two main data types for Java:

Built-in data types
Reference data type

1.7.1 Built-in Data Types

Java is a strongly typed language that provides a corresponding data type for each type of data.
The Java language provides eight basic types.
There are six numeric types (four integers, two floats), one character type, and one Boolean type.

  1. byte(1):

The byte data type is an 8-bit, signed integer represented by a binary complement.
The minimum value is -128 (-2^7);
The maximum value is 127 (2^7-1);
The default value is 0;
The byte type is used in large arrays to save space, mainly instead of integers, because the byte variable takes up only a quarter of the space of the int type.
Examples: byte a = 100, byte b = -50.

  1. short(2):

The short data type is a 16-bit, signed integer in binary complement
The minimum value is -32768 (-2^15);
The maximum value is 32767 (2^15 - 1);
Short data types can also save as much space as byte. A short variable is half the space occupied by an int variable;
The default value is 0;
Example: short s = 1000, short r = -20000.

  1. int(4):

The int data type is a 32-bit signed integer represented by a binary complement.
The minimum value is -2,147,483,648 (-2^31);
The maximum is 2,147,483,647 (2^31-1);
Generally, integer variables default to int type;
The default value is 0;
Examples: int a = 100000, int b = -200000.

  1. long(8):

The long data type is a 64-bit signed integer represented by a binary complement.
The minimum value is -9,223,372,036,854,775,808 (-2^63);
The maximum is 9,223,372,036,854,775,807 (2^63-1);
This type is mainly used on systems that require larger integers;
The default value is 0L;
Example: long a = 100000L, Long b = -200000L.
"L" is theoretically case-insensitive, but if written as "l", it is easy to confuse with the number "1", and it is not easy to distinguish. So it is best to capitalize.

  1. float(4):

The float data type is a single-precision, 32-bit floating point number that meets the IEEE 754 standard.
float saves memory space when storing large floating-point arrays;
The default value is 0.0f;
Floating-point numbers cannot be used to represent precise values, such as currency;
Example: float f1 = 234.5f.

  1. double(8):

The double data type is a double-precision, 64-bit, floating-point number that meets the IEEE 754 standard.
The default type of floating point number is the double type.
The double type also does not represent an exact value, such as currency;
The default value is 0.0d;
double d1 = 7D ;
double d2 = 7.;
double d3 = 8.0;
double d4 = 8.D;
double d5 = 12.9867;
7 is an int literal quantity, while 7D, 7.And 8.0 are double literals.

  1. boolean:

The boolean data type represents one bit of information;
There are only two values: true and false;
This type only serves as a flag to record true/false situations;
The default value is false;
Example: boolean one = true.

  1. char(2):

The char type is a single 16-bit Unicode character;
The minimum value is \u0000 (decimal equivalent is 0);
The maximum value is \uffff (that is, 65535);
char data types can store any character;
Example: char letter ='A';.

1.7.2 Reference Types

  • In Java, variables of reference types are very similar to C/C++ pointers. Reference types point to an object, and variables that point to an object are reference variables. These variables are declared with a specific type, such as Employee, Puppy, etc. Once declared, the type cannot be changed.
  • Objects and arrays are reference data types.
  • The default value for all reference types is null.
  • A reference variable can be used to reference any compatible type.
    Example: Site site = new Site("Runoob").

1.8 Data Type Conversion (Master)

  1. boolean type does not participate in conversion
  2. Default Conversion
    _A: From Small to Large
       B:byte,short,char – int – long – float – double
    _C:byte,short,char are not converted to each other. They are directly converted to int type to participate in the operation.
  3. Cast
    _A: From Big to Small
    _B: There may be loss of precision, which is not generally recommended.
    _C: Format:
    Target data type variable name = (Target data type) (Converted data);
  4. Think and interview questions:
    A re there any differences between the following two ways?
          float f1 = 12.345f;
          float f2 = (float)12.345;
    _B: Are there any problems with the following program, if so, where?
          byte b1 = 3;
          byte b2 = 4;
          byte b3 = b1 + b2;
           byte b4 = 3 + 4;
    _C: What is the result of the following operation?
          byte b = (byte)130;
    _D: Characters participate in operations
    _is to find values in ASCII
		'a'		97
		'A'		65
		'0'		48	
		System.out.println('a' + 1);

_E: Strings participate in operations
_This is actually a connection of strings

System.out.println("hello"+'a'+1);			System.out.println('a'+1+"hello");

1.9 Source File Declaration Rules

At the end of this section, we'll learn the declaration rules for source files. When defining multiple classes in a source file, as well as import and package statements, pay special attention to these rules.

  1. Only one public class can exist in a source file
  2. A source file can have more than one non-public class
  3. The name of the source file should be the same as the class name of the public class. For example, if the class name of the public class in the source file is Employee, then the source file should be named
  4. If a class is defined in a package, the package statement should be in the first line of the source file.
  5. If the source file contains import statements, it should be placed between the package statement and the class definition
  6. If there is no package statement, the import statement should be at the top of the source file.
  7. The import and package statements are valid for all classes defined in the source file. You cannot declare different packages for different classes in the same source file.
  8. Classes have several access levels, and classes are divided into different types: abstract class and final class. These are described in the Access Control chapter.

In addition to the types mentioned above, Java also has special classes, such as internal classes, anonymous classes.

2 Operator

2.1 Operator (Master)

  1. Arithmetic Operators
    A:+ - * / % ++ --
    Usage of B:+
    Difference between C:/and%
    Usage of D:++ and--
    _a: Their role is self-increasing or self-decreasing
    _b: Use
    Use separately
    Placing_in front of the operational data has the same effect as the latter.
    _a++ or +a have the same effect.
    Participate in operation use
    Place_in front of the operands: increase or decrease first, then participate in the operation
					int a = 10;
					int b = ++a;

Place after the operand: participate in the operation first, then increase or decrease by itself

					int a = 10;
					int b = a++;
  1. Assignment Operators
    A:=, +=, -=, *=, /=,%=etc.
    B:=is called assignment operator and is also the most basic assignment operator
    int x = 10;Assign 10 to the variable X of type int.
    C: Features of Extended Assignment Operators
    Automatic cast is implied.

     	Interview questions:
     		short s = 1;
     		s = s + 1;
     		short s = 1;
     		s += 1;
     		What's wrong with the code above??
  2. Comparison operator
    B: Whether the operators are simple or complex at both ends, the end result is a boolean type.
    C:Never write==as=

  3. Logical operators
    B: A logical operator used to connect boolean-type formulas
    &: false with false
    |: true if true
    ^: The same is false, the different is true.
    Couple relationship.
    !:Non-true false, non-false true

     	&&:Results and&It's the same, but with short circuit effect. To the left is false,Not on the right.
     	||:Results and|It's the same, but with short circuit effect. To the left is true,Not on the right.
  4. Bit Operators (Understanding)
    Special Use of A:^
    One data is exclusive to another data bit or twice, the number is not changed
    B: Interview Questions
    a:Please exchange the two variables
    ** Use third-party variables
    ** Using Bitwise XOR Operators
    Left a,b,a
    a^b on the right
    b: Use the most efficient way to calculate the result of multiplying 2 by 8

  5. Ternary operator
    Compare expressions? Expression 1: Expression 2;
    B: Execution process:
    First calculate the value of the comparison expression to see if it is true or false.
    If true, expression 1 is the result.
    If false, expression 2 is the result.
    C: Case:
    a: Compare whether two data are equal
    b: Get the maximum value in two data
    c:Get the maximum value in three data

2.2 Keyboard Input (Master)

  1. In the actual development, the data is changing. To improve the flexibility of the program, we add keyboard to input data.
  2. How? Now remember
	A:Guide Pack
		import java.util.Scanner;
		Location: In class Top
	B:create object
		Scanner sc = new Scanner(;
	C:get data
		int x = sc.nextInt();

2.3 Process Control Statements

(1) Sequential structure is executed from top to bottom
(2) Selection structure executes different codes according to different selection
(3) The loop structure does some duplicate code

2.4.1 if statement (master)

  1. Three formats
A:Format 1
			if(Comparison expression) {
				Statement Body;
Execution process:
			Judge the value of the comparison expression, see Yes true still false
			If it is true,Execute statement body
			If it is false,Do not execute statement body
B:Format 2
		if(Comparison expression) {
			Statement body 1;
		}else {
			Statement body 2;
Execution process:
			Judge the value of the comparison expression, see Yes true still false
			If it is true,Execute statement body 1
			If it is false,Execute statement body 2
C:Format 3
		if(Comparison expression 1) {
			Statement body 1;
		}else if(Comparison Expression 2){
			Statement body 2;
		else {
			Statement Body n+1;
Execution process:
			Judge the value of comparison expression 1, see Yes true still false
			If it is true,Execute statement body 1
			If it is false,Continue to evaluate the value of comparison expression 2, see Yes true still false
			If it is true,Execute statement body 2
			If it is false,Continue to evaluate the value of comparison expression 3, see Yes true still false
			If none of them is satisfied, execute the statement body n+1
  1. Matters needing attention
    A: Comparing expressions, simple or complex, results in boolean type
    The braces can be omitted if the body of the statement controlled by the B:if statement is a single statement, and cannot be omitted if there are multiple statements.
    Suggestion: Never omit.
    C: Generally speaking, if there is a left brace, there will be no semicolon, if there is a semicolon, there will be no left brace.
    If there is no if after D:else, no comparison expression will appear.
    E: All three if statements are actually one statement. As long as one is executed, the others are not executed.

3 Branch Statement

3.1 switch statement (master)

  1. Format:
switch(Expression) {
		case Value 1:
			Statement body 1;
		case Value 2:
			Statement body 2;
			Statement Body n+1;
 Format explanation:
		switch:Explain that this is switch Sentence.
		Expression:Can be byte,short,int,char
			   JDK5 It can be an enumeration later
			   JDK7 Can be a string later
		case:The next value is the value to compare with the expression
		break:Indicates that the program is interrupted here, jumping out switch Sentence
		default:If everything doesn't match,Execute here,Amount to if In statement else
  1. Interview Questions
    Can the switch statement be byte, long, or String?
    Yes, no, after JDK7
  2. Matters needing attention
	A:case It can only be a constant, not a variable, and more than one case The following values cannot be the same
	B:default Can I omit it??
		It can be omitted, but it is not recommended because it serves to alert you to incorrect situations.
		Exceptional case:
				case You can fix the value.
	C:break Can I omit it??
		It can be omitted, but the result may not be what we want.
		A phenomenon occurs: case Pierce through.
		Ultimately, we recommend not omitting
	D:default Must it be at the end?
		No, it can be anywhere. But it's recommended at the end.
	E:switch End condition of statement
		a:encounter break That's it.
		b:Execution ends at the end

3.2 Loop statement (master)

  1. There are three types: for,while,do...
  2. for loop statement
			for(Initialization statement;Judgment Conditional Statement;Control condition statement){
				Loop body statement;
	Execution process:
			a:Execute Initialization Statement
			b:Execute the judgement statement
				If this is true,Continue
				If this is false,Loop ends
			c:Execute Loop Body Statement
			d:Execute control condition statement
			e:Go back to b
	B:Matters needing attention
		a:Whether a conditional statement is simple or complex, the result is boolean type
		b:If a loop statement is one, curly braces may be omitted, but not recommended
		c:No left brace with semicolon, no semicolon with left brace
  1. while Loop
A:Basic Format
while(Judgment Conditional Statement) {
		Loop body statement;

Extended format:

Initialization statement;
		while(Judgment Conditional Statement){
			Loop body statement;
			Control condition statement;
  1. do...while loop
A:Basic Format
		do {
			Loop body statement;
		}while(Judgment Conditional Statement);

Extended format:

Initialization statement;
		do {
			Loop body statement;
			Control condition statement;
		}while(Judgment Conditional Statement);
  1. Recycling considerations (dead cycle)
    A: Always pay attention to modifying the control conditions, otherwise, it is prone to deadlock.
    B: The simplest dead-loop format

3.3 Control Jump Statements (Master)

  1. Break: Meaning of break

A: Used in loops and switch statements, it makes no sense to leave this application scenario.
B: Role:
_a: Jump out of single layer cycle
_b: Jump out of the multi-layer cycle, need the combination of label statements

  1. continue:
    A: Used in loops, leaving this application scenario is meaningless.
    _a: Jump out of one single-layer cycle once and continue for the next time
  2. return:
    A: For the end method, we will continue to explain and use it later.
    B: Once a return is encountered, the program will not continue to execute later.

3.4 for-each loop

Syntax simplification for array traversal and set iteration traversal

3.5 random

4 methods (similar to functions, master)

4.1 Method Meaning

Is the block of code that completes a specific function.
Note: Functions are defined in many languages, and in Java, functions are called methods.

4.2 Format:

Modifier Return Value Type Method Name(Parameter type parameter name 1,Parameter type parameter name 2...) {
			Method body statement;
			return Return value;

Modifier: public static is now used. Other modifiers will be explained in more detail later
Return value type: is the data type of the function result
Method Name: Just give us a name to call this method.
Parameter type: is the data type of the parameter
Parameter name: is the variable
Parameter classification:
_Arguments: Data actually participating in the operation
_Formal parameter: A variable defined on a method that receives an actual parameter
Method body statement: is the code block that completes the function
return: end method
return value: is the result of the function, returned to the caller.

4.3 Two definitions

Return value type: The data type of the result
Parameter List: Number of parameters and corresponding data types

4.4 Method Calls

	A:Methods with explicit return values
		a:Called individually, meaningless
		b:Output call, which is not very good, because I may need to do something further without the result. But I usually use it for the lecture.
		c:Assignment call, recommended scenario
	B:void Method of Type Modification
		a:Call individually

4.5 Cases

	A:Summation scheme
	B:Get the larger of two numbers
	C:Compare whether two data are identical
	D:Get the maximum of three numbers
	E:output m That's ok n Star of Column
	F:output nn Multiplication table

Notes on 4.6 Method

	A:Method call does not execute
	B:There is a horizontal relationship between methods and definitions cannot be nested
	C:When a method is defined, parameters are separated by
	D:Method is called without passing a data type
	E:If the method has an explicit return value type, it must have return Statement returned.

4.7 Method overload

	In the same class, the method name is the same and the parameter list is different. It is not related to the return value.
	Parameter lists are different:
		The number of parameters is different.
		Parameters have different data types.

4.8 Method overload cases

	Comparison of multiple methods with the same name of different types.

5 Arrays (Master)

5.1 Array

A container for storing multiple elements of the same data type.

5.2 Features

Each element has a number, starting at 0 and the maximum number is length-1.
Professional nomenclature for numbering: index

5.3 Definition Format

	A:data type[] Array name;
	B:Data type array name[];
	Recommendation is A mode
	But to understand

Initialization of 5.4 Arrays

	A:dynamic initialization
		Length only, default value given
		Give an example: int[] arr = new int[3];
	B:initiate static
		Given the value, the system determines the length
		Give an example: int[] arr = new int[]{1,2,3};
		Simplified version: int[] arr = {1,2,3};

5.5 Java Memory Allocation

	A:Stack stores local variables
	B:Heap Stores All new Out
	C:Method Area(A detailed explanation of the object-oriented section)
	D:Local Method Area(System correlation)
	E:register(CPU Use)

Be careful:
A: Local variable: A variable defined in a method definition or on a method declaration.
b: The difference between stack memory and stack memory
Stack: Once the data is used, it disappears.
Heap: Everything new comes out with an address
Each variable has a default value
byte,short,int,long     0
float,double          0.0
char                  '\u0000'
boolean               false
Reference Type_null
When the data is used up, recycle it when the garbage collector is idle.

5.6 Array Memory Graph

	A:An array
	B:Two Arrays
	C:Three Arrays(Two stack variables point to the same heap memory)

Common operations for 5.7 arrays

Mode 1:

public static void printArray(int[] arr) {
					for(int x=0; x<arr.length; x++) {

Mode 2:

public static void printArray(int[] arr) {
				for(int x=0; x<arr.length; x++) {
					if(x == arr.length-1) {
					}else {
						System.out.println(arr[x]+", ");

Maximum value:

public static int getMax(int[] arr) {
				int max = arr[0];
					for(int x=1; x<arr.length; x++) {
						if(arr[x] > max) {
							max = arr[x];
					return max;

Minimum value:

public static int getMin(int[] arr) {
					int min = arr[0];
					for(int x=1; x<arr.length; x++) {
						if(arr[x] < min) {
							min = arr[x];
					return min;

C:Reverse Order
Mode 1:

public static void reverse(int[] arr) {
					for(int x=0; x<arr.length/2; x++) {
						int temp = arr[x];
						arr[x] = arr[arr.length-1-x];
						arr[arr.length-1-x] = temp;

Mode 2:

public static void reverse(int[] arr) {
				for(int start=0,end=arr.length-1; start<=end; start++,end--) {
					int temp = arr[start];
					arr[start] = arr[end];
					arr[end] = temp;

D:Lookup table

public static String getString(String[] strArray,int index) {
				return strArray[index];

E:Basic Search
Mode 1:

public static int getIndex(int[] arr,int value) {
					for(int x=0; x<arr.length; x++) {
						if(arr[x] == value) {
							return x;
					return -1;

Mode 2:

public static int getIndex(int[] arr,int value) {
				int index = -1;
				for(int x=0; x<arr.length; x++) {
					if(arr[x] == value) {
						index = x;
				return index;

5.8 2-D Array (Understanding)

  1. Elements are arrays of one-dimensional arrays.
  2. Format:
    _A: Data type [][] array name= new data type [m][n];
    _B: Data type [][] array name= new data type [m][];
    _C: Array name of data type [][]= new data type [][]{...}, {...};
    _D: Data type [][] array name = {{...}, {...}, {...};
  3. Case (master):
    _A: Traversal of a two-dimensional array
    _B: Sum of two-dimensional arrays
    _C:Yang Hui Triangle

5.9 Array Supplementary Code

package 2-D Array;
    Two-dimensional array: An array whose elements are one-dimensional arrays
    Format 1:
           Data type [][] array name= new data type [m][n];
           m: Indicates how many one-dimensional arrays this two-dimensional array has.
           n: There are more than one element for each one-dimensional array
     Be careful:
        A:The following formats can also represent two-dimensional arrays (not recommended):
            a: Data type array name [][] = new data type [m][n];
            b: Data type [] array name [] = new data type [m][n];
        B: Note the differences defined below:
            int x,y;

            int[] x;
            int[] y[];

            int[] x, y[];

public class Array2Demo {
    public static void main(String[] args) {
        First Lesson:
        //Define a two-dimensional array
        int[][] arr = new int[3][2];
        //Defines a two-dimensional array arr
        //This two-dimensional array has three elements of a one-dimensional array
        //Each one-dimensional array has two elements
        //Name of output two-dimensional array
        System.out.println(arr);//Address value
        //The name of the first element of the output two-dimensional array One-dimensional array:
        System.out.println(arr[0]);//Address value
        System.out.println(arr[1]);//Address value
        System.out.println(arr[2]);//Address value
        //Elements of the output two-dimensional array:

        Lesson 2:
        //Define Array
        int[][] arr1 = new int[3][];
        //The first number must be given, the second can be given or not

        System.out.println(arr1[0]);//Null (why null because the one-dimensional loop of a two-dimensional array is undefined)
        //Dynamic space for each one-dimensional component
        arr1[0] = new int[2];
        arr1[1] = new int[2];
        arr1[2] = new int[2];


        //System.out.println(arr1[0][2]);//Cross-border error
        arr1[1][0] = 100;
        arr1[1][1] = 200;

        Lesson 3:
        Format 3:
            Basic format:
                Data type [][] array name= new data type [][]{{Element 1, Element 2...}, {Element 1, Element 2...}, {Element 1, Element 2...};
            Simplified Format:
                Data type [][] Array name = {{Element 1, Element 2...}, {Element 1, Element 2...}, {Element 1, Element 2...};
            Give an example:
                int[][] arr = {{1, 2, 3},{1, 2, 3},{1, 2, 3}};
                int[][] arr = {{1, 2, 3},{1 },{1, 2};
        int[][] arr2 = {{1, 2, 3}, {1}, {1, 2}};
        System.out.println("Lesson 3");


[[I@16b98e56([[: Two-dimensional array, type I:int)

5.10 java memory mechanism and memory address

Stacks and Stacks in 5.10.1 Java

Java divides memory into two types: stack memory and stack memory.
Some of the basic types of variables and reference variables defined in a function are allocated in the stack memory of the function.
When a variable is defined in a block of code, Java allocates memory space for the variable on the stack. When it exceeds the scope of the variable, Java automatically frees up the memory space allocated for the variable, which can be used for other purposes immediately.
Heap memory is used to store objects and arrays created by new.
Memory allocated in the heap is managed by the automatic garbage collector of the Java virtual machine.
After an array or object is generated in the stack, a special variable can also be defined in the stack so that the value of the variable on the stack is equal to the first address of the array or object in the stack memory, which becomes a reference variable to the array or object.
A reference variable is equivalent to a name given to an array or object that can then be used in a program to access the array or object in the stack.

Stacks and stacks are places where Java stores data in Ram. Unlike C++, Java automatically manages stacks and stacks, and programmers cannot set them directly.
Java heap is a runtime data area, class(Objects allocate space from them. These objects are built with directives such as new, newarray, anewarray, and multianewarray, and they do not require program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that it dynamically allocates memory size and does not have to tell the compiler beforehand about its lifetime, because it dynamically allocates memory at runtime and Java's garbage collectionAggregators automatically take away data that is no longer in use. The disadvantage is that access is slow because memory is allocated dynamically at run time.
The advantage of a stack is that it is faster to access than a stack, next only to registers, and stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly stores some basic types of variables (int, short, long, byte, float, double, boolean, char) and object handles.
An important particularity of stacks is that there is data in them that can be shared. Suppose we define both:

int a = 3;
int b = 3;

The compiler first processes int a = 3; first it creates a reference to a variable in the stack, then it looks for the value of 3 on the stack, if it cannot find it, stores 3, then points a to 3. Then it processes int b =3; After creating the reference variable for b, because there are already three values in the stack, point B directly to 3. This leads to a situation where a and B both point to 3. At this point, if a=4 is made again, the compiler will search again for 4 values in the stack, if not, store 4 and point a to 4; if there is already, point a directly to this address.A change in the value will not affect the value of B. Note that this sharing of data is different from referencing two objects that point to one object at the same time, because the modification of a does not affect B in this case.This is done by the compiler, which helps save space. An object reference variable modifies the internal state of this object and affects another object reference variable.

String Is a special kind of packaging data. You can use:
String str = new String("abc");
String str = "abc";

The first is to create a new object with new(), which is stored in the heap. A new object is created every time it is called.
The second is to create an object reference variable str to the String class in the stack first, and then look for "abc" in the stack. If not, put "abc" on the stack and make str point to "abc", and if there is already "abc", direct str to "abc".
Use the equals() method when comparing the equality of values within a class; use== when testing whether references to two wrapper classes point to the same object; the following example illustrates the above theory.
Mode 1:

String str1 = "abc";
String str2 = "abc";
System.out.println(str1==str2); //true

You can see that str1 and str2 point to the same object.

Mode 2:

String str1 =new String ("abc");
String str2 =new String ("abc");
System.out.println(str1==str2); // false

The new way is to generate different objects. One at a time.
So the first way to create multiple "abc" strings is to have only one object in memory.This is a good way to write and save memory space.At the same time, it can increase the speed of the program to some extent, because the JVM automatically determines whether it is necessary to create a new object based on the actual conditions of the data in the stack. For String str = new String("abc"); code creates new objects in the heap, regardless of whether their string values are equal or not, making it necessary to create new objects, thus increasing the burden on the program.
On the other hand, it is important to note that when we define a class using a format such as String str = "abc"; we always take it for granted that an object str of the String class has been created. Worry about traps! The object may not have been created! It may just point to an object that has been created previously. Only through new ()Method ensures that a new object is created each time. Because of the immutable nature of the String class, the String Buffer class should be considered to improve program efficiency when String variables need to frequently change their values.

Tags: Java

Posted on Tue, 21 Sep 2021 13:01:50 -0400 by Shaun