0

I always wonder what happen to a new object let's say

   final StringBuilder sb = new StringBuilder();
   sb.append("some code");

After java create the new StringBuilder object, do what it does (without store it to a class variable) and exit the method, what happen to the StringBuilder object? It remain in ram or its removed by garbage collector?

I ask this because i design a game and i create many many objects upon each click such as a StringBuilder.

  • It gets collected by Garbage collector and memory is freed. – Quanta Jun 21 '20 at 15:02
  • If your StringBuilder never escapes the method and has 0 references to it, then it will very likely be garbage collected. You probably don't need to worry about memory usage because you never destruct those objects. – user Jun 21 '20 at 15:02
  • 2
    It will become *eligible* for garbage collection. – Pshemo Jun 21 '20 at 15:02
  • Depends by where StringBuilder is declared. – KunLun Jun 21 '20 at 15:03
  • It depends when the reference to the memory in which object is stored is destroyed. As soon as the reference becomes null, garbage collector removes it from memory and it is no longer accessible. – Vipul Tyagi Jun 21 '20 at 15:04
  • If there are no references to that object, it is removed. That is what garbage collector does for you. – Glauvus Jun 21 '20 at 15:04
  • Recommended: https://stackoverflow.com/questions/3798424/what-is-the-garbage-collector-in-java – Quanta Jun 21 '20 at 15:05

1 Answers1

0

If there's no reference to that object it will be eventually be removed by the garbage collector.

Avi L
  • 1,558
  • 2
  • 15
  • 33
  • So if my code create a StringBuilder upon each click it's safe? In terms of 2020 it shouldn't matter since java is object oriented language i guess that is the purpose of it. – WhatRemainsOfEdithFinch Jun 21 '20 at 15:02
  • Yes it is totally safe and you should not worry about it unless you store it's reference somewhere – Quanta Jun 21 '20 at 15:03
  • Yes, that's correct. – Avi L Jun 21 '20 at 15:04
  • 1
    It has nothing to do with Java being an object oriented language. It's because Java is a garbage collected language. There are many languages that are not object oriented, but is garbage collected anyway. – marstran Jun 21 '20 at 15:05