+ 4

I got somethin funny. Here it is

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); } } when run the output is- 6 5 my problem is if execution starts from top to bottom why is not the output 5 6. help me

3rd Feb 2018, 5:45 PM
stephen haokip
stephen haokip - avatar
9 Respuestas
+ 18
statement(s) in main method are executing from top to bottom only , see carefully //thats why "6\n5\n" as output
3rd Feb 2018, 6:00 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 8
hilarious! are you a comedian?
3rd Feb 2018, 6:32 PM
Ahri Fox
Ahri Fox - avatar
+ 3
gotcha tank you
3rd Feb 2018, 6:25 PM
stephen haokip
stephen haokip - avatar
+ 2
It seems to be because of the order of output. The System.out.println after calling addOneTo is printing out the value of x inside main(). The System.out.println call in addOneTo is also printing it's local value of x, but after adding 1 to it. So, if you swap those two lines you should be fine.
3rd Feb 2018, 9:40 PM
Tom Shaver
Tom Shaver - avatar
+ 2
Ha! you're right, that is funny! why the downvote!
4th Feb 2018, 10:29 PM
DeleteThisAccount
+ 2
The execution starts in main method, the first call is to addOneTo(x) this one recives x as a parameter and print x+1. The next instruction called is System.out.println(x), this one print x.
13th Mar 2018, 8:38 PM
Lucas Abregú
Lucas Abregú - avatar
+ 1
De todos modos me parece que la idea del ejercicio era mostrar el 'ambito de trabajo' de la variable, ya que aunque el metodo addOneTo(x) incrementa el valor de su parametro, la variable x del metodo main no se altera.
13th Mar 2018, 8:44 PM
Lucas Abregú
Lucas Abregú - avatar
+ 1
Bécasse the statement in main() executes first and second statement exécutés after vallon.
11th Aug 2020, 4:31 AM
Lucifer 👩‍💻
Lucifer 👩‍💻 - avatar
0
if you sumation num5 & num1 in binary for exampl: 1---> 0001 + 5--->0101 = 0101=5
25th Sep 2020, 11:42 AM
Sarah Ali Alshawi
Sarah Ali Alshawi - avatar