+ 1

Someone explain this in simple way ..y the answer is 5 not 6?

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; } }

20th Sep 2017, 4:19 AM
karthik
karthik - avatar
10 Respostas
+ 2
wait what was that john??? u r using * and & in java?? java has no such conventions -_- -_-
20th Sep 2017, 1:18 PM
sayan chandra
sayan chandra - avatar
+ 2
it will work in c++ right ?
20th Sep 2017, 1:55 PM
karthik
karthik - avatar
+ 1
public class MyClass { public static void main(String[ ] args) { int x = 5; int c; c=addOneTo(x); System.out.println(c); } static int addOneTo(int num) { num = num + 1; return num; } } addoneTo function needs to return the incrememted value... else num the change of x wont occur in main func... if u want to do in either u need to tae x as global var..
20th Sep 2017, 4:26 AM
sayan chandra
sayan chandra - avatar
+ 1
Pointers are not supported in Java, so @John's Idea won't work.
20th Sep 2017, 12:36 PM
Jonas Schröter
Jonas Schröter - avatar
+ 1
ya cpp has pointer... that ans has been marked as best ans...đŸ˜šđŸ˜šđŸ˜”đŸ˜”OMG
20th Sep 2017, 1:57 PM
sayan chandra
sayan chandra - avatar
0
Anyways, you could also try this: public class MyClass { static int x; public static void main(String[ ] args) { x = 5; addToX (); System.out.println(x); } static void addToX (){ x++; } } The function does not work with other variables as x here, so @sayans idea might be better for your uses.
20th Sep 2017, 5:18 AM
Jonas Schröter
Jonas Schröter - avatar
0
I posted the same code as yours @sayan
20th Sep 2017, 3:58 PM
Jonas Schröter
Jonas Schröter - avatar
0
Ok, your point😊
20th Sep 2017, 4:09 PM
Jonas Schröter
Jonas Schröter - avatar
- 1
this is another way... public class MyClass { static int x; public static void main(String[ ] args) { x = 5; addToX (); System.out.println(x); } static void addToX () { x++; } }
20th Sep 2017, 2:03 PM
sayan chandra
sayan chandra - avatar
- 1
no you r not... 1--the code needs a static before int... ur code wont work... 2--also u have printed c which is not in code..
20th Sep 2017, 4:06 PM
sayan chandra
sayan chandra - avatar