+ 2

What goes where in the memory according to following code?

I am trying to understand how java works and I really need to understand the following points: For each variable r from line 2, r from line 5, n and x in general 1- the lifetime 2- the scope 3- and the visibility section It would be very kind of you to help a new programmer understand from your experiences and I really appreciate it as I spend days to understand but couldn't be sure and there is no test for that. The code is the following: ____________________________________________________________________ 1 public class Example { 2 private static int r; // this is the first variable r I want to know about 3 4 public static int logTwo (int x) { //I want to know generally about n and x in all positions 5 int r = 0; // this is the second variable r I want to know about 6 while (x > 1) { 7 x = x / 2; 8 r = r + 1; 9 } 10 return r; 11 } 12 13 public static void main ( String [] args ) { 14 int n = Integer . parseInt ( args [0]); 15 r = logTwo (n); 16 System .out. println (r); 17 r = logTwo (n +1); 18 System . out. println (r); 19 } 20 } ____________________________________________________________________ I spent day reading and couldn't figure out the question I asked so PLEASE DON'T THROW ME LINKS It would be very nice to explain I'd really Appreciate it Thanks a lot in advance!

10th May 2020, 7:05 AM
Mohammad Ala Tahhan
Mohammad Ala Tahhan - avatar
2 ответов
+ 3
First variable r, its scope spans entire class and is visible in all methods inside the class. But because its private it's not visible outside the class. Second variable r is a local variable and shadows the one with class scope -> it means that inside the method r refer to the local variable and not the one with class scope. The local variable r in the method will be destroyed when we exit the method, but the one with class scope will continue to exist. For method arguments: The argument x acts like a local variable, so it only exists until method exits. the variable you pass into the method is a copy of n , and x holds that copy. But because it is a copy and not a reference, any changes to x wont change the value of n outside the method.
10th May 2020, 7:21 AM
Gen2oo
Gen2oo - avatar
+ 1
Gen2oo thank you so very much. I am really grateful to you for your help, time, and amazing explanation. I voted up and I wish if I can vote 100000000000 times up to you. This is how much I thank you Have a great day :)
10th May 2020, 12:41 PM
Mohammad Ala Tahhan
Mohammad Ala Tahhan - avatar