Reference passing and value passing of parameters in Java

Source: Internet
Author: User

1. Some definitions

Value passing: Assigns the value of the actual passed-in parameter to a copy in memory

Reference passing: The address of the actual parameter passed in

2. Pass the parameters of the basic type

Because Java is a value pass, it is not difficult to understand that the following code does not exchange any values

Swap (type arg1, type arg2) {    = arg1;     = arg2;     = temp;}

3. Parameters for passing reference variables

Java uses references to manipulate objects, and all variables that point to the object are references, however, Java does not pass the reference to the parameter of the method, but rather to the value of the reference;

So why can the member values of an object be changed?

Class Apple {public String color= ' Red ', ' public ' class main {public static void main (string[] args) {Apple Apple = new APPL E (); System.out.println (Apple.color); Changeapple (Apple); System.out.println (Apple.color);} public static void Changeapple (Apple apple) {Apple.color = "green";}}

Because both the original and the assignment references point to the same object, the value of the member is changed

Output:

1 Red 2 Green

Reference passing and value passing of parameters in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.