java - Still unsure as to why this integer remains unmodified -


this question has answer here:

i learning references , datatypes in java , particular code still confusing me. understand of primitive types in java value types (byte, short, int, long, float, double, boolean, char), , when you're using string or object it's reference type. when taught declare , initialize variable, told think of creating box. if create variable "y" , give value of "5" it's i've created box called "y" contained value of 5. teacher said if try call y in method (check out code below more detail) value remain untouched because it's primitive datatype i'm passing in 5, not variable contains 5. i'm confused because if i'm passing in value of 5, why wouldn't following method add 1 onto it.

public class referenceandvaluetypes {     public static void main(string[] args) {          int y = 5;         addoneto(y);          system.out.println(y);      }       static void addoneto(int number){         number = number + 1;     } } 

the output 5 , confuses me greatly. teacher says it's because int value type we're not passing y variable in, , we're not operating on variable rather value of variable. however, value of variable 5 , since method adds one, shouldn't 6? or, because y value type, method cannot work has print out initial value of y 5?

java primitives (int, long, boolean, etc) not references, they're actual values. when have addoneto(y);, addoneto receives copy of value. copied value incremented one, , lost when method exits.

as analogy, when see primitive method parameter can think of photocopier. in contrast, object reference same passing notepad written on it. method see same object, not copy of it, , changes made present after method exits.

changing name of parameter can make little clearer

static void addoneto(int numbera) {  // numbera not same int in calling method, it's exact copy of     numbera = numbera + 1; // numbera incremented 1     // method exits, numbera lost } 

if want have method provides increment functionality, can define 1 returns result.

public static void main(string[] args) {     int x = 3;     addoneto(x); // x still 3     x = addoneto(x); x 4 }  static int addoneto(int number) {     return number + 1; } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -