As I understand it, an object or variable only continues to exist within the brackets that its created in. So if a create an int in a for loop, it will be destroyed outside of the loop. But what if I wanted it to exist beyond that. What if you would know outside of the for loop what types of variables would be created or how many because it depends on user input?
Just declare them outside the for loop:
int myint = 0;
for(int i = 0; i < 3; i++) {
myint += i;
}
System.out.println(myint);
I don’t understand… you seem to know how scope works, but then you seem to think you can get around it…?
If you create an object within brackets, its going to (in theory) be sent to the G.C. when its scope limit is reached, there’s nothing you can do about that. You can declare the object in a “bigger” scope (outside of the brackets) and then you can keep using the object, or you can do something like this:
int y;
for(int i = 0; i < 5; i++) {
int z = i;
y = z;
//z's scope ends here, it will be "deleted". However, 'y' holds the value of 'z' so you can keep using it essentially.
}
Set a reference to the object in a larger scope.
Object globalObject;
{
Object o;
// create Object o
globalObject = o;
// globalObject now points at the Object o
}
o.doSomething();
// Do something with the Object o
That won’t work
o’s scope ends after the brackets, you can’t call upon it! You probably meant to type globalObject.
(globalObject.doSomething();
)
That basically was my question. I understood that I can (and should) just declare variables outside of the for loop (or whatever brackets we’re talking about) in order to keep it in scope. I was just wondering if there was a way around it.
Thanks though, that answers my question!
Note: Scope and lifetime are not the same thing.
Clarification: scope is the amount of time you can count on the object existing - AKA how long it exists theoretically. Lifetime is how long is practically exists before it’s garbage collected.