Vous êtes sur la page 1sur 19

Java

Study online at quizlet.com/_2m5riy

1. ... In Java a static nested class is essentially a normal class that has just been nested inside another class. Being static, a static
nested class can only access instance variables of the enclosing class via a reference to an instance of the enclosing class.
2. ... A private constructor can still get called from other constructors, or from static methods in the same class.
3. ... The Java access modifiers private and protected cannot be assigned to a class.
4. ... Java access modifier assigned to a Java class takes precedence over any access modifiers assigned to fields, constructors and
methods of that class. If the class is marked with the default access modifier, then no other class outside the same Java package
can access that class, including its constructors, fields and methods.
5. ... The protected access modifier provides the same access as the default access modifier, with the addition that subclasses can
access protected methods and member variables (fields) of the superclass. This is true even if the subclass is not located in the
same package as the superclass.
6. ... Subclasses cannot access methods and member variables (fields) in the superclass, if they these methods and fields are marked
with the default access modifier, unless the subclass is located in the same package as the superclass.
7. ... The default access modifier means that code inside the class itself as well as code inside classes in the same package as this
class, can access the class, field, constructor or method which the default access modifier is assigned to. Therefore, the default
access modifier is also sometimes referred to as the package access modifier.
8. ... The default Java access modifier is declared by not writing any access modifier at all.
9. ... Classes cannot be marked with the private access modifier.
Therefore the private access modifier is not allowed for classes.
10. ... Fields and methods with default (package) access modifiers can be accessed by subclasses only if the subclass is located in the
same package as the superclass. Private fields and methods of the superclass can never be referenced directly by subclasses.
11. ... If a method or variable is marked as private (has the private access modifier assigned to it), then only code inside the same class
can access the variable, or call the method. Code inside subclasses cannot access the variable or method, nor can code from
any external class.
12. ... if a constructor is declared protected then only classes in the same package, or subclasses of that class can call that constructor.
13. ... The object versions of the primitive data types are immutable.
14. ... It is possible to have many different variables reference the same object. This is not possible with primitive data types.
15. ... Java's auto boxing features enables you to use primitive data types where the object version of that data type was normally
required, and vice versa. There is one pitfall to keep in mind though. A variable of type object (a reference to an object) can point
to null, meaning it points to nothing - no object. If you try to convert null to a primitive value you will get a NullPointerException
16. ... Using the keyword super refers to the superclass of the class using the super keyword. When super keyword is followed by
parentheses like it is here, it refers to a constructor in the superclass.
17. ... When you create a subclass of some class, the methods in the subclass cannot have less accessible access modifiers assigned to
them than they had in the superclass.
18. ... In Java you cannot override private methods from a superclass. If the superclass calls a private method internally from some
other method, it will continue to call that method from the superclass, even if you create a private method in the subclass with the
same signature.
19. ... A class that extends another class does not inherit its constructors. However, the subclass must call a constructor in the
superclass inside one of the subclass constructors!
20. ... A final class cannot be extended. In other words, you cannot inherit from a final class in Java.
21. ... If a Java inner class declares fields or methods with the same names as field or methods in its enclosing class, the inner fields or
methods are said to shadow over the outer fields or methods.
22. ... Notice how you put new after the reference to the outer class in order to create an instance of the inner class.

Non-static nested classes (inner classes) have access to the fields of the enclosing class, even if they are declared private.
23. ... A Java method parameter can be declared final, just like a variable. The value of a final parameter cannot be changed. That is, if
the parameter is a reference to an object, the reference cannot be changed, but values inside the object can still be changed.
24. ... The different Java nested class types are:

Static nested classes


Non-static nested classes
Local classes
Anonymous classes
25. ... In Java nested classes are considered members of their enclosing class.
26. ... The purpose of a nested class is to clearly group the nested class with its surrounding class, signaling that these two classes are
to be used together. Or perhaps that the nested class is only to be used from inside its enclosing (owning) class.
27. ... Nested classes which are declared private are not inherited. Nested classes with the default (package) access modifier are only
accessible to subclasses if the subclass is located in the same package as the superclass. Nested classes with the protected or
public access modifier are always inherited by subclasses.
28. ... If you override a method in a subclass, and the method is all of a sudden removed or renamed or have its signature changed in
the superclass, the method in the subclass no longer overrides the method in the superclass.
29. ... In fact, since the constructor is now empty, we could leave it out and the Java compiler would insert it, and insert an implicit call
to the no-arg constructor in the superclass.
30. ... Java classes where the subclass constructors did not seem to call the constructors in the superclass. Maybe the superclass did
not even have a constructor. However, the subclass constructors have still called superclass constructors in those case.
31. ... The Java inheritance mechanism does not include constructors. In other words, constructors of a superclass are not inherited by
subclasses. Subclasses can still call the constructors in the superclass using the super() contruct. In fact, a subclass constructor is
required to call one of the constructors in the superclass as the very first action inside the constructor body.
32. ... If, however, the subclass calls up into a method in the superclass, and that method accesses the field with the same name as in
the subclass, it is the field in the superclass that is accessed.
33. ... fields cannot be overridden in a subclass. If you define a field in a subclass with the same name as a field in the superclass, the
field in the subclass will hide (shadow) the field in the superclass.
34. ... If you override a method in a subclass, but still need to call the method defined in the superclass, you can do so using the super
reference
35. ... Java has a way to force all numbers in a calculation to be floating point variables. You suffix the numbers with either a capital F
or D. Here is an example: 4F or 4D
36. ... The Math.abs() function returns the absolute value of the parameter passed to it.
37. ... The Template Method design pattern provides a partial implementation of some process, which subclasses can complete when
extending the Template Method base class.
38. ... method named replace() which can replace characters in a String. The replace() method does not actually replace characters in
the existing String. Rather, it returns a new String instance which is equal to the String instance it was created from, but with the
given characters replaced.
39. ... There is a version of the indexOf() method that takes an index from which the search is to start. That way you can search through a
string to find more than one occurrence of a substring.
40. ... The Java String class also has a lastIndexOf() method which finds the last occurrence of a substring.
41. ... The compareTo() method compares the String to another String and returns an int telling whether this String is smaller, equal to or
larger than the other String. If the String is earlier in sorting order than the other String, compareTo() returns a negative number. If
the String is equal in sorting order to the other String, compareTo() returns 0. If the String is after the other String in sorting order,
the compareTo() metod returns a positive number.
42. ... compareTo() method may not work correctly for Strings in different languages than English. To sort Strings correctly in a specific
language, use a Collator.
43. ... The Java String class contains a method called trim() which can trim a string object. By trim is meant to remove white space
characters at the beginning and end of the string. White space characters include space, tab and new lines.
44. ... The trim() method does not modify the String instance. Instead it returns a new Java String object which is equal to the String
object it was created from, but with the white space in the beginning and end of the String removed.
45. ... The Java String class contains a split() method which can be used to split a String into an array of String objects. The source String
has been split on the a characters. The Strings returned do not contain the a characters. The a characters are considered delimiters
to split the String by, and the delimiters are not returned in the resulting String array.
46. ... The indexOf() method returns the index of where the first character in the first matching substring is found.
47. ... The String split() method exists in a version that takes a limit as a second parameter. Here is a Java String split() example using the
limit parameter:

