Section 1

Preview this deck

How can you find a value fast in a sorted array?

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (289)

Section 1

(50 cards)

How can you find a value fast in a sorted array?

Front

Arrays.binarysearch works on all primitives and on objects using a comparator

Back

How can you transform a List into an array?

Front

Collections.toArray

Back

what algorithm is Arrays.sort?

Front

An improved quicksort with average nlog(n) runtime

Back

how can you sort a range of an array in-place?

Front

Arrays.sort(int[] a, int fromIndex, int toIndex) works with all primitive types and comparables

Back

what is the size of double?

Front

64 bits

Back

What is ~0 bitwise?

Front

0

Back

What is the smallest number binary representation in two complement?

Front

...

Back

Why do we need to implement the Clonable interface?

Front

At runtime it would throw the CloneNotSupportedException if we don't implement 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.

Back

What is the size of byte?

Front

8 bits

Back

How can you transform an array into a List?

Front

Arrays.asList

Back

How can you turn off the rightmost 1Bit?

Front

AND with (number - 1)

Back

How can you create a duplicate of an array?

Front

Arrays.copyOf copies until a given length

Back

What is the range of short?

Front

-32,768 to 32,767

Back

How do you test if the n-th bit is set?

Front

Shift n times to the right and then AND

Back

What is the size of short?

Front

16 bits

Back

Why can Annotations replace marker interfaces?

Front

Annotations can convey metadata about the class to its consumers without creating a separate type for it. Annotations let you pass information to classes that "consume" it.

Back

How is the comparable interface implemented?

Front

