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!

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor
