In the Main method, instead of in a Static block, whatever that means. Both would populate the list the same way.
It works, but why would this make ANY difference, compared to just doing it like we've done it before ?
You must be signed in to leave a comment
28 May 2019, 17:28
This is true. They are introducing you to static blocks though. This is a complex subject that I don't even fully understand, but here is a discussion about it on stackoverflow: https://stackoverflow.com/questions/13994950/necessity-of-static-block-in-java
28 May 2019, 17:37
The best answer I can come up with, using the info in that link, is that static blocks are initialized once when the class is first loaded (not every time a new object is created) and initialized before anything else. Because static members are shared among every object of that class, putting the code to initialize static members wouldn't make sense anywhere else because you could re initialize something by accidently by over writing values.Lets say that you had a static count and initialized it to 0 in the constructor. You then create an object and use it to increase count a couple of times in your code (for whatever reason). Then you create a new object of the same type expecting it to have the same count, but the constructor reinitializes count to 0 and you lose value. This isn't the best example, but in more complex code you would want certain things initialized there. Here is some code you can run to see the what goes on:
27 July 2019, 11:46
If you initialize it in main instead wouln't that also run only once?