public interface Comparable<T>{ int compareTo(T o) { return 1; //if this > that return 0; //if this == that return -1; //if this < that } }

Back

What can you use Arrays.parallelPrefix for?

Front

cumulate values in an array

Back

What is a marker interface?

Front

A Marker interface, has no method. Serializable, Clonable are marker interfaces.

Back

How can you sort an array using parallel tasks

Front

Arrays.parallelSort usesmergesort and ForkJoin common pool to execute any parallel tasks. works with all primitive types and comparables

Back

How can you turn on the rightmost 0-bit.

Front

number OR (number + 1)

Back

What is the size of int?

Front

32 bits

Back

How can you isolate the rightmost 0-bit?

Front

invert number AND (number + 1)

Back

How can you create a duplicate of an array range?

Front

Arrays.copyOfRange

Back

How can you return only 1 or 0 for the rightmost 1Bit value?

Front

number & ( - number)

Back

How do you recognize overflow in two complement?

Front

Adding 2 positive results in negative and vice versa

Back

How do you clone an object?

Front

MyClone a = (MyClone) c.clone() - TypeCast is nessesary. - handle CloneNotSupportedException

Back

What is the size of char?

Front

16 bits

Back

What is the range of byte

Front

-128 to 127

Back

How can you assign a specific value to each element of an array or subarray?

Front

public static void Arrays.fill

Back

what is the size of long?

Front

64 bits

Back

How can you sort with different rules on the same array?

Front

use a comparator:

Back

How do you make an object serializable?

Front

The class must implement the java.io.Serializable interface

Back

What is escape analysis?

Front

escape analysis is a method for determining the dynamic scope of pointers - where in the program a pointer can be accessed.

Back

How can you set the n-th bit

Front

Shift n times to the left and OR

Back

what is the size of float?

Front

32 bits

Back

What is -1 in twos complement?

Front

1111 1111

Back

How can you compare arrays?

Front

Arrays.equals : two arrays are equal if they contain the same elements in the same order

Back

What is serialVersionUID?

Front

In addition to implementing the Serializable interface, a class intended for serialization should also 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.

Back

How do you check if a number is even?

Front

check if number AND 1 is 0

Back

How can you also declare -x bitwise?

Front

~x + 1

Back

How can Double-checked locking improve performance?

Front

By limiting synchronization to the rare case of computing the field's value or constructing a new instance for the field to reference and by foregoing synchronization during the common case of retrieving an already-created instance or value.

Back

How can you toggle the nth Bit?

Front

Shift n times to the left and XOR

Back

What is Double-Checked Locking?

Front

To reduce the overhead of acquiring a lock by first testing the locking criterion without actually acquiring the lock.

Back

What is the largest number binary representation in a two complement?

Front

...

Back

If you overwrite clone(), which 3 rules must this method obey?

Front

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

Back

How can you right propagate the rightmost 1-bit?

Front

number OR (number - 1), does not work for 0

Back

How can you unset the nth bit

Front

Shift n times to the left and invert, then AND

Back

What is the range of int?

Front

-2,1 billion to 2,1billion

Back

Java object serialization is performed using which classes?

Front

Java object serialization (writing) is done with the ObjectOutputStream and deserialization (reading) is done with the ObjectInputStream.

Back

Section 2

(50 cards)

How can Functional Parallelism be performant?

Front

When each function call can be executed independently, each function call can be executed on separate CPUs. That means, that an algorithm implemented functionally can be executed in parallel, on multiple CPUs.

Back

Attempting to synchronize on a null object will

Front

throw a NullPointerException.

Back

Explain the channel model!

Front

Workers do not communicate directly with each other. Instead they publish their messages (events) on different channels. Other workers can then listen for messages on these channels without the sender knowing who is listening.

Back

Which concurrency model is used by reactive or event driven systems

Front

Each worker only performs a part of the full job. When that part is finished the 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.

Back

What exactly is concurrency?

Front

An application is making progress on more than one task at the same time (concurrently). It does not completely finish one task before it begins the next.

Back

Describe the idea behind event driven concurrency!

Front

The system's workers react to events occurring in the system, either received from the outside world or emitted by other workers.

Back

Are you holding a lock when you access a volatile variable?

Front

access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;

Back

What is the most common mistake when starting a thread?

Front

To call the run() method of the Thread instead of start(). in that case, the run() method is executed by the thread that created the thread.

Back

What exactly is parallelism?

Front

Application splits its tasks up into smaller subtasks which can be processed in parallel, for instance on multiple CPUs at the exact same time.

Back

What is the volatile Visibility Guarantee

Front

The Java volatile keyword guarantees visibility of changes to variables across threads.

Back

What is the use of Streams in Java 8?

Front

parallel streams which can help you parallelize the iteration of large collections.

Back

What is a race condition?

Front

When the result of multiple threads executing a critical section may differ depending on the sequence in which the threads execute.

Back

What is non-blocking IO?

Front

...

Back

May a primitive variable may be declared volatile or synchronized?

Front

Volatile, but not synchronized.

Back

How can you avoid race conditions?

Front

By proper thread synchronization in critical sections.

Back

Are you holding a lock when you access a synchronized method?

Front

access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;

Back

When is volatile Enough?

Front

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.

Back

Parallel Workers Disadvantages

Front

- The shared workers often need access to some kind of shared data, either in memory or in a shared database. That creates complexity. Threads need to avoid race conditions, deadlock and many other shared state concurrency 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.

Back

...

Front

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");

Back

Can you think of a case where you may have to implement Runnable as well as subclass Thread?

Front

For instance, if creating a subclass of Thread that can execute more than one Runnable. This is typically the case when implementing a thread pool.

Back

How is the intrinsic lock used?

Front

Methods declared as synchronized and blocks that synchronize on the this reference both use the object as monitor (that is, its intrinsic lock)

Back

What is Context Switching Overhead

Front

When a CPU switches from executing one thread to executing another, the CPU needs to save the local 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.

Back

How do you create a Thread?

Front

1) Extend Thread (java.lang.Thread) 2) Implement Runnable (java.lang.Runnable)

Back

In which situation would you not use volatile?

Front