String source = "A man drove with a car.";


int limit = 2;
String[] occurrences = source.split("a", limit);
The limit parameter sets the maximum number of elements that can be in the returned array.
48. ... The Java String class contains a set of overloaded static methods named valueOf() which can be used to convert a number to a
String.
49. ... It is possible to get a character at a certain index in a String using the charAt() method.
50. ... You can also get the byte representation of the String method using the getBytes() method. Use the specific charset to do that.
51. ... loop over each string in the array:
for(String aString : strings) {
//
}
52. ... The private access modifier means that only code inside the class itself can access this Java field.

The package access modifier means that only code inside the class itself, or other classes in the same package, can access the
field. You don't actually write the package modifier. By leaving out any access modifier, the access modifier defaults to package
scope.

The protected access modifier is like the package modifier, except subclasses of the class can also access the field, even if the
subclass is not located in the same package.

The public access modifier means that the field can be accessed by all classes in your application.
53. ... If the substring is not found within the string, the indexOf() method returns -1;
54. ... The substring() method takes two parameters.
55. ... The Math.ceil() function rounds a floating point value up to the nearest integer value.
56. ... When you call a constructor from inside another constructor, you use the this keyword to refer to the constructor
57. ... The Math.floor() function rounds a floating point value down to the nearest integer value.
58. ... The Math.floorDiv() method divides one integer (int or long) by another, and rounds the result down to the nearest integer value.
What is the difference to regular int division?
59. ... The Math.min() method returns the smallest of two values passed to it as parameter.
60. ... The Math.max() method returns the largest of two values passed to it as parameter.
61. ... The Math.round() method rounds a float or double to the nearest integer using normal math round rules .
62. ... The Math.random() method returns a random floating point number between 0 and 1.
63. ... You can access the length of an array via its length field
64. ... The parameters mean "from - including, to - excluding".
65. ... You can convert an Java array of primitive types to a String using the Arrays.toString() method. H
66. ... Binary search
If more than one element exists in the array with the searched value, there is no guarantee about which element will be found.

If no element is found with the given value, a negative number will be returned. The negative number will be the index at which
the searched element would be inserted, and then minus one.
67. ... More precisely, objects representing Java String literals are obtained from a constant String pool which the Java virtual machine
keeps internally. That means, that even classes from different projects compiled separately, but which are used in the same
application may share constant String objects. The sharing happens at runtime. It is not a compile time feature.
68. ... If you want to be sure that two String variables point to separate String objects, use the new operator like this:

String myString1 = new String("Hello World");


69. ... When concatenating Strings you have to watch out for possible performance problems. Concatenating two Strings in Java will be
translated by the Java compiler to something like this:

String one = "Hello";


String two = " World";

String three = new StringBuilder(one).append(two).toString();


As you can see, a new StringBuilder is created, passing along the first String to its constructor, and the second String to its
append() method, before finally calling the toString() method. This code actually creates two objects: A StringBuilder instance and
a new String instance returned from the toString() method.
70. ... Now, for every iteration in this loop a new StringBuilder is created. Additionally, a String object is created by the toString()
method. This results in a small object instantiation overhead per iteration: One StringBuilder object and one String object. This by
itself is not the real performance killer though. But something else related to the creation of these objects is.

Every time the new StringBuilder(result) code is executed, the StringBuilder constructor copies all characters from the result String
into the StringBuilder. The more iterations the loop has, the bigger the result String grows. The bigger the result String grows, the
longer it takes to copy the characters from it into a new StringBuilder, and again copy the characters from the StringBuilder into
the temporary String created by the toString() method. In other words, the more iterations the slower each iteration becomes.
71. ... You can obtain the length of a String using the length() method.
72. ... Local classes can only be accessed from inside the method or scope block in which they are defined.

Local classes can access members (fields and methods) of its enclosing class just like regular inner classes.

