Introduction to Programming (Java) & #183; 3.3.2 by value transitive semantics

Source: Internet
Author: User

Don't be influenced by the idea of Java programming, the terminology in computer science- passed by reference (pass-by-reference). Do not make yourself a self-talk personal language.

These terms are also not specific to Java, and you should not learn from a Java Book special "Pass-by-reference" that cannot be used in C, C + +, or Fortran languages.

Verify that passing by value is easy. use an assignment statement in the method body to set the shape to the left value .

When passing by value, the assignment to the shape will not affect the actual participation. Other words. The assignment statement does not have any side effects whatsoever.

For Foo (a a), notice that in the method body you want to play a= new A () instead of playing with one thing. such as A. Change ().

This text seconds understand, "Introduction to Programming (Java) 3.3.2 by value transitive semantics" content can be skipped.

By defining a series of methods, the program can be decomposed into small modules, and the method invocation links them together. A formal parameter is specified when the method is defined, and the formal parameter is initialized by a given actual number of parameters when the method is called.

An important topic in message delivery is: How should the message count (actual participation) be passed to the method's formal participation? in a variety of programming languages. [1] There are many ways to pass the parameters. This is by the language of the designer and the implementation of the choice.

The frequently used parameters are passed by value (Pass-by-value) and by reference (pass-by-reference).

From the source of the parameter transfer mechanism, the C language is passed by value, and Fortran is passed by reference, while the C + + language uses both. The Java language, like the C language, uses a unique pass-through method: pass by value.

Two questions need to be considered in the mechanism of the number of parameters:

Initialization of the form.

Whether the manipulation of the shape in the method body has side effects on the actual participation.

1. Method call Stack

Passing by value means that when a method is called, the actual number of references (or expressions) is evaluated first (and the resulting value is copied). The copied value is then stored in the form parameter.

In short, passing by value is a copy of the actual number of parameters passed.

In principle (the method stack frame is explained in the [7.4 Execution-time storage management]), Java creates a new method frame each time the method is called.

formal parameters (whether basic or reference type variables) belong to their own method frames, and the space on which the values are stored is allocated on the stack.

The actual number of arguments (or expressions) can be either in the heap (the domain of the object) or in a method frame (there is also a local variable), and the two are independent . When passing by value, it is assumed that the method being called alters the value of the shape, only the copy is changed, and the original value (the actual participation) is unaffected.

Routine 3?13 method calls the package Oo;import static tips. print.*;p ublic class passbyvalue{    private void m (int x) {    x + =  5;  }    private int max (int a,int b) {  return (a>b? a:b);  }    public void Foo () {    ?  int i = 1,j the symbol before the =2;//code, representing the breakpoint        int max = max (i,j);         M (max);        I=max;}    }

Create an object and run its foo () method, Foo () run process, 3-6 see.

It reflects two points: (1) How a "larger code" breaks down into more small fragments (methods), and how these fragments form a large population--the hypothetical method m (int) and Max (Int,int) have very long, very long code.

(2) The running flow of the method call.

Figure 3?6 Method Invocation Process

Foo () Runs: (1) Initializes local variables I and J; (2) int max = max (i,j). The (return) value of the method Max (I,J) is first evaluated and then assigned to the local variable max.

In order to find the value of the method Max (I,J). The JVM creates a new method frame Max, which copies the values of the local variables I and J of the previous frame Foo and assigns them to the form, and Foo frames wait.

Max Run completion will return the 2,max frame to be ejected, 2 assigned to Max, and (3) run M (max). Creates a new frame m, which copies the value of 2 of the frame foo to the parameter x. M-Frame changes the value of x, though. However, the value of the actual participation is not affected.

Assuming that you are familiar with setting breakpoints in the BlueJ source editor when learning [2.3.4 creating objects], you can switch between two frames in the method frame call stack seen in 3-7 to see that the actual participation and the shape are assigned their own space in each frame.

Figure 3?7 switching between two frames

2. Only the Java language is passed by value

To learn how to pass the Java language, verify 3 scenarios:

(1) For the base type of the number of references. The action in the method body does not cause side effects.

(2) When a reference to an object is used as a parameter. Actual participation (references) will not change .

(3) However, the reference as the message receiver May have changed the content of the object it points to.

Package Oo;import tips. Fraction;import static tips. print.*;p ublic class passbyvalue{        /////////////////////////////////////as a reference. ////////private void change is still passed by value    (fraction frrr) {        frrr = new fraction (11,55);//note here.    }    private void Doubleit (fraction f) {        f.add (f);    }    public void Test () {        fraction f = new fraction (1,3);        P (f+ "");         Change (f);        PLN (f);        f = 1/3 Vs 1/5                fraction f2 = new fraction (1,3);        Fraction temp = new fraction (f2);        Doubleit (F2);        Doubleit (temp);        PLN (F2);    }    }

In the routines, the change (fraction) and Doubleit (fraction) methods take the fractional class variable as a form. Running the test () code shows that the assignment of change (fraction) to the shape of the parameter does not affect the actual participation. and Doubleit (fraction) invokes the method of the formal participation, which causes the content of the object (which is also the object to which it is actually directed) to change, thus producing side effects.

To avoid the possible side effects of a method call, you can use the following actions, for example:

2 The object that the reference points to belongs to the invariant class. An immutable class object (content) cannot be changed, such as a string.

2 clones an object and passes its reference to the method.

3. Negative negative positive

Sometimes two errors are put together and are correct in effect. A typical error example, "Objects in Java is passed by reference." There are two purposes for introducing this error: (1) to indicate what is passed by reference, and (2) to emphasize when a reference is a method parameter. The pass value still has side effects.

Passing by reference means that the form parameter of the method is not the alias of the actual argument--it does not pass its value but the address to the shape, and the two have the same data storage location. So whenever the method changes the value of the formal parameter. In fact, it also changed the value of the actual participation.

The reason that "objects in Java is passed by reference" is a negative error that comes from an easy, misleading word: objects are passed by reference (you're passing objects by reference). The intention is to say. Objects in Java are not passed, but are passed their references. But whether it is English or Chinese meaning, a little careless will be confused with pass-by-reference. The so-called negative positive, based on:

(1) objects can be passed. objects are not passed in Java . So this is wrong if. The root cause is because people often mix terminology. "Passing objects to methods" is a frequently used term, see [2.4.2 Reference variables, references, and objects].

(2) The formal participation and the actual participation have the same position.

Assume that both the shape and the actual participation are objects. Of course it's true. The problem is that the shape and the actual participation (not the object) is a reference, just as the left hand and the right hand point to the same moon, but the left hand is not the right hand, the left hand is not the right hand alias/nickname.

The effect is correct: You can change the object's content.

In short, the correct argument is that the object's reference is passed by value (object references is passed by value).

Exercise 3-1: Someone might say, "objects are passed by reference." A reference to passing by value "is too much of a word, and there is no" object passing by reference "to be crisp. How do you answer?

Exercise 3-2: Why say "basic types are passed by value and references are passed by reference" is an error.

Exercise 3-3: What delivery mechanisms should be used to pass serialized objects in a network program? Hint: Pass the reference semantics.


[1] http://www.yoda.arachsys.com/java/passing.html, the semantics of various parameters passed, the purpose of passing by reference.

Introduction to Programming (Java) & #183; 3.3.2 by value transitive semantics

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.