When we want to read-update-write as an atomic operation (unless we're prepared to "miss an update"); Accessing a volatile variable never holds a lock.

Back

Parallel Workers Advantages

Front

it is easy to understand. To increase the parallelization of the application you just add more workers.

Back

volatile is used to indicate that

Front

a variable's value will be modified by different threads.

Back

Give an example of a race condition when using a volatile variable.

Front

As soon as a thread needs to first read the value of a volatile variable, and based on that value generate a new value for the shared volatile variable, a volatile variable is no longer enough to guarantee correct visibility. The short time gap in between the reading of the volatile variable and the writing of its new 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.

Back

Explain the consequences of workers having state.

Front

If workers can be stateful, they have to be sure there are no other threads modify their data. They can keep their data in memory, only writing changes back the eventual external systems. A stateful worker can therefore often be faster than a stateless worker.

Back

Name some Concurrency Models

Front

Parallel Workers

Back

Explain the actor model!

Front

Each worker is called an actor. Actors can send messages directly to each other. Messages are sent and processed asynchronously. Actors can be used to implement one or more job processing assembly lines, as described earlier.

Back

What does Functional Parallelism mean?

Front

It is a third concurrency model. Functions can be seen as "agents" or "actors" that send messages to each other (call each other).

Back

What is the parallel worker concurrency model ?

Front

A delegator distributes the incoming jobs to different workers. Each worker completes the full job. The workers work in parallel, running in different threads, and possibly on different CPUs.

Back

What is the volatile Happens-Before Guarantee?

Front

If Thread A writes to a volatile variable and Thread B subsequently reads the same 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.

Back

What is the difference between static nested and inner classes?

Front

Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.

Back

Explain how Functional Parallelism avoids race conditions?

Front

All parameters passed to the function are copied, so no entity outside the receiving function can manipulate the data. This copying is essential to avoiding race conditions on the shared data. This makes the function execution similar to an atomic operation. Each function call can be executed independently of any other function call.

Back

What is a critical section?

Front

A section of code that is executed by multiple threads and where the sequence of execution for the threads makes a difference in the result

Back

Explain advantages of channel vs actor model!

Front

In the channel model, workers do not communicate directly with each other. Instead they publish their messages (events) on different channels. Other workers can then listen for messages on these channels without the sender knowing who is listening.

Back

What are the advantages of implementing Runnable or extending Thread?

Front

Implementing Runnable handing an instance of the implementation to a Thread instance is easy with Threadpools

Back

Name some advantages of event driven models!

Front

No shared state between workers

Back

two ways to synchronize access to shared mutable variables:

Front

method synchronization and block synchronization

Back

What is the Holder Class Idiom?

Front

Solution to Singleton with the initialize-on-demand, holder class idiom that implicitly incorporates lazy 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; } }

Back

Which package contains ForkAndJoinPool?

Front

java.util.concurrent

Back

May a volatile variable that is an object reference be null?

Front

