please explain this to me | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

please explain this to me

really having a hard time understanding this 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; } } // Outputs "5" this one outputs 5 if we wanted to print 6 we would have done System.out.println(num); or better yet x+=1 ; and then print "x" 2nd thing is about getters and setters doesn t getter and setters are used for private variables so they can be accessed in creating the object in main ? like each private variable have it s own getter and setter?

25th Dec 2018, 11:30 AM
Fe Di
Fe Di - avatar
1 Answer
+ 3
1. I think that code sample in tutorial exists solely to demonstrate that value-types passed as method arguments are immutable, changes in method 'addOneTo' only applies to a copy of <x> that is created (and recognized as <num>) within the 'addOneTo' method. 2. Yes, getters and setters are used for manipulation of 'hidden' members, but they have nothing to do with object instantiation, they are available after an object has been instantiated from a class. Private variables (members) may have a getter, a setter or both, depending whether if they are supposedly readable, writable, or read-write-able, I guess : ) Hth, cmiiw
25th Dec 2018, 12:20 PM
Ipang