Local classes can also access local variables inside the same method or scope block, provided these variables are declared
final.
73. ... A Java field can have be given an initial value. This value is assigned to the field when the field is created in the JVM. Static fields
are created when the class is loaded. A class is loaded the first time it is referenced in your program. Non-static fields are created
when the object owning them are created.
74. ... An interface default method can contain a default implementation of that method. Classes that implement the interface but which
contain no implementation for the default interface will then automatically get the default method implementation. You mark a
method in an interface as a default method using the default keyword.
75. ... add() adds the given element to the collection, and returns true if the Collection changed as a result of calling the add() method.
76. ... A class that implements the Iterable can be used with the new for-loop. Here is such an example:

List list = new ArrayList();

for(Object o : list){
//do something o;
}
77. ... addAll() adds all elements found in the Collection passed as parameter to the method. The Collection object itself is not added.
Only its elements.
78. ... You can check the size of a collection using the size() method. By "size" is meant the number of elements in the collection.
79. ... Matching a Java lambda expression against a functional interface is divided into these steps:

Does the interface have only one method?


Does the parameters of the lambda expression match the parameters of the single method?
Does the return type of the lambda expression match the return type of the single method?
If the answer is yes to these three questions, then the given lambda expression is matched successfully against the
interface.
80. ... A Java lambda expression is thus a function which can be created without belonging to any class. A lambda
expression can be passed around as if it was an object and executed on demand.
81. ... Java annotations are typically used for the following purposes:

Compiler instructions
Build-time instructions
Runtime instructions
82. ... an
because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-
write as an atomic operation (unless we're prepared to "miss an update");
83. ... The enum constructor must be either private or package scope (default). You cannot use public or protected
constructors for a Java enum.
84. ... java.util.List interface is a subtype of the java.util.Collection interface. It represents an ordered list of objects, meaning
you can access the elements of a List in a specific order, and by an index too. You can also add the same element
more than once to a List.
85. ... You can obtain an array of all the possible values of a Java enum type by calling its static values() method.
86. ... Let's assume our application, a todo-list, is already running for a while and the user presses a button to create a new
entry in the todo-list. This will result in a button-clicked event in the DOM, which is captured by the DOM-Driver and
forwarded to one of our ActionCreators.

The ActionCreator takes the DOM-event and maps it to an action. Actions are an implementation of the Command
Pattern, i.e. they describe what should be done, but do not modify anything themselves. In our example, we create an
AddToDoItemAction and pass it to the Updater.

The Updater contains the application logic. It keeps a reference to the current state of the application. Every time it
receives an action from one of the ActionCreators, it generates the new state. In our example, if the current state
contains three todo-items and we receive the AddToDoItemAction, the Updater will create a new state that contains
the existing todo-items plus a new one.

The state is passed to the View()-Function, which creates the so-called Virtual DOM. As the name suggests, the Virtual
DOM is not the real DOM, but it is a data-structure that describes how the DOM should look like. The code snippet
above shows an example of a Virtual DOM for a simple <div>. A later article will explain the Virtual DOM and its
advantages in detail.

The Virtual DOM is passed to the DOM-Driver which will update the DOM and wait for the next user input. With this,
the cycle ends.
87. ... remove() removes the given element and returns true if the removed element was present in the Collection, and was
removed. If the element was not present, the remove() method returns false.
88. ... Regardless of what Collection subtype you are using there are a few standard methods to add and remove elements
from a Collection. Adding and removing single elements is done like this:
89. Are object No, object member variables (fields) are stored on the heap along with the object. Therefore, if two threads call a
member method on the same object instance and this method updates object member variables, the method is not thread safe.
variables
thread safe?
90. Are you holding a lock when you access access to a volatile variable never has the potential to block: we're only ever doing a
a synchronized method? simple read or write, so unlike a synchronized block we will never hold on to any lock;
91. Are you holding a lock when you access access to a volatile variable never has the potential to block: we're only ever doing a
a volatile variable? simple read or write, so unlike a synchronized block we will never hold on to any lock;
92. Attempting to synchronize on a null throw a NullPointerException.
object will
93. By general contract, the equals() method reflexive, symmetric, transitive, consistent, and any non-null reference must return false.
in Java must be ..
94. Can you think of a case where you may For instance, if creating a subclass of Thread that can execute more than one Runnable.
have to implement Runnable as well as This is typically the case when implementing a thread pool.
subclass Thread?
95. Can you think of a guarantee to know if a If an object created locally never escapes the method it was created in, it is thread
given object is thread safe? safe.
96. create an array using literals int[] ints2 = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
97. create a new array of strings String[] stringArray = new String[10];
98. cycle a linked list to the right by K steps because K can be larger than N, use K mod N
find the tail node, link it to the head. the new head is then K steps away.
99. Declaring a volatile Java variable means: 1) The value of this variable will never be cached thread-locally: all reads and writes
will go straight to "main memory";
2) Access to the variable acts as though it is enclosed in a synchronized block,
synchronized on itself.
100. Delete a node in a singly linked list in Delete the next node instead: Copy the next node value into the current node, point
O(1) time. next to next.next.
101. Delete the Kth last element from a use 2 iterators, the second is k steps behind the first
singly linked list
102. Describe how a read operation is done Typically, when a CPU needs to access main memory it will read part of main memory
on hardware. into its CPU cache. It may even read part of the cache into its internal registers and
then perform operations on it.
103. Describe how race conditions can occur. If two or more threads share an object, and more than one thread updates variables in
that shared object, race conditions may occur.
Solved by Java synchronized block.
104. Describe how write operation is done on When the CPU needs to write the result of a computation back to main memory it will
hardware. flush the value from its internal register to the cache memory, and at some point flush
the value back to main memory.
105. Describe the builder pattern 1) The client gets a builder object.
2) The client calls setter-like methods on the builder object to set each optional
parameter of interest.
3) the client calls a parameterless build method to generate the object, which is
immutable.
106. Describe the contract between hashcode hashCode and equals are closely related :
and equals!
if you override equals, you must override hashCode.
hashCode must generate equal values for equal objects.
equals and hashCode must depend on the same set of "significant" fields.
107. Describe the contract that needs to be 1) if a class overrides equals, it must override hashCode
followed when implementing hashcode. 2) equals and hashCode must use the same set of fields
3) if two objects are equal, then their hashCode values must be equal as well
4) if the object is immutable, then hashCode is a candidate for caching and lazy
initialization
108. Describe the idea behind The system's workers react to events occurring in the system, either received from the outside world or
event driven emitted by other workers.
concurrency!
109. Describe the Java The Java memory model used internally in the JVM divides memory between thread stacks and the
memory model. heap.
110. Describe the Java
memory model

111. Describe the logic that int compareTo(Object o1)


needs to be followed This method compares this object with o1 object and returns a integer. Its value has following meaning
when implementing 1. positive - this object is greater than o1
Comparable 2. zero - this object equals to o1
3. negative - this object is less than o1
112. Describe the logic that int compare(Object o1,Object o2)
needs to be followed This method compares o1 and o2 objects. and returns a integer.Its value has following meaning.
when implementing 1. positive - o1 is greater than o2
Comparator. 2. zero - o1 equals to o2
3. negative - o1 is less than o1
113. Describe the pattern service provider framework:
implemented in JDBC Connection: service interface,
Connection, DriverManager.registerDriver: provider registration API
DriverManager and DriverManager.getConnection: service access API
Driver Driver: service provider interface
114. Describe the problem of If two or more threads are sharing an object, without the proper use of either volatile declarations or
Visibility of Shared synchronization, updates to the shared object made by one thread may not be visible to other threads.
Objects Solved by volatile
115. Describe the purpose of Class whose objects to be sorted do not need to implement this interface. Some third class can
the Comparator implement this interface to sort.
interface:
116. Determine if a singly Use a fast and a slow iterator and check if they meet.
linked list contains a
circle.
117. Explain advantages of In the channel model, workers do not communicate directly with each other. Instead they publish their
channel vs actor model! messages (events) on different channels. Other workers can then listen for messages on these channels
without the sender knowing who is listening.
118. Explain how Functional All parameters passed to the function are copied, so no entity outside the receiving function can
Parallelism avoids race manipulate the data. This copying is essential to avoiding race conditions on the shared data. This
conditions? makes the function execution similar to an atomic operation. Each function call can be executed
independently of any other function call.
119. Explain loitering When you don't free references to be collected. E.g. In the array implementation of a stack, pop needs
to null the entry for the popped item
120. Explain the actor Each worker is called an actor. Actors can send messages directly to each other. Messages are sent and
model! processed asynchronously. Actors can be used to implement one or more job processing assembly lines,
as described earlier.
121. Explain the channel Workers do not communicate directly with each other. Instead they publish their messages (events) on
model! different channels. Other workers can then listen for messages on these channels without the sender
knowing who is listening.
122. Explain the If workers can be stateful, they have to be sure there are no other threads modify their data. They can
consequences of keep their data in memory, only writing changes back the eventual external systems. A stateful worker can
workers having state. therefore often be faster than a stateless worker.
123. Explain the They can be implemented without having to think about all the concurrency problems that may arise from
consequences of concurrent access to shared state. This makes it much easier to implement workers. You implement a
workers NOT sharing worker as if it was the only thread performing that work - essentially a singlethreaded implementation.
state with each other!
124. Explain the the service 1) a service interface, which providers implement;
provider framework 2) a provider registration API, which the system uses to register implementations, giving clients access to
components them
3) a service access API, which clients use to obtain an instance of the service
4) optionally, a service provider interface, which providers implement to create instances of their service
implementation. In the absence of a service provider interface, implementations are registered by class
name and instantiated reflectively.
125. Give an example of a As soon as a thread needs to first read the value of a volatile variable, and based on that value generate
race condition when a new value for the shared volatile variable, a volatile variable is no longer enough to guarantee correct
using a volatile visibility. The short time gap in between the reading of the volatile variable and the writing of its new
variable. value, creates an race condition where multiple threads might read the same value of the volatile variable,
generate a new value for the variable, and when writing the value back to main memory - overwrite each
other's values.
126. Here's a string with I'd XOR them.
numbers from 1-250 in
random order, but it's
missing one number.
How will you find the
missed number?
127. How can a thread share One thread may pass a copy of a primitive variable to another thread, but it cannot share the primitive
a variable with another? local variable itself.
128. How can Double- By limiting synchronization to the rare case of computing the field's value or constructing a new instance
checked locking for the field to reference and by foregoing synchronization during the common case of retrieving an
improve performance? already-created instance or value.
129. How can Functional When each function call can be executed independently, each function call can be executed on separate
Parallelism be CPUs. That means, that an algorithm implemented functionally can be executed in parallel, on multiple
performant? CPUs.
130. How can static factory If HashMap provided this generic static factory:
methods reduce the public static <K, V> HashMap<K, V> newInstance() {
verbosity of creating return new HashMap<K, V>();
parameterized type }
instances? Then instead of writing:
Map<String, List<String>> m = new HashMap<String, List<String>>();
we could write this:
Map<String, List<String>> m = HashMap.newInstance();
131. How can you also ~x + 1
declare -x bitwise?
132. How can you assign a specific value to public static void Arrays.fill
each element of an array or subarray?
133. How can you avoid race conditions? By proper thread synchronization in critical sections.
134. How can you check whether a tree is a ...
valid binary tree or not?
135. How can you compare arrays? Arrays.equals : two arrays are equal if they contain the same elements in the same order
136. How can you create a duplicate of an Arrays.copyOf copies until a given length
array?
137. How can you create a duplicate of an Arrays.copyOfRange
array range?
138. How can you create an immutable Set a value in the constructor and expose only a getter.
object?
139. How can you find a value fast in a Arrays.binarysearch works on all primitives and on objects using a comparator
sorted array?
140. How can you isolate the rightmost 0- invert number AND (number + 1)
bit?
141. How can you perform operations on Operate and create a new immutable object.
an immutable object?
142. How can you prevent race conditions? Make sure that the critical section is executed as an atomic instruction. So that when a
thread is executing it, no other can execute it until the first thread has left the critical
section.
143. How can you return only 1 or 0 for the number & ( - number)
rightmost 1Bit value?
144. How can you right propagate the number OR (number - 1), does not work for 0
rightmost 1-bit?
145. How can you set the n-th bit Shift n times to the left and OR
146. How can you sort an array using Arrays.parallelSort usesmergesort and ForkJoin common pool to execute any parallel
parallel tasks tasks. works with all primitive types and comparables
147. how can you sort a range of an array Arrays.sort(int[] a, int fromIndex, int toIndex)
in-place? works with all primitive types and comparables
148. How can you sort with different rules use a comparator:
on the same array?
149. How can you toggle the nth Bit? Shift n times to the left and XOR
150. How can you transform a List into an Collections.toArray
array?
151. How can you transform an array into a Arrays.asList
List?
152. How can you turn off the rightmost AND with (number - 1)
1Bit?
153. How can you turn on the rightmost 0- number OR (number + 1)
bit.
154. How can you unset the nth bit Shift n times to the left and invert, then AND
155. how Do you calculate the reminder of int remainder = 100 % 9;
100 / 9 ?
156. How do you check if a number is check if number AND 1 is 0
even?
157. How do you clone an object? MyClone a = (MyClone) c.clone()
- TypeCast is nessesary.
- handle CloneNotSupportedException
158. How do you create a Thread? 1) Extend Thread (java.lang.Thread)
2) Implement Runnable (java.lang.Runnable)
159. How do you make an object serializable? The class must implement the
java.io.Serializable interface
160. How do you recognize overflow in two complement? Adding 2 positive results in negative and vice
versa
161. How do you test if the n-th bit is set? Shift n times to the right and then AND
162. How do you use Comparable on a collection? Collections.sort(List)
Here objects will be sorted on the basis of
CompareTo method
163. How do you use java collections when need a stack? Deque <T> stack = new LinkedList<T>()
164. How is the comparable interface implemented? public interface Comparable<T>{
int compareTo(T o) {
return 1; //if this > that
return 0; //if this == that
return -1; //if this < that
}
}
165. How is the intrinsic lock used? Methods declared as synchronized and blocks
that synchronize on the this reference both use
the object as monitor (that is, its intrinsic lock)
166. How to use Comparator on a collection? Collections.sort(List, Comparator)
Here objects will be sorted on the basis of
Compare method in Comparator
167. How would you implement the natural ordering of an entity? Comparable interface: Class whose objects to
be sorted must implement this interface
168. How would you name a static factory method that is like getInstance, but used get<Type>
when the factory method is in a different class. Type indicates the type of
object returned by the factory method.
169. How would you name a static factory method that is like new Instance, but new<Type>
used when the factory method is in a different class. <Type> indicates the type
of object returned by the factory method.
170. How would you name a static factory method that is used for type valueOf(..) or of(..)
conversion?
171. How would you name a static factory method that returns an instance that is getInstance
described by the parameters but cannot be said to have the same value.
172. How would you name a static factory method that returns an instance that is newInstance
described by the parameters but cannot be said to have the same value when
it guarantees that each instance returned is distinct from all others?
173. If you overwrite clone(), which 3 rules must this method obey? 1) the new object should be new: memory
address should differ
2) Both should be an object of the same class
3) Both should be in the same state:
a.clone().equals(a) == true
174. In which situation would you not When we want to read-update-write as an atomic operation (unless we're prepared to "miss an
use volatile? update"); Accessing a volatile variable never holds a lock.
175. Java object serialization is Java object serialization (writing) is done with the ObjectOutputStream and deserialization
performed using which classes? (reading) is done with the ObjectInputStream.
176. List the steps to implement 1) Use this == that to check reference equality
equals 2) Use instanceof to test for correct argument type
3) Cast the argument to the correct type
4) Compare significant fields for equality
177. May a primitive variable may be Volatile, but not synchronized.
declared volatile or
synchronized?
178. May a volatile variable that is an Yes! (because you're effectively synchronizing on the reference, not the actual object).
object reference be null?
179. Name an advantage of an object's if an object is immutable, then hashCode is a candidate for caching and lazy initialization
immutability for collections
180. Name integer types that will Java integer types (byte, short, int and long)
truncate division.
181. Name some advantages of event No shared state between workers
driven models!
182. Name some Concurrency Models Parallel Workers
183. Name some positive examples of 1) group related methods on primitive values or arrays, in the manner of java.lang.Math or
a non-instantiable class java.util.Arrays.
2) group static methods, including factory methods, for objects that implement a particular
interface, in the manner of java.util.Collections.
3) group methods on a final class, instead of extending the class.
184. Name the consequences of - The class cannot be instantiated.
creating only a private default - prevents the class from being subclassed: All constructors must invoke a superclass
constructor. constructor, explicitly or implicitly, and a subclass would have no accessible superclass
constructor to invoke.
185. The natural ordering for a class C if and only if this.compareTo(that) == 0 has the same boolean value as this.equals(that) for
is said to be consistent with every this and that of class C.
equals ...
186. An object's member variables are heap along with the object itself. That is true both when the member variable is of a primitive
stored on the .. type, and if it is a reference to an object.
187. Objects on the heap can be all threads that have a reference to the object. When a thread has access to an object, it can
accessed by.. also get access to that object's member variables.
188. Parallel Workers Advantages it is easy to understand. To increase the parallelization of the application you just add more
workers.
189. Parallel - The shared workers often need access to some kind of shared data, either in memory or in a shared database.
Workers That creates complexity. Threads need to avoid race conditions, deadlock and many other shared state concurrency
Disadvantages problems.
- Part of the parallelization is lost when threads are waiting for each other when accessing the shared data
structures. Many concurrent data structures are blocking, leading to contention and eventually serialization.
- Shared state can be modified by other threads in the system. Therefore workers must re-read the state every time it
needs it, to make sure it is working on the latest copy. This is true no matter whether the shared state is kept in
memory or in an external database. A worker that does not keep state internally (but re-reads it every time it is
needed) is called stateless . Re-reading data every time you need it can get slow. Especially if the state is stored in
an external database.
190. Race multiple threads are accessing the same resource, and one or more of the threads write to the resource. If multiple
conditions threads read the same resource race conditions do not occur.
occur only if
...
191. remove remove all successive nodes that have the same element.
duplicates Time analysis here is amortized O(n).
from a sorted
list
192. shared objects making sure that these objects are never updated by making them immutable.
can be made
thread safe by
..
193. Sketch the public interface Service {}
components public interface Provider {
of the service Service newService();
provider }
framework
public class Services {
private Services() { } // Prevents instantiation (Item 4)

// Maps service names to services


private static final Map<String, Provider> providers =
new ConcurrentHashMap<String, Provider>();
public static final String DEFAULT_PROVIDER_NAME = "<def>";

// Provider registration API


public static void registerDefaultProvider(Provider p) {
registerProvider(DEFAULT_PROVIDER_NAME, p);
}
public static void registerProvider(String name, Provider p){
providers.put(name, p);
}

// Service access API


public static Service newInstance() {
return newInstance(DEFAULT_PROVIDER_NAME);
}
public static Service newInstance(String name) {
Provider p = providers.get(name);
if (p == null)
throw new IllegalArgumentException(
"No provider registered with name: " + name);
return p.newService();
}
}
194. Static class heap along with the class definition.
variables are also
stored on the..
195. Take two cycle free The lists would have the same tail element.
singly linked lists
and determine if
there is an element
that belongs to
both.
196. Take two posibly ...
cyclic singly linked
lists and determine
if there is an
element that
belongs to both.
197. two ways to method synchronization and block synchronization
synchronize access
to shared mutable
variables:
198. volatile is used to a variable's value will be modified by different threads.
indicate that
199. what algorithm is An improved quicksort with average nlog(n) runtime
Arrays.sort?
200. What are 1) they have names
advantages of static 2) they are not required to create a new object
factory methods 3) they can return an object of any subtype of their return type
over constructors? 4) they reduce the verbosity of creating parameterized type instances
201. What are cache The values stored in the cache memory is typically flushed back to main memory when the CPU needs to
lines? store something else in the cache memory. The CPU cache can have data written to part of its memory at a
time, and flush part of its memory at a time. It does not have to read / write the full cache each time it is
updated. Typically the cache is updated in smaller memory blocks called "cache lines". One or more cache
lines may be read into the cache memory, and one or mor cache lines may be flushed back to main memory
again.
202. What are the Implementing Runnable handing an instance of the implementation to a Thread instance is easy with
advantages of Threadpools
implementing
Runnable or
extending Thread?
203. What can you use cumulate values in an array
Arrays.parallelPrefix
for?
204. What does assertTrue( a.equals(b) == a.equals(b) );
consistent mean?
205. What does It is a third concurrency model. Functions can be seen as "agents" or "actors" that send messages to each
Functional other (call each other).
Parallelism mean?
206. What does reflexive assertTrue( a.equals(a) );
mean?
207. What does assertTrue( a.equals(b) == b.equals(a) );
symmetic mean?
208. What does thread safe Code that is safe to call by multiple threads simultaneously
mean?
209. What does transitive if ( a.equals(b) && b.equals(c) ) {
mean? assertTrue( a.equals(c) );
}
210. What do you need to It is critical that
consider when creating - the build method check these invariants.
invariants for a class - invariants are checked after copying the parameters from the builder to the object
using a builder? - invariants are checked on the object fields rather than the builder fields.
- If any invariants are violated, the build method should throw an IllegalStateException
211. What exactly is An application is making progress on more than one task at the same time (concurrently). It does not
concurrency? completely finish one task before it begins the next.
212. What exactly is Application splits its tasks up into smaller subtasks which can be processed in parallel, for instance on
parallelism? multiple CPUs at the exact same time.
213. What is ~0 bitwise? 0
214. What is -1 in twos 1111 1111
complement?
215. What is a critical A section of code that is executed by multiple threads and where the sequence of execution for the
section? threads makes a difference in the result
216. What is a marker A Marker interface, has no method.
interface? Serializable, Clonable are marker interfaces.
217. What is a race When the result of multiple threads executing a critical section may differ depending on the sequence in
condition? which the threads execute.
218. What is Context When a CPU switches from executing one thread to executing another, the CPU needs to save the local
Switching Overhead data, program pointer etc. of the current thread, and load the local data, program pointer etc. of the next
thread to execute. This switch is called a "context switch". The CPU switches from executing in the context
of one thread to executing in the context of another.