Yes! (because you're effectively synchronizing on the reference, not the actual object).

Back

What is the ForkAndJoinPool?

Front

...

Back

What is same-threading?

Front

A concurrency model where a single-threaded systems are scaled out to N single-threaded systems. The result is N single-threaded systems running in parallel.

Back

What is the private lock object idiom?

Front

This idiom uses the intrinsic lock associated with the instance of a private final java.lang.Object declared 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.

Back

Declaring a volatile Java variable means:

Front

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.

Back

Explain the consequences of workers NOT sharing state with each other!

Front

They can be implemented without having to think about all the concurrency problems that may arise from concurrent access to shared state. This makes it much easier to implement workers. You implement a worker as if it was the only thread performing that work - essentially a singlethreaded implementation.

Back

How can you prevent race conditions?

Front

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.

Back

What is the "Visibility Problem"?

Front

The problem with threads not seeing the latest value of a variable because it has not yet been written back 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.

Back

Section 3

(50 cards)

Name integer types that will truncate division.

Front

Java integer types (byte, short, int and long)

Back

Race conditions occur only if ...

Front

multiple threads are accessing the same resource, and one or more of the threads write to the resource. If multiple threads read the same resource race conditions do not occur.

Back

Which constructs can also be achieve thread synchronization?

Front

Locks over critical sections or atomic variables like java.util.concurrent.atomic.AtomicInteger.

Back

...

Front

The object versions of the primitive data types are immutable.

Back

...

Front

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

Back

...

Front

The Math.min() method returns the smallest of two values passed to it as parameter.

Back

Describe the Java memory model

Front

Back

...

Front

You can convert an Java array of primitive types to a String using the Arrays.toString() method. H

Back

...

Front

The Math.round() method rounds a float or double to the nearest integer using normal math round rules .

Back

What does thread safe mean?

Front

Code that is safe to call by multiple threads simultaneously

Back

Are object member variables thread safe?

Front

No, object member variables (fields) are stored on the heap along with the object. Therefore, if two threads call a method on the same object instance and this method updates object member variables, the method is not thread safe.

Back

An object's member variables are stored on the ..

Front

heap along with the object itself. That is true both when the member variable is of a primitive type, and if it is a reference to an object.

Back

...

Front

The Math.floor() function rounds a floating point value down to the nearest integer value.

Back

How can a thread share a variable with another?

Front

One thread may pass a copy of a primitive variable to another thread, but it cannot share the primitive local variable itself.

Back

When multithreading, local primitive variables are stored ..

Front

In each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.

Back

...

Front

It is possible to have many different variables reference the same object. This is not possible with primitive data types.

Back

...

Front

You can access the length of an array via its length field

Back

Objects on the heap can be accessed by..

Front

all threads that have a reference to the object. When a thread has access to an object, it can also get access to that object's member variables.

Back

...

Front

The Math.random() method returns a random floating point number between 0 and 1.

Back

How can you perform operations on an immutable object?

Front

Operate and create a new immutable object.

Back

create an array using literals

Front

int[] ints2 = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

Back

...

Front

The Math.abs() function returns the absolute value of the parameter passed to it.

Back

What kind of information is contained on the heap?

Front

- all objects created in your Java application, regardless of what thread created the 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.

Back

How can you create an immutable object?

Front

Set a value in the constructor and expose only a getter.

Back

What are cache lines?

Front

The values stored in the cache memory is typically flushed back to main memory when the CPU needs to 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.

Back

Describe how write operation is done on hardware.

Front

When the CPU needs to write the result of a computation back to main memory it will flush the value from its internal register to the cache memory, and at some point flush the value back to main memory.

Back

Describe the problem of Visibility of Shared Objects

Front

If two or more threads are sharing an object, without the proper use of either volatile declarations or synchronization, updates to the shared object made by one thread may not be visible to other threads. Solved by volatile

Back

Would a local variable be stored on heap or stack?

Front

- primitive type, it is totally kept on the thread 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.

Back

...

Front

The Math.ceil() function rounds a floating point value up to the nearest integer value.

Back

What is the role of the thread stack?

Front

Each thread running in the Java virtual machine has its own thread stack. A thread can only access it's own thread stack.

Back

...

Front

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");

Back

When objects and variables can be stored in various different memory areas in the computer, certain problems may occur. The two main problems are:

Front

Visibility of thread updates (writes) to shared variables. Race conditions when reading, checking and writing shared variables.

Back

Where are heap and thread stack located in hardware?

Front

On the hardware, both the thread stack and the heap are located in main memory. Parts of the thread stacks and heap may sometimes be present in CPU caches and in internal CPU registers.

Back

Describe how a read operation is done on hardware.

Front

Typically, when a CPU needs to access main memory it will read part of main memory into its CPU cache. It may even read part of the cache into its internal registers and then perform operations on it.

Back

shared objects can be made thread safe by ..

Front

making sure that these objects are never updated by making them immutable.

Back

how Do you calculate the reminder of 100 / 9 ?

Front

int remainder = 100 % 9;

Back

...

Front

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.

Back

...

Front

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?

Back

Describe how race conditions can occur.

Front

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.

Back

...

Front

The Math.max() method returns the largest of two values passed to it as parameter.

Back

Which kinds of variables are fully stored on the thread stack?

Front

All local variables of primitive types ( boolean, byte, short, char, int, long, float, double) are fully stored on the thread stack and are thus not visible to other threads.

Back

What is the Thread Control Escape Rule

Front

If a resource is created, used and disposed within the control of the same thread, and never escapes the control of this thread, the use of that resource is thread safe.

Back

Describe the Java memory model.

Front

The Java memory model used internally in the JVM divides memory between thread stacks and the heap.

Back

...

Front

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

Back

...

Front

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.

Back

Where is the Math class located?

Front

java.lang.Math

Back

What kind of information is held on the thread stack?

Front

- all methods the thread has called to reach the current point of execution. - all local variables for all methods on the call stack

Back

Can you think of a guarantee to know if a given object is thread safe?

Front

If an object created locally never escapes the method it was created in, it is thread safe.

Back

Static class variables are also stored on the..

Front

heap along with the class definition.

Back

create a new array of strings

Front

String[] stringArray = new String[10];

Back

Section 4

(50 cards)

...

Front

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.

Back

...

Front

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.

Back

...

Front

The Java String class also has a lastIndexOf() method which finds the last occurrence of a substring.

Back

...

Front

The Java access modifiers private and protected cannot be assigned to a class.

Back

...

Front

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.

Back

...

Front

compareTo() method may not work correctly for Strings in different languages than English. To sort Strings correctly in a specific language, use a Collator.

Back

...

Front

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.

Back

What is the result: Car car = new Car(); boolean isVehicle = car instanceof Vehicle;

Front

...

Back

...

Front

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!

Back

...

Front

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.

Back

...

Front

You can obtain the length of a String using the length() method.

Back

...

Front

The substring() method takes two parameters.

Back

...

Front

You can also get the byte representation of the String method using the getBytes() method. Use the specific charset to do that.

Back

How can you check whether a tree is a valid binary tree or not?

Front

...

Back

...

Front

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.

Back

...

Front

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

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

If the substring is not found within the string, the indexOf() method returns -1;

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

A private constructor can still get called from other constructors, or from static methods in the same class.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

loop over each string in the array: for(String aString : strings) { // }

Back

...

Front

if a constructor is declared protected then only classes in the same package, or subclasses of that class can call that constructor.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

The indexOf() method returns the index of where the first character in the first matching substring is found.

Back

...

Front

Classes cannot be marked with the private access modifier. Therefore the private access modifier is not allowed for classes.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

It is possible to get a character at a certain index in a String using the charAt() method.

Back

...

Front

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.

Back

...

Front

The parameters mean "from - including, to - excluding".

Back

...

Front

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.

Back

...

Front

The default Java access modifier is declared by not writing any access modifier at all.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

When you call a constructor from inside another constructor, you use the this keyword to refer to the constructor

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

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.

Back

...

Front

A final class cannot be extended. In other words, you cannot inherit from a final class in Java.

Back

...

Front

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.

Back

...

Front

The Java String class contains a set of overloaded static methods named valueOf() which can be used to convert a number to a String.

Back

Section 5

(50 cards)

...

Front

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.

Back

...

Front

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.

Back

...

Front

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.

Back

When implementing equals, how do you compare doubles

Front

convert to long using Double.doubleToLongBits, then use ==

Back

When implementing equals, how do you compare float

Front

convert to int using Float.floatToIntBits, then use ==

Back

...

Front

addAll() adds all elements found in the Collection passed as parameter to the method. The Collection object itself is not added. Only its elements.

Back

which package is Arrays ?

Front

java.util.Arrays

Back

...

Front

The different Java nested class types are: Static nested classes Non-static nested classes Local classes Anonymous classes

Back

Describe the contract between hashcode and equals!

Front

hashCode and equals are closely related : 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.

Back

When implementing equals, how do you compare array fields

Front

: use Arrays.equals

Back

Delete a node in a singly linked list in O(1) time.

Front

Delete the next node instead: Copy the next node value into the current node, point next to next.next.

Back

...

Front

In Java nested classes are considered members of their enclosing class.

Back

How do you use Comparable on a collection?

Front

Collections.sort(List) Here objects will be sorted on the basis of CompareTo method

Back

...

Front

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.

Back

...

Front

The enum constructor must be either private or package scope (default). You cannot use public or protected constructors for a Java enum.

Back

...

Front

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; }

Back

Take two cycle free singly linked lists and determine if there is an element that belongs to both.

Front

The lists would have the same tail element.

Back

Here's a string with numbers from 1-250 in random order, but it's missing one number. How will you find the missed number?

Front

I'd XOR them.

Back

...

Front

The Template Method design pattern provides a partial implementation of some process, which subclasses can complete when extending the Template Method base class.

Back

When implementing equals, how do you compare possibly-null objects?

Front

use both == and equals

Back

...

Front

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.

Back

How to use Comparator on a collection?

Front

Collections.sort(List, Comparator) Here objects will be sorted on the basis of Compare method in Comparator

Back

When implementing equals, how do you compare primitive fields other than float or double

Front

use ==

Back

...

Front

You can obtain an array of all the possible values of a Java enum type by calling its static values() method.

Back

What is the implication for TreeMap or TreeSet

Front

Objects which implement Comparable in java can be used as keys without implementing any other interface.

Back

When implementing equals, how do you compare enums?

Front

type-safe enumerations : use either equals or == (they amount to the same thing, in this case)

Back

...

Front

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.

Back

...

Front

The Template Method design pattern provides a partial implementation of some process, which subclasses can complete when extending the Template Method base class.

Back

Why would a pure function be better testable?

Front

To test a pure function, it is sufficient to create the input parameter, run the "function 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.

Back

...

Front

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.

Back

When implementing equals, how do you compare objects?

Front

object fields, including collections : use equals

Back

What is the implication of implementing comparable for collections and arrays alike?

Front

If any class implements the comparable interface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort()

Back

...

Front

You can check the size of a collection using the size() method. By "size" is meant the number of elements in the collection.

Back

...

Front

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.

Back

...

Front

Java annotations are typically used for the following purposes: Compiler instructions Build-time instructions Runtime instructions

Back

Name an advantage of an object's immutability for collections

Front

if an object is immutable, then hashCode is a candidate for caching and lazy initialization

Back

Describe the logic that needs to be followed when implementing Comparable

Front

int compareTo(Object o1) This method compares this object with o1 object and returns a integer. Its value has following meaning 1. positive - this object is greater than o1 2. zero - this object equals to o1 3. negative - this object is less than o1

Back

...

Front

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.

Back

Write a method that compares Country objects.

Front

@Override public int compareTo(Object arg0) { Country country=(Country) arg0; return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ; }

Back

Determine if a singly linked list contains a circle.

Front

Use a fast and a slow iterator and check if they meet.

Back

...

Front

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:

Back

...

Front

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.

Back

...

Front

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.

Back

Take two posibly cyclic singly linked lists and determine if there is an element that belongs to both.

Front

...

Back

Describe the purpose of the Comparator interface:

Front

Class whose objects to be sorted do not need to implement this interface. Some third class can implement this interface to sort.

Back

When is a function pure?

Front

The outcome of a pure function depends only on the input parameters and they do not have any side effects.

Back

...

Front

add() adds the given element to the collection, and returns true if the Collection changed as a result of calling the add() method.

Back

How would you implement the natural ordering of an entity?

Front

Comparable interface: Class whose objects to be sorted must implement this interface

Back

Describe the logic that needs to be followed when implementing Comparator.

Front

int compare(Object o1,Object o2) This method compares o1 and o2 objects. and returns a integer.Its value has following meaning. 1. positive - o1 is greater than o2 2. zero - o1 equals to o2 3. negative - o1 is less than o1

Back

Describe the contract that needs to be followed when implementing hashcode.

Front

1) if a class overrides equals, it must override 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

