+ 1
Please explain this program
public class MyClass { public static void main(String[ ] args) { int x = 5; addOneTo(x); System.out.println(x); } static void addOneTo(int num) { num = num + 1; } }
4 Réponses
+ 2
The code tries to tell you that variables of primitive datatypes such as int are passed by value in java. Which means, when you pass x with a value of 5 to addOneTo function, the function copies the value of x and put that copy into the num variable. So, if you try to change num inside the addOneTo function you're basically changing its own copy of the value not the original one of the x. hence, the x remains 5 as it is after calling addOneTo in the main.
+ 2
Value of x is pass to the function
addOneTo()
But function is void that not return value
It means
They not return any value after adding 5
Because of this
You got answer 5
+ 2
Please add return type in your function
+ 2
When the computer is running the program in main, is looking down at the first line below main, and sees a variable instance.
The next line invokes method addOneTo(x), which passes x as a parameter of addOneTo method. The value of num gets set to 6 in the method of addOneTo. But the method addOneTo does not have a return statement, neither have a system.out.print(num) statement.
In this case the method “addOneTo” is acting basically as a “setter” but without the conventional “set” name that is used, because is basically setting the value of num to x and add 1 to whatever x is.
However, as you can see thats all it does, add one to num. the computer remembers that information but cant do anything with it. Thats why num is never printed out, because the computer is lookng at the main method that invokes its, but once it is invoked the addOneTo does not have the instruction to print it out.
Then finally, the last line of the main method is to print x, which the value of x is 5.
Happy coding!