Questo concetto mi rimane oscuro![]()
Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Here is an example:
When you run this program, the output is:codice:public class PassPrimitiveByValue { public static void main(String[] args) { int x = 3; // invoke passMethod() with // x as argument passMethod(x); // print x to see if its // value has changed System.out.println("After invoking passMethod, x = " + x); } // change parameter in passMethod() public static void passMethod(int p) { p = 10; } }
After invoking passMethod, x = 3
Non riesco a capire il razionale di questa cosa.
Ho anche questo esempio:
codice:class Parametri { static void inc(int x) { x++; } public static void main (String[] args) { int y=0; inc(y); System.out.println(y); //ritorna 0 } }Perché il primo non funziona e il secondo sì??codice:class Parametri { static int inc(int x) { x=x+1; return x; } public static void main (String[] args) { int y=0; y=inc(y); System.out.println(y); //ritorna 1 } }
Sarò tonta ma non ci arrivo proprio, se qualcuno ha voglia di farmi capire questa cosa, gliene sono grata.

Rispondi quotando