-3

This is an example code:

public void doSomething(){
   long currentTime = 1430668777967;
   System.out.println("Time: "+currentTime);
}

If I made the code above run multiple times would it be using more ram at the currentTime variable even after I stop using it and create a new one?

Note: I know I can just get it from System

2 Answers2

3

No. In fact currentTime is disposed of (freed) after doSoemthing() finishes because it is a local variable.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

the memory is allocated on the stack when currenttime is set. then in the next line the string "Time: " and String representation of the long are concatinated to create a new string that is printed. the constructed temporary strings are released by the end of the method and the long is returned to the stack as the method exits.

LhasaDad
  • 1,786
  • 1
  • 12
  • 19
  • *"the Strings are released by the end of the method"* Wrong. http://stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings – m0skit0 May 03 '15 at 16:36
  • Its likely only the "Time: " string object would have been added to the pool. correct? the other items would have been released. they are not automatically intern-ed. – LhasaDad May 03 '15 at 16:52
  • That's right sir, but that's the only string there :) – m0skit0 May 03 '15 at 17:04
  • What about the constructed string that is passed to the println function? it will wind up getting a ref to the concatenated string also I would assume before the concatenation occurred the compiler created a temp string for the long? all these temp objects would be freed and not intern-ed. Just thinking the downvote I got was overly harsh response. – LhasaDad May 03 '15 at 17:10
  • Yes, there's a String constructed from the long. Still your answer explicitly states that the string "Time: " is released, which is wrong. – m0skit0 May 03 '15 at 17:21
  • I'll edit it to add "temporary" strings to the answer. I see how it could be interpreted to refer to the "time: " string (literal string). in my mind I consider that a constant that is 'always around' (inter-ed or inlined, etc). – LhasaDad May 03 '15 at 17:45