Home >Java >javaTutorial >How to use the new keyword in java

How to use the new keyword in java

王林
王林forward
2023-05-03 22:16:052925browse

1. Concept

In the Java language, the "new" expression is responsible for creating an instance, which will call the constructor to initialize the instance ;The return value type of the constructor itself is void, which does not mean that "the constructor returns a reference to the newly created object", but that the value of the new expression is a reference to the newly created object.

2.Purpose

New class object

3.Working mechanism

Allocate memory space for object members, and specify default values

Explicitly initialize member variables

Execute Construction method

Calculate and return reference value

4.Instance

new operation It often means opening up a new memory space in the memory. This memory space is allocated in the heap area in the memory and is controlled by the jvm and automatically manages the memory. Here we use the String class as an example.

public class Test {
    public static void main(String[] args) {
    	String aString = "hello";
    	String bString = new String("hello");
    	String cString = "hello" ;
    	String dString = new String("hello") ;
    	System.out.println(aString==bString);
    System.out.println(aString == cString);	
    System.out.println(dString == bString);	
    System.out.println(aString);
    aString = "hi" ;
    System.out.println(aString);
    }
    
}

The above is the detailed content of How to use the new keyword in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete