Java – why can variables be declared without an initial value?
I'm reading Gilles Dowek's programming principles:
He said that it is also possible to declare a variable without giving it an initial value, and we must be careful not to use a variable that has been declared without an initial value and has no assignment This can produce errors
Note: the author of this book mentioned the possibility of declaring variables without initial values on Java
So why is this variable declared valid? When do I start using it?
Solution
Many different languages have many different reasons
When memorizing declared variables, you need some memory to hold the variables This involves asking the operating system kernel for memory, or some kind of monitor that tracks memory In short, this can be an expensive operation Therefore, in many cases, you want to allocate all the memory required by the object at the same time, and then allocate any value that must be allocated to it later In this way, you can improve the performance of programs in key components This use case is common, allowing declared functionality without initialization However, good practice asserts that in all other cases, you should initialize variables at allocation time
Think of memory allocation as bureaucracy Too much work on paper Therefore, if you know that a large amount of memory will be used in the future, you need to provide a large amount of memory in advance in a single transaction instead of requiring the kernel every time
Expensive initialization is very similar to the above view Suppose you have 1 million times and 1 million arrays Initializing such an array is an expensive process It would be foolish to use the default value to do so, so such a function in which memory is allocated and then used as needed
Here, it's like you're buying a lot of Lego blocks to build something, but you want to buy them in the default spider man shape Shopkeepers or you have to make extra efforts to make them spider - man shapes when you reshape them anyway