Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
jamalbacchus
Courses Plus Student 6,664 PointsQuick question:
@CriagDennis,
Could you explain why this calculator is equal to 20. if the num = 100:
public class Calculator { int num = 100; public void calc(int num) { this.num = num * 10; } public void printNum(){ System.out.println(num); } public static void main(String[] args) { Calculator obj = new Calculator (); obj.calc(2); obj.printNum(); } }
1 Answer
Boban Talevski
24,793 PointsI assume you mean why the output of the program is 20, i.e. the class variable num is actually 20 and not 100.
It's because 100 is only the initial value of the class variable num.
Once the line obj.calc(2); is executed , we are calling the method with a parameter 2 which then assigns a value to the variable num equal to 10 times that parameter, in this case (10 times 2), so the variable num gets the value of 20 and it's no longer 100.
The value of the variable num is 100 upon creation of the object, so if we didn't call the method calc, the value would be 100 and we would get 100 as the output of the program.