Should this variable be local or static?

Lukas :

I'm a beginner in Java trying to learn it and sorry if the question sounds dumb :D

Right now I'm making this simple program (without objects) for practice purpose, which generates random elements for the array using Random randomNumber = new Random();, all 3 methods (random: byte int, long elements), uses the same randomNumber variable. My question: should the randomNumber variable created as static variable (by my knowledge it means that it will be in memory until execution of the program ends, is it true?), or local variable that is created every time we call one of those 3 methods (and destroyed after exiting them)? I'm trying to work on this task without objects just for practice purposes.

Thanks for help !

Halex :

This is entirely your choice. Your program will function the same way. The only difference is at the memory and processing power level.

Will you call many methods that use randomNumber in a row? Then don't destroy it and let it be an instance variable.

Do you plan on calling such a function every once in a while? Then don't keep the object in memory, let it be vreated only when you need it and destroy it afterwards (use it as a local variable).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396723&siteId=1