官术网_书友最值得收藏!

Argument passing

In Java, arguments are passed by value. When the method modifies an argument variable, then only the copy of the original value is modified. Any primitive value is copied during the method call. When an object is passed as an argument, then the copy of the reference to the object is passed.

That way, the object is available to be modified for the method. In the case of classes that have their primitive counterpart, and also in the case of String and some other class types, the objects simply do not provide methods or fields to modify the state. This is important for the integrity of the language, and to not get into trouble when objects and primitive values automatically get converted.

In other cases, when the object is modifiable, the method can effectively work on the very object it was passed to. This is also the way the sort method in our example works on the array. The same array, which is also an object itself, is modified.

This argument passing is much simpler than it is in other languages. Other languages let the developer mix the pass by reference and the pass by value argument passing. In Java, when you use a variable by itself as an expression to pass a parameter to a method, you can be sure that the variable itself is never modified. The object it refers to, however, in case it is mutable, may be modified.

An object is mutable if it can be modified, altering the value of some of its field directly or via some method call. When a class is designed in a way that there is no normal way to modify the state of the object after the creation of the object, the object is immutable. The classes Byte, Short, Integer, Long, Float, Double, Boolean, Character, as well as String, are designed in the JDK so that the objects are immutable.
It is possible to overcome the limitation of immutability implementation of certain classes using reflection, but doing that is hacking and not professional coding. Doing that can be done for one single purpose—getting a better knowledge and understanding of the inner workings of some Java classes, but nothing else.

主站蜘蛛池模板: 荆门市| 庄河市| 聂拉木县| 宁武县| 卢氏县| 丽江市| 孝义市| 化德县| 武邑县| 丰台区| 二连浩特市| 巴南区| 蓬莱市| 双牌县| 上饶市| 永安市| 津南区| 安西县| 哈巴河县| 都兰县| 赫章县| 合江县| 天长市| 绵阳市| 鹿泉市| 新乡市| 江孜县| 舒城县| 仙游县| 永昌县| 金秀| 任丘市| 伊金霍洛旗| 满城县| 上犹县| 普宁市| 乌拉特前旗| 汤阴县| 绍兴县| 无为县| 酉阳|