Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Passing Arguments to a method always ordered left to right in java?

I'll call a method with two arguments, but i'll use k++ like this:

polygon.addPoint((int)rs.getDouble( k++),(int)rs.getDouble( k++ ));

Actually i want to be sure that jvm executes first argument first, then the second one. If somehow the order will change, arguments would be passed wrong order.

Thanks a lot!

like image 330
Ismail Yavuz Avatar asked Mar 27 '14 15:03

Ismail Yavuz


People also ask

Does the order of Java arguments matter?

Answer. No, the order of query parameters should not matter.

How is an argument passed to a method in Java?

Arguments in Java are always passed-by-value. During method invocation, a copy of each argument, whether its a value or reference, is created in stack memory which is then passed to the method.

What happens when an argument is passed to a method?

When passing an argument by reference, the method gets a reference to the object. A reference to an object is the address of the object in memory. Now, the local variable within the method is referring to the same memory location as the variable within the caller.


2 Answers

Yes, the arguments are guaranteed to be evaluated left-to-right. Any compiler complying to JLS rules should follow that. This is mentioned in JLS §15.7.4:

In a method or constructor invocation or class instance creation expression, argument expressions may appear within the parentheses, separated by commas. Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

like image 60
Rohit Jain Avatar answered Oct 05 '22 22:10

Rohit Jain


Yes, Java guarantees that. However, this does not mean that using the code like that is a good idea: readers of your code may get thoroughly confused.

It is much cleaner to show the order explicitly:

int a = (int)rs.getDouble(k++);
int b = (int)rs.getDouble(k++);
polygon.addPoint(a, b);
like image 35
Sergey Kalinichenko Avatar answered Oct 05 '22 21:10

Sergey Kalinichenko