Context switching isn't cheap. You don't want to switch between threads more than necessary.
219. What is Double- To reduce the overhead of acquiring a lock by first testing the locking criterion without actually acquiring
Checked Locking? the lock.
220. What is escape escape analysis is a method for determining the dynamic scope of pointers - where in the program a
analysis? pointer can be accessed.
221. What is important to - the builder's setter methods return the builder itself so that invocations can be chained
remember when - the created object should be immutable
creating a builder? - the builder is a static member class of the class it builds.
222. What is non-blocking ...
IO?
223. What is same- A concurrency model where a single-threaded systems are scaled out to N single-threaded systems. The
threading? result is N single-threaded systems running in parallel.
224. What is In addition to implementing the Serializable interface, a class intended for serialization should also
serialVersionUID? contain a private static final long variable named serialVersionUID.
The serialVersionUID variable is used by Java's object serialization API to determine if a deserialized
object was serialized (written) with the same version of the class, as it is now attempting to deserialize it
into.
If you make changes to the class that affect serialization, you should also change its serialVersionUID
value.
225. What is the difference The static factory method Boolean.valueOf(String) is almost always preferable to the constructor
between Boolean(String). The constructor creates a new object each time it's called, while the static factory
A) Boolean.valueOf(String) method is never required to do so and won't in practice. The static factory method can work with a
B) new Boolean(String) pool of immutable objects.
226. What is the difference A creates a new String instance each time it is executed, and none of those object creations is
between necessary. The argument to the String constructor ("stringette") is itself a String instance, functionally
A) String s = new identical to all of the objects created by the constructor.
String("stringette"); B uses a single String instance, rather than creating a new one each time it is executed. Furthermore, it
and is guaranteed that the object will be reused by any other code running in the same virtual machine that
B) String s = "stringette"; happens to contain the same string literal.
227. What is the difference Nested classes that are declared static are called static nested classes. Non-static nested classes are
between static nested and called inner classes.
inner classes?
228. What is the ...
ForkAndJoinPool?
229. What is the Holder Class Solution to Singleton with the initialize-on-demand, holder class idiom that implicitly incorporates lazy
Idiom? initialization by declaring a static variable within a static Holder inner class:
final class Foo {
// Lazy initialization
private static class Holder {
static Helper helper = new Helper();
}

public static Helper getInstance() {


return Holder.helper;
}
}
230. What is the implication for Objects which implement Comparable in java can be used as keys without implementing any other
TreeMap or TreeSet interface.
231. What is the implication of If any class implements the comparable interface then collection of that object can be sorted
implementing comparable automatically using Collection.sort() or Arrays.sort()
for collections and arrays
alike?
232. What is the largest ...
number binary
representation in a two
complement?
233. What is the main classes without public or protected constructors cannot be subclassed.For example, it is impossible
disadvantage of providing to subclass any of the convenience implementation classes in the Collections Framework. Arguably
only static factory this can be a blessing in disguise, as it encourages programmers to use composition instead of
methods? inheritance.
234. What is the most common To call the run() method of the Thread instead of start(). in that case, the run() method is executed by
mistake when starting a the thread that created the thread.
thread?
235. What is the parallel A delegator distributes the incoming jobs to different workers. Each worker completes the full job. The
worker concurrency workers work in parallel, running in different threads, and possibly on different CPUs.
model ?
236. What is the private This idiom uses the intrinsic lock associated with the instance of a private final java.lang.Object declared
lock object idiom? within the class instead of the intrinsic lock of the object itself. This idiom requires the use of synchronized
blocks within the class's methods rather than the use of synchronized methods. Lock contention between the
class's methods is prevented.
237. What is the range of -128 to 127
byte
238. What is the range of -2,1 billion to 2,1billion
int?
239. What is the range of -32,768 to 32,767
short?
240. What is the result: ...
Car car = new Car();

