+ 2
we initialized x to 5 .. then we used the method addOneTo(x) that increments x by 1. The output stays 5 why????
the example is given in the lesson of java about reference types https://code.sololearn.com/cOcBwW97Ts8W/?ref=app
2 ответов
+ 13
//so many ppl asking same question , some keyword for it 😅
👉why its not working presently ?
reason 1)U didn't assigned increased value of x to x , thatswhy it remained 5
reason 2) x is not static variable its value didn't get changed with changes U made in its in value in some function
👉to make it work through method : [method 1]
step 1)do ... x=addOneTo(x); //instead of addOneTo(x);
step 2)change return type of function to int & use return keyword
//see code below
👉 here is the code :
public class MyClass {
public static void main(String[ ] args) {
int x = 5;
x = addOneTo(x);
//assigning increased value of x to x
System.out.println(x);
}
static int addOneTo(int num) {
return num = num + 1;
}
}
[method 2]
👉U can try making x as static variable , then u will no need to change return type of funcn. & assign value of x to x😅 , I am leaving it for U to try ...
+ 1
Java passes into methods by value, not by reference -- although objects are manipulated by reference. In order for your example to work, you would need to have the class you're working in as an instance.
AddByOne add = new AddByOne(5);
add.addOne(); //outputs 5
That would work because in the constructor you would set a private int that is accessible only to the instance and manipulate it from inside the object. However you can also add getter/setter to change or grab the variable externally.
https://www.sololearn.com/Discuss/472655/?ref=app
https://www.sololearn.com/Discuss/727678/?ref=app
https://www.sololearn.com/Discuss/1113635/?ref=app