Back

Section 6

(39 cards)

Name the consequences of creating only a private default constructor.

Front

- The class cannot be instantiated. - prevents the class from being subclassed: All constructors must invoke a superclass constructor, explicitly or implicitly, and a subclass would have no accessible superclass constructor to invoke.

Back

What is important to remember when creating a builder?

Front

- the builder's setter methods return the builder itself so that invocations can be chained - the created object should be immutable - the builder is a static member class of the class it builds.

Back

Explain loitering

Front

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

Back

When fetching a URL in a browser, what happens after the host has formed the response?

Front

The browser receives the response, and parses the HTML (which with 95% probability is broken) in the response A DOM tree is built out of the broken HTML.

Back

The natural ordering for a class C is said to be consistent with equals ...

Front

if and only if this.compareTo(that) == 0 has the same boolean value as this.equals(that) for every this and that of class C.

Back

When fetching a URL in a browser, what happens after the browser parses the URL to find the protocol, host, port, and path?

Front

It forms a HTTP request.

Back

remove duplicates from a sorted list

Front

remove all successive nodes that have the same element. Time analysis here is amortized O(n).

Back

What is the difference between A) Boolean.valueOf(String) B) new Boolean(String)

Front

The static factory method Boolean.valueOf(String) is almost always preferable to the constructor Boolean(String). The constructor creates a new object each time it's called, while the static factory method is never required to do so and won't in practice. The static factory method can work with a pool of immutable objects.

