+ 1

WHY output is 6, 5 instead of 5,6. How the value 5 assigned to num? For below code.

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; System.out.println(num); } }

10th Nov 2019, 8:26 PM
Tejas
Tejas - avatar
3 Respostas
+ 4
Important: void addOneTo() does not return a value. The method gets a value, increment it and print it. This has no effect to your variable x. x = 5 then you call addOneTo(5) num = 5 + 1 = 6 print num -> print 6 After that you jump back to your main method: print x -> x is still 5, so print 5 Output: 6 5 If you want a method which changes x: public static int addOneTo(int num){ return num + 1; } inside main: int x = 5; x = addOneTo(x); System.out.println(x); Output: 6
10th Nov 2019, 8:35 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
The code will display the content in the order its compiled so int x = 5; //x equals 5 addOneTo(x)// grab a copy of the value of x above me and send it over to that method outside the main method, add one to it and print 6 to console once your done come back and finish executing the code in the main method System.out.println(x)// since only a copy was sent to the addOneto method then x still remains being the value of 5 so 5 is printed to console. 6 5 is printed to console Denise Roßberg explained this very well already
10th Nov 2019, 10:57 PM
D_Stark
D_Stark - avatar