boolean isVehicle =
car instanceof
Vehicle;
241. What is the role of Each thread running in the Java virtual machine has its own thread stack. A thread can only access it's own
the thread stack? thread stack.
242. What is the size of 8 bits
byte?
243. What is the size of 16 bits
char?
244. what is the size of 64 bits
double?
245. what is the size of 32 bits
float?
246. What is the size of 32 bits
int?
247. what is the size of 64 bits
long?
248. What is the size of 16 bits
short?
249. What is the smallest ...
number binary
representation in two
complement?
250. What is the Thread If a resource is created, used and disposed within
Control Escape Rule the control of the same thread,
and never escapes the control of this thread,
the use of that resource is thread safe.
251. What is the use of parallel streams which can help you parallelize the iteration of large collections.
Streams in Java 8?
252. What is the "Visibility The problem with threads not seeing the latest value of a variable because it has not yet been written back
Problem"? to main memory by another thread, is called a "visibility" problem. The updates of one thread are not visible
to other threads.
Solution: By declaring the counter variable volatile all writes to the counter variable will be written back to
main memory immediately. Also, all reads of the counter variable will be read directly from main memory.
253. What is the volatile Happens-Before If Thread A writes to a volatile variable and Thread B subsequently reads the same
Guarantee? volatile variable, then all variables visible to Thread A before writing the volatile
variable, will also be visible to Thread B after it has read the volatile variable.
Instructions before and after can be reordered, but the volatile read or write cannot
be mixed with these instructions. Whatever instructions follow a read or write of a
volatile variable are guaranteed to happen after the read or write.
254. What is the volatile Visibility Guarantee The Java volatile keyword guarantees visibility of changes to variables across
threads.
255. What it the first thing that happens after The browser parses the URL to find the protocol, host, port, and path.
you enter a URL in the browser and hit
enter?
256. What kind of information is contained on - all objects created in your Java application, regardless of what thread created the
the heap? object.
- This includes the object versions of the primitive types (e.g. Byte, Integer, Long
etc.).
- It does not matter if an object was created and assigned to a local variable, or
created as a member variable of another object, the object is still stored on the
heap.
257. What kind of information is held on the - all methods the thread has called to reach the current point of execution.
thread stack? - all local variables for all methods on the call stack
258. When fetching a URL in a browser, what To reach the host, it first needs to translate the human readable host into an IP
happens after the browser forms an HTTP number, and it does this by doing a DNS lookup on the host.
request.
259. When fetching a URL in a browser, what It forms a HTTP request.
happens after the browser parses the URL
to find the protocol, host, port, and path?
260. When fetching a URL in a browser, what Then a socket needs to be opened from the user's computer to that IP number, on
happens after the DNS lookup? the port specified (most often port 80 (http) or 433(https))
261. When fetching a URL in a browser, what New requests are made to the server for each new resource that is found in the
happens after the DOM tree is built in the HTML source (typically images, style sheets, and JavaScript files). Go back to step 3
browser? and repeat for each resource.
262. When fetching a URL in a browser, what The browser receives the response, and parses the HTML (which with 95% probability
happens after the host has formed the is broken) in the response
response? A DOM tree is built out of the broken HTML.
263. When fetching a URL in a browser, what The software configured to listen to that port processes the request and forms a
happens after the HTTP request is sent to response.
the host?
264. When fetching a URL in a browser, what When a connection is open, the HTTP request is sent to the host.
happens after the socket is opened?
265. When implementing equals, how do you : use Arrays.equals
compare array fields
266. When implementing equals, how do you convert to long using Double.doubleToLongBits, then use ==
compare doubles
267. When implementing equals, how do you type-safe enumerations : use either equals or == (they amount to the same thing, in
compare enums? this case)
268. When implementing equals, how do you convert to int using Float.floatToIntBits, then use ==
compare float
269. When implementing equals, how do you object fields, including collections : use equals
compare objects?
270. When implementing equals, how do you use both == and equals
compare possibly-null objects?
271. When implementing equals, how do you use ==
compare primitive fields other than float or
double
272. When is a function pure? The outcome of a pure function depends only on the input parameters and they do
not have any side effects.
273. When is volatile Enough? n case only one thread reads and writes the value of a volatile variable and other
threads only read the variable, then the reading threads are guaranteed to see the
latest value written to the volatile variable. Without making the variable volatile,
this would not be guaranteed.

