I am developing a Java application, and now I have noticed strange behavior that confused me. I have the following situation:
Integer currentIndex = 0; doSomethings(currentIndex); System.out.println("Print "+currentIndex); private void doSomethings(Integer currentIndex){ //Do other things and update my current index currentIndex++; }
but always get the value 0. I remember that objects are passed as a reference in java, while primitive types are like copying. Why in this case do I get 0?
Integer . , . , Integer int ( "unboxing" ), int . Integer. Integer, , . .
Integer
int
-:
private static void doSomethings(java.lang.Integer); Code: Stack=2, Locals=1, Args_size=1 0: aload_0 1: invokevirtual #56; //Method java/lang/Integer.intValue:()I --> get the int value of the Integer 4: iconst_1 --> constant value 1 5: iadd --> add int value and 1 6: invokestatic #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/In --> get another integer with value increased by 1 teger; 9: astore_0 10: return
.
, Java . ++ Java-.
, java , "auto boxing". Integer int .
, :
Interger myInt = 0; int i = myInt++; // this line
: myInt int, int i. , myInt.
myInt
i
, , ++ , Integer . , Integer , .
++
, beworker . .
Java . , , currentIndex, , currentIndex dosomething() .
currentIndex
dosomething()
. , Eng.Fouad , .
Java . ( ). , Integer . , .
, , , .
private Integer doSomethings(Integer currentIndex){ return currentIndex++; }
currentIndex = doSomethings(currentIndex); private Integer doSomethings(Integer currentIndex){ //Do other things and update my current index return currentIndex++; }
Integer currentIndex = 0; currentIndex = doSomethings(currentIndex); System.out.println("Print "+currentIndex); private Integer doSomethings(Integer currentIndex,){ //Do other things and update my current index return currentIndex++;
doSomethings () increments the value of currentIndex and returns it. Then save this object in currentIndex link
Good luck !!!
Java is passed by value, these two articles explain well
http://www.javaranch.com/campfire/StoryCups.jsp http://www.javaranch.com/campfire/StoryPassBy.jsp
Read in that order.