Can someone explain the code step by step? | Sololearn: Learn to code for FREE!
+ 1

Can someone explain the code step by step?

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

2nd Mar 2018, 10:25 PM
Sebastian Sivertsen
Sebastian Sivertsen - avatar
6 odpowiedzi
+ 5
You're defining a public class "MyClass". Inside it. You're defining two static methods(main, addOne). Normally static void main is the entry point for executing a Java program. Assuming you execute main method: You're declaring an int variable (x) and initializing it's value with 5. Then you're calling addOneTo method. AddOneTo is a method that increments input parameter (int) value by one, but it doesn't return its value. So you are declaring x variable and then you're printing it's value. That's it! int x = 5 -> initialices int variable x on 5 addOneTo(x) -> Increments x from 5 to 6 But when exiting this method, x remains 5 on main method because the variable's Scope. X it's defined only for main method, is not a class attribute and addOneTo method does not return this value, so it will be eventually lost. System.out.println(x); -> Prints 5 Hope I helped you. Have a nice day and enjoy coding!!
2nd Mar 2018, 10:48 PM
Sergio David Romero
Sergio David Romero - avatar
+ 19
public class MyClass { public static void main(String[ ] args) { int x = 5; x=addOneTo(x); System.out.println(x); } static int addOneTo(int num) { return num + 1; } } //this will output 6 , u will see 👉3 modifications //be simple , hopu U got the difference & also understood why output was 5 in the previous code👍
3rd Mar 2018, 1:17 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 4
//variable of type integer declaration int x=5; //function increments x by one addone(x){ x=x+1; therefore x=6 } //outputs x which is 6 System.out.println(x)
2nd Mar 2018, 10:29 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 1
Why is the method addOne used if 5 + 1 would be 6?
2nd Mar 2018, 10:27 PM
Sebastian Sivertsen
Sebastian Sivertsen - avatar
+ 1
So there is a mistake in the course: Java/Classes and Objects/Value & Reference Types lesson 1. Could you have a look?
2nd Mar 2018, 10:34 PM
Sebastian Sivertsen
Sebastian Sivertsen - avatar
+ 1
So the output is 5, but why?
2nd Mar 2018, 10:44 PM
Sebastian Sivertsen
Sebastian Sivertsen - avatar