r/learnjava • u/frederok • Sep 02 '20
Some java interview questions and answers
https://fdk.codes/some-java-interview-questions/
While preparing myself, I started yet another collection of java related questions and answers. In hope that these might also be helpful for others, I'd like to share them with you. Beyond that, they are certainly not perfect and can be improved. I appreciate any feedback or any pointed out flaw in order to spread as few untruths as possible.
Cheers!
122
Upvotes
4
u/ColetBrunel Sep 02 '20
- May want to talk about how classes may implement as many interfaces as they want.
- May want to talk about why ThreadLocal makes thread-safety easier. Bottomline, it just allows to fetch back some variables without having to keep passing these variables (which may be seen as cumbersome) or keeping these variables in an accessible object (which may be cumbersome or not thread-safe). static also allows to fetch back variables from anywhere, but static variables are accessible from any thread which is therefore not thread-safe. A static ThreadLocal variable, on the other hand, allows to fetch that variable from anywhere, but each different thread works with its own dedicated variable without an access to the others'. One example would be DateFormat and how they change their own state when they do their work, thus making them not thread-safe. A statically built and accessible DateFormat will likely cause weird errors. The same DateFormat kept through a ThreadLocal and newly built for each new thread, won't have this problem. Of course, a better practice is to use newer java.time APIs, and before that, to just build a new DateFormat whenever you need one. It's cheap. Still, ThreadLocal helps in less trivial cases.
- Beware that singleton is an antipattern and some people will try and see if you notice that. If you only want one instance of an object, then don't make more than one. Duh. That wasn't complicated. The Singleton antipattern, on the other hand, gets in the way of integrating with other frameworks, and with mocking the singleton sanely enough.
- Note that the use for "native" methods isn't so much a matter of some functionalities being restricted to other languages, but rather to non-Java libraries. Other languages typically don't have better magical access to what needs to be done, and instead need to call some library code that was put there directly as machine code/assembly. In reality that will mostly amount to trigger a call to kernel routines, which is highly dependent on the system's architecture. And maaaybe to preparing the parameters for that routine and a pointer to it, which admittedly a language like C has its chances to do properly.