Java Quizlet
Java Quizlet
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:
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:
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:
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:
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
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();
}
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.