The volatile keyword is guaranteed to work on 32 bit and 64 variables.


274. When multithreading, local primitive In each thread's own stack. That means that local variables are never shared
variables are stored .. between threads. That also means that all local primitive variables are thread safe.
275. When objects and variables can be stored in Visibility of thread updates (writes) to shared variables.
various different memory areas in the Race conditions when reading, checking and writing shared variables.
computer, certain problems may occur. The
two main problems are:
276. Where are heap and thread stack located in On the hardware, both the thread stack and the heap are located in main memory.
hardware? Parts of the thread stacks and heap may sometimes be present in CPU caches and
in internal CPU registers.
277. Where is the Math class located? java.lang.Math
278. Which concurrency model is used by Each worker only performs a part of the full job. When that part is finished the
reactive or event driven systems worker forwards the job to the next worker. Each worker is running in its own
thread, and shares no state with other workers. This is also sometimes referred to
as a shared nothing concurrency model.
They are usually design to use non-blocking IO.
279. Which constructs can also be achieve thread Locks over critical sections or atomic variables like
synchronization? java.util.concurrent.atomic.AtomicInteger.
280. Which kinds of variables are fully stored on All local variables of primitive types ( boolean, byte, short, char, int, long, float,
the thread stack? double) are fully stored on the thread stack and are thus not visible to other
threads.
281. Which package contains ForkAndJoinPool? java.util.concurrent
282. which package is Arrays ? java.util.Arrays
283. Why can Annotations replace marker Annotations can convey metadata about the class to its consumers without
interfaces? creating a separate type for it. Annotations let you pass information to classes that
"consume" it.
284. Why do we need to implement the Clonable At runtime it would throw the CloneNotSupportedException if we don't implement
interface? the Cloneable interface. A class implements the Cloneable interface to indicate to
the Object.clone() method that it is legal for that method to make a field-for-field
copy of instances of that class.
285. Why would a pure function be better To test a pure function, it is sufficient to create the input parameter, run the "function
testable? under test" and compare the outcome. No mockups, no dependency injection, no
complex setup, and no other techniques are necessary that take the fun out of
testing.
286. Why would you avoid An adapter is an object that delegates to a backing object, providing an alternative interface to the
creating more than one backing object. Because an adapter has no state beyond that of its backing object, there's no need to
adapter object per create more than one instance of a given adapter to a given object.
backend? For example, the keySet method of the Map interface returns a Set view of the Map object, consisting of
all the keys in the map. Naively, it would seem that every call to keySet would have to create a new Set
instance, but every call to keySet on a given Map object may return the same Set instance.
287. Would a local variable be - primitive type, it is totally kept on the thread stack
stored on heap or stack? - reference to an object. In that case the reference (the local variable) is stored on the thread stack, but
the object itself if stored on the heap.
288. Write a method that @Override
compares Country public int compareTo(Object arg0) {
objects. Country country=(Country) arg0;
return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
}

Vous aimerez peut-être aussi