Java pass by reference and compiler optimization

江枫思渺然 提交于 2019-12-02 10:13:35

Java is pass by value. If you assign a new value to the argument, it won't affect the value in the caller method.

You have two options:

  • make your method return a and b - either in a int[] or using a separate FactorizationRezult class that has two fields. That way you will declare a and b as local variables in your called method, rather than taking them as parameters. This is the most advisable approach.

  • An alternative approach is to use a MutableLong and use a setValue(..) method - that way the changes will affect the object in the caller method. This is less advisable

a and b are references, not 'reference parameters', and they are passed by value. The values are changed in the called method but that has no effect on the caller.

There is no 'pass by reference' in Java.

In Java, everything is passed by value. There is no call-by-reference. Even when you pass an Object, it's reference is passed by value. So, when you pass a Long object, you are simply passing the reference to it by value.

Long, just like other primitive type wrappers, is "immutable". You can't change the long value it has inside. So, if you don't want to change your design, you have to make a mutable wrapper for long yourself (or use MutableLong) and pass it on. Changing your design to return the results instead of changing the method arguments is a much better way if you ask me.

Using the = operator clears out the spot in the memory where the local variable is stored and replaces it. This will not affect the original variable. Pass by value only allows you to modify data in in object (like modifying a field in it), not it's actual reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!