Which code is better in terms of performance, object allocation and memory management?
String a = "";
String b = "";
String c = "";
int n = 1000;
Well its pretty much all the same - by the way the space for the references is allocated on the stack as soon as you enter the method.
The question is what you do with the string-objects, if you do a lot of concatenations using the + operator or many calls to methods which return new string-objects (like substring, ...) this will be slow. For concatenation StringBuilder is a good point to start...
Conclusion: Don't worry about the local variables, object creation for the strings will be visible way before ;)
but one is on the heap and one is on the stack, right? The first one is on the heap, the other is on the stack.. so the second one is best in terms of overall runtime memory footprint?
I took it as implicit that the first one has class scope on the Strings (they're members) and the second on has local scope for the strings (they're declared in a method).
Your use of this web site or any of its content or software indicates your agreement to be bound by these Terms of Participation.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.