简体   繁体   中英

Magic passing variable to parameter in Java

public class experiment3 {
    private static void mystery(String foo, String bar, String zazz) {
        System.out.println(zazz + " and " + foo + " like " + bar);
    }
    public static void main(String[] args) {
        String foo = "peanuts";
        String bar = "foo";
        mystery(bar, foo, "John");
    }
}

Can somebody explain to me how this result is formed when outputting it?

The output will be:

John and foo like peanuts

I understand that param. name zazz always is John;

I don't understand how the last 2 params. were formed?!

PS: Please help me to understand how this 2 last params were formed. If there is a possibility for a schematic representation for better understanding the way that java compiler works!

The Java compiler doesn't care about the names of the variables passed in as arguments of a method call as it pertains to the names of the parameters of the method that is called. Only the position of the values matters.

                             "foo"        "peanuts"
                               |               |   
                               v               v       
                    mystery(   bar    ,       foo , "John")
                               |               |       |
                               v               v       v
private static void mystery(String foo, String bar, String zazz)

The mixed order of variable names here serves no purpose here except to confuse.

zazz + " and " + foo + " like " + bar

becomes

John and foo like peanuts

When you're making the call to the 'mystery' method you give the params :

bar(="foo"), foo(="peanuts), "John".

the names of these variables have nothing to to with the way you declare the method, only their content, so, the method receives the params:

 foo(="foo"), bar(="peanuts"), zazz(="John")

I do not see any mystery in this code: you must follow the order of the arguments in the signature of your method and the order of the arguments to the call of this method.

If the same order had been respected in both directions with the same names of variables foo, bar and zazz; the output to the display would have been simply:

"john and peanuts like foo".

But because the order has been inverted, it is necessary to follow the position of each variable in the signature of the method to know the value that will be returned. So in the signature on:

foo = 1, bar = 2 and zazz = 3

But in the call we have:

bar = 1 and its value = foo
foo = 2 and its value = peanuts

the value of zazz = john from where the display

"john and foo like peanuts"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM