Java to pass a value or to pass a reference

Source: Internet
Author: User

This is a classic interview question, it confuses Java novice. In this article, I'll use an example and some diagrams to prove that Java is passed by value.

Definition:
-Pass by value: Make a copy of the actual parameter value in memory to pass.
-Pass Reference: a copy of the address that passes the actual parameter.

Java is always a value pass. Both the original data type and the object reference are just values.

Pass the original type variable:

swap(Type arg1, Type arg2) {    Type temp = arg1;    arg1 = arg2;    arg2 = temp;}

Passing objects:
Java refers to manipulating objects by reference, and all object variables are references. However, Java does not pass a parameter value by reference, but instead passes it by value.

The question is: why can the member values of an object be modified?

Code:

class Apple {public  String color= "red" ;} public  class  main  { Span class= "Hljs-keyword" >public  static  void  main  (string[] args) {Apple Apple = new  A        Pple ();        System.out.println (Apple.color);        Changeapple (Apple);    System.out.println (Apple.color); } public  static   void  changeapple  (Apple apple) {Apple.color =  "Gree    n "; }}

Because the original and copied references point to the same object, the value of the member variable can be modified.
Results:

redgreen

http://www.programcreek.com/2011/08/so-java-passes-object-by-reference-or-by-value/

Java to pass a value or to pass a reference

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.