Search code examples
javaswingjtextfield

Where to declare a variable (Java)


I'm making a GUI using Java Swing right now and I'm doing some code refactoring.

My question is this: Does it matter where I declare a variable type in terms of memory/efficiency or anything else for that matter? Code:

for (int i = 0; i < 7; i++) {
    JTextField textfield = new JTextField(5);
    // Do stuff with textfield

vs:

JTextField textfield;
for (int i = 0; i < 7; i++) {
    textfield = new JTextField(5);
    // Do stuff with textfield

Solution

  • If you only need it inside the loop, declare it inside. After the loop is finished, the textfield will be available for Garbage Collection.

    This way, you make the object available to Garbage Collection as soon as possible.