Back

How would you name a static factory method that is used for type conversion?

Front

valueOf(..) or of(..)

Back

cycle a linked list to the right by K steps

Front

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.

Back

When fetching a URL in a browser, what happens after the DOM tree is built in the browser?

Front

New requests are made to the server for each new resource that is found in the HTML source (typically images, style sheets, and JavaScript files). Go back to step 3 and repeat for each resource.

Back

What it the first thing that happens after you enter a URL in the browser and hit enter?

Front

The browser parses the URL to find the protocol, host, port, and path.

Back

By general contract, the equals() method in Java must be ..

Front

reflexive, symmetric, transitive, consistent, and any non-null reference must return false.

Back

When fetching a URL in a browser, what happens after the browser forms an HTTP request.

Front

To reach the host, it first needs to translate the human readable host into an IP number, and it does this by doing a DNS lookup on the host.

Back

How would you name a static factory method that is like new Instance, but used when the factory method is in a different class. <Type> indicates the type of object returned by the factory method.

Front

new<Type>

Back

Delete the Kth last element from a singly linked list

Front

use 2 iterators, the second is k steps behind the first

Back

How do you use java collections when need a stack?

Front

Deque <T> stack = new LinkedList<T>()

Back

How can static factory methods reduce the verbosity of creating parameterized type instances?

