Analyze the concept of reference types in java
1. What is a reference type?
A reference type points to an object, not a primitive value. The variable pointing to the object is a reference variable.
In java, other types except basic data types are reference data types. The classes you define are reference types and can be used like basic types.
Examples are as follows:
public class MyDate { private int day = 8; private int month = 8; private int year = 2008; private MyDate(int day, int month, int year){...} public void print(){...} } public class TestMyDate { public static void main(String args[]) { //这个today变量就是一个引用类型的变量 MyDate today = new MyDate(23, 7, 2008); } }
2. Assignment of reference types
In the java programming language, it is declared with a type of the class The variable is designated as a reference type because it is referencing a non-primitive type, which has important implications for assignment. The following code:
int x = 7; int y = x; String s = "Hello"; String t = s;
Four variables are created: two primitive types int and two reference types String. The value of x is 7, and this value is copied to y; x and y are two independent variables and further changes in either have no effect on the other. As for the variables s and t, only one String object exists, which contains the text "Hello", and both s and t refer to this single object.
If the variable t is redefined as t="World"; then a new object World is created, and t refers to this object.
3. The difference between passing by value and passing by reference
1) Passing by value
means that when the method is called, the parameters passed are passed by copy of the value. An example is as follows:
public class TempTest { private void test1(int a) { // 做点事情 a++; } public static void main(String args[]) { TempTest t = new TempTest(); int a = 3; t.test1(a);//这里传递的参数a就是按值传递。 System.out.printIn("main方法中的a===" + a); } }
The important feature of passing by value: what is passed is a copy of the value, which means that they are irrelevant after passing. A in line 9 and a in line 2 are two variables. When the value of a in line 2 is changed, the value of a in line 9 remains unchanged, so the printed result is 3.
The a in the main method is 3
The a in the test1 method is 4
We call the a in line 9 an actual parameter, and the a in line 2 called a formal parameter; for basic data Changes in type and formal parameter data do not affect the actual parameter data.
2) Passing by reference
means that when the method is called, the parameters passed are passed by reference. In fact, what is passed is the address of the reference, which is the memory space corresponding to the variable. the address of.
Examples are as follows:
public class TempTest { private void test1(A a) { a.age = 20; System.out.printIn("test1方法中的age="+a.age); } public static void main(String args[]) { TempTest t = new TempTest(); A a = new A(); a.age = 10; t.test1(a);// 这里传递的参数a就是按引用传递 System.out.printIn("main方法中的age="+a.age); } } classA { public int age = 0; }
The running results are as follows: age = 20 in test1 method age = 20 in main method
Important features of passing by reference:
What is passed is The reference of the value, that is to say, both before and after the transfer point to the same reference (that is, the same memory space).
If you want to correctly understand the process of passing by reference, you must learn to understand the process of memory allocation. The memory allocation diagram can help us understand this process.
Use the above example to analyze:
(1) Start running, run line 8, create an instance of A, the memory allocation diagram is as follows:
A in the main method
(2), run line 9, modify the age value in the A instance, the memory allocation diagram is as follows:
a in the main method
(3) Run line 10, which transfers the memory space address referenced by variable a in the main method to the a variable in the test1 method by reference. Please note: these two a variables are completely different, don't be fooled by the same name, but they point to the same A instance. The memory allocation diagram is as follows:
此时A实例的age值的变化是由test1方法引起的。
(5)、运行第4行,根据此时的内存示意图,输出test1方法中的age=20
(6)、运行第11行,根据此时的内存示意图,输出main方法中的age=20
3)对上述例子的改变
理解了上面的例子,可能有人会问,那么能不能让按照引用传递的值,相互不影响呢?就是test1方法里面的修改不影响到main方法里面的呢?
方法是在test1方法里面新new一个实例就可以了。改变成下面的例子,其中第3行为新加的:
public class TempTest { private void test1(A a) { a = new A();// 新加的一行 a.age = 20; System.out.printIn("test1方法中的age="+a.age); } public static void main(String args[]) { TempTest t = new TempTest(); A a = new A(); a.age = 10; t.test1(a);// 这里传递的参数a就是按引用传递 System.out.printIn("main方法中的age="+a.age); } } classA { public int age = 0; }
运行结果为:test1方法中的age=20 main方法中的age=10
实现了按引用传递的值传递前与传递后互不影响,还是使用内存示意图来理解一下:
(1)、运行开始,运行第9行,创建了一个A实例,内存分配示意图如下:
(2)、运行第10行,是修改A实例里面的age的值,运行后内存分配示意图如下:
(3)、运行第11行,是把mian方法中的变量a所引用的内存地址,按引用传递给test1方法中的a变量。请注意:这两个a变量是完全不同的,不要被名称相同所蒙蔽。
(4)、运行第3行,为test1方法中的变量a重新生成了新的A实例,完成后形成的新的内存示意图如下:
(5)、运行第4行,为test1方法中的变量a指向的新的A实例的age进行赋值,完成后形成新的内存示意图如下:
注意:这个时候test1方法中的变量a的age被改变,而main方法中的a变量是没有改变的。
(6)、运行第5行,根据此时的内存示意图,输出test1方法中的age=20
(7)、运行第12行,根据此时的内存示意图,输出main方法中的age=10
说明:
(1)、“在Java里面参数传递都是按值传递”这句话的意思是:按值传递是传递的值的拷贝,按引用传递其实传递的是引用的地址值,所以统称按值传递。
(2)、在Java里面只有基本类型和按照下面这种定义方式的String是按值传递,其它的都是按引用传递。就是直接使用双引号定义的字符串方式:String str = "Java快车";
相关文章:
The above is the detailed content of Analyze the concept of reference types in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
