3

I have a static factory method which will return a fragment object.

private static String  final A1="a1";
private static String  final A2="a2";
private static String  final A3="a2";
private static String  final A4="a4";

public static MyFragment newInstance(int index) {
    MyFragment f = new MyFragment();
    Bundle args = new Bundle(4);
    args.putInt(A1, index);
    args.putInt(A2, index);
    args.putInt(A3, index);
    args.putInt(A4, index);
    f.setArguments(args);
    return f;
}

And am getting it within oncreate()

getArguments().getInt(A1, 0);

Now my question is: I am creating couple of MyFragment object like below

List<Fragment> fragments = new ArrayList<>();
fragments.add(MyFragment.newInstance(defaultId));
int i = 1;
for (Categories categories : mCategories) {
    String id = categories.getCategory_id();
    String name = categories.getCategory_name();
    //  String slno = categories.getSlno();
    fragments.add(MyFragment.newInstance(defaultId));
    Titles[i] = name;
    i++;
}

As the variables A1-A4 as static will it clear it's memory on activity destroy ? or i need to assign the variables as null in onDistroy ?

Please help me to clarify the doubt ?

Christ
  • 155
  • 2
  • 16
  • 1
    you have marked as final too. So you can't any new value to them. And don't worry about them. `final static` is the marker for java constants. As little exercise look for the meaning of static and final in java. – Blackbelt Oct 26 '15 at 13:19

1 Answers1

2

A static variable is allocated when the class is loaded, and it will only be garbage collected if the class loader that loaded the class is itself deallocated.

A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector [...] Classes and interfaces loaded by the bootstrap loader may not be unloaded.

See the answer to a similar question Are static fields open for garbage collection?

Community
  • 1
  • 1
James Wierzba
  • 16,176
  • 14
  • 79
  • 120
  • So, Initializing it as `null` in onDistroy() is the right thing to do right ? so that garbage collector can free up the memory asap.. – Christ Oct 27 '15 at 04:12
  • 1
    @Christ No, these are final and therefore cannot be assigned to `null`. Rarely in Java do you ever have to worry about cleaning up references to primitives (or Strings) as they are treated differently by the VM and GC. If you did want to unload something onDestroy make them a non-static variable and they will get collected with the class, but this example is not a case where you'd want to do that as the optimizer probably inlines the current implementation. – LINEMAN78 Oct 27 '15 at 04:34