Front

If HashMap provided this generic static factory: public static <K, V> HashMap<K, V> newInstance() { return new HashMap<K, V>(); } 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();

Back

What does transitive mean?

Front

if ( a.equals(b) && b.equals(c) ) { assertTrue( a.equals(c) ); }

Back

What is the main disadvantage of providing only static factory methods?

Front

classes without public or protected constructors cannot be subclassed.For example, it is impossible to subclass any of the convenience implementation classes in the Collections Framework. Arguably this can be a blessing in disguise, as it encourages programmers to use composition instead of inheritance.

Back

What are advantages of static factory methods over constructors?

Front

1) they have names 2) they are not required to create a new object 3) they can return an object of any subtype of their return type 4) they reduce the verbosity of creating parameterized type instances

Back

How would you name a static factory method that returns an instance that is described by the parameters but cannot be said to have the same value.

Front

getInstance

Back

What is the difference between A) String s = new String("stringette"); and B) String s = "stringette";

Front

A creates a new String instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor ("stringette") is itself a String instance, functionally identical to all of the objects created by the constructor. B uses a single String instance, rather than creating a new one each time it is executed. Furthermore, it is guaranteed that the object will be reused by any other code running in the same virtual machine that happens to contain the same string literal.

Back

When fetching a URL in a browser, what happens after the DNS lookup?

Front

Then a socket needs to be opened from the user's computer to that IP number, on the port specified (most often port 80 (http) or 433(https))

Back

When fetching a URL in a browser, what happens after the socket is opened?

Front

When a connection is open, the HTTP request is sent to the host.

Back

What does consistent mean?

Front

assertTrue( a.equals(b) == a.equals(b) );

Back

How would you name a static factory method that is like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

Front

get<Type>

Back

What does symmetic mean?

Front

assertTrue( a.equals(b) == b.equals(a) );

Back

Describe the builder pattern

Front

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.

Back

What does reflexive mean?

Front

assertTrue( a.equals(a) );

Back

Describe the pattern implemented in JDBC Connection, DriverManager and Driver

Front

service provider framework: Connection: service interface, DriverManager.registerDriver: provider registration API DriverManager.getConnection: service access API Driver: service provider interface

Back

What do you need to consider when creating invariants for a class using a builder?

Front

It is critical that - the build method check these invariants. - invariants are checked after copying the parameters from the builder to the object - invariants are checked on the object fields rather than the builder fields. - If any invariants are violated, the build method should throw an IllegalStateException

Back

How would you name a static factory method that returns an instance that is 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?

Front

newInstance

Back

Name some positive examples of a non-instantiable class

Front

1) group related methods on primitive values or arrays, in the manner of java.lang.Math or 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.

Back

Explain the the service provider framework components

Front

1) a service interface, which providers implement; 2) a provider registration API, which the system uses to register implementations, giving clients access to 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.

Back

List the steps to implement equals

Front

1) Use this == that to check reference equality 2) Use instanceof to test for correct argument type 3) Cast the argument to the correct type 4) Compare significant fields for equality

Back

When fetching a URL in a browser, what happens after the HTTP request is sent to the host?

Front

The software configured to listen to that port processes the request and forms a response.

Back

Sketch the components of the service provider framework

Front

public interface Service {} public interface Provider { Service newService(); } 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(); } }

Back

Why would you avoid creating more than one adapter object per backend?

Front

An adapter is an object that delegates to a backing object, providing an alternative interface to the backing object. Because an adapter has no state beyond that of its backing object, there's no need to create more than one instance of a given adapter to a given object. 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.

Back