+ 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; } }
6 Answers
+ 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!!
+ 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đ
+ 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)
+ 1
Why is the method addOne used if 5 + 1 would be 6?
+ 1
So there is a mistake in the course: Java/Classes and Objects/Value & Reference Types lesson 1. Could you have a look?
+ 1
So the output is 5, but why?