úterý 21. července 2015

Otázky z prac. pohovorů

Během pohovorů do pozice Java programátora jsem pochytil pár zajímavých otázek, u kterých jsem si nevěděl rady. Předkládám tu některé z nich:


1) Co je statická synchronized metoda?
Výtah ze specifikace Javy: A synchronized method acquires a monitor (§17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
Pokud je synchronized na statické metodě, zámek je na třídě. Tudíž opravdu jen jedno vlákno může přistupovat do této metody


 2) Mohou 2 vlákna volat stejnou synchronized metodu v tu samou chvíli?
Ano, protože synchronized na metodě získává zámek na objektu. Pokud tedy máme 2 různé objekty stejné třídy, mohou volat v jednu chvíli tu samou metodu.
Zdroj: http://stackoverflow.com/questions/9382015/can-two-threads-access-a-synchronized-method-at-the-same-time


3) Může v Javě existovat statické třídy?
Ano, může existovat jako nested class (vnořené třídy?). Statické vnořené třídy mohu vytvářet bez nutnosti mít instanci vnější třídy.

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

4) Jaký je rozdíl mezi nested a inner class?
Nested class se dělí na statické a nestatické. Statické jsem popsal o otázku výše, nestatické se nazývají inner class.
Pro zajímavost, v Javě existují 4 druhy vnořených tříd: 
  • static class: declared as a static member of another class
  • inner class: declared as an instance member of another class
  • local inner class: declared inside an instance method of another class
  • anonymous inner class: like a local inner class, but written as an expression which returns a one-off object


5) Mohu přetížit (overload) metody public void fun(List<String> x) a public void fun(List<Integer> x)?
Ne. Generics kontroluje kompilátor, ale při překladu do bajtkódu se maže generics typy (tzv. Type erasure proces) a konverze do správného typu je zajištěno pomocí casting. Proto v bajtkódu by tyto metody byly od sebe nerozlišitelné.


6) Úloha:
Write a method that tells whether a given positive integer is happy. A happy number is found using the following process: Take the sum of the squares of its digits, and continue iterating this process until it yields 1, or produces an infinite loop.

For example the number 49:
4^2 + 9^2 = 97
9^2 + 7^2 = 130
1^2 + 3^2 + 0^2 = 10
1^2 + 0^2 = 1

Therefore number 49 is happy. Similarly 10 is happy, but 2, 3, 4, 5, 6, 8 or 9 are not happy.

Žádné komentáře:

Okomentovat