Guy Hazan
Guy Hazan

Reputation: 11

Java static variables usage and memory

I would like to know what happens to the memory allocated to objects that are dependent on static variables and what is the best practice for this, example:

private static final int lineSeperator = System.getProperty("line.separator");

public String concat(String a, String b){
    String concat = a + lineSeperator + b;
    String concat2 = concat + "2";
    return concat2;
}

What would happen in memory to concat and concat2, will they be garbage collected or will they stay alive for ever since they are using a static variable?

Upvotes: 1

Views: 238

Answers (2)

Stephen C
Stephen C

Reputation: 718826

What would happen in memory to concat and concat2, will they be garbage collected or will they stay alive for ever since they are using a static variable?

The String in the concat variable will be eligible for garbage collection when this method returns since it will no longer be reachable.

The lifetime of the String in concat2 that is being returned (modulo the compilation error!!) will depend on what the caller does with it.

The + operator will generate a new String. The fact that it contains characters from an existing String that (in this case) is referenced from a static variable makes no difference. The characters are copied into the new String as it is being formed.


what is the best practice for this

  1. There is no "best practice". Read No Best Practices.

  2. Given that there are no garbage collection implications for concatenating static strings, you don't need to do anything.

  3. As a general rule, you can just let the JVM optimize string concatenations as it sees fit. It will probably produce code that is as good as anything you can achieve. Possibly better ... in recent JVMs.

    The only situation where it can be helpful to intervene is if you are constructing a large string by looping over some data structure; e.g.

    String res = "";
    for (String member: someLargeList) {
        res = res + " " + member;
    }
    

    For this example may be advisable to use a StringBuilder and append calls to build the string. Better still use StringJoiner or equivalent.

    But it is NOT advisable to try to optimize string concatenations in general; see above.

Upvotes: 4

Crack_it
Crack_it

Reputation: 63

They will be eligible for garbage collection as soon as the last statement of method concat() is executed.

By the way, your above concat() method will not compile as it is returning String value when it's return type is void.

Upvotes: 0

Related Questions