Java Study Questions

The following is a study guide for information that any self-proclaimed Java programmer should know.

Questions

Strings

  1. What is the difference between a) String foo = "foo"; and b) String foo = new String("foo");?
    1. a) creates the string in the string pool, b) creates the string on the heap
  2. What is the string pool?
    1. A “pool” of strings stored on the heap. Before Java 7 the pool was in the permanent generation area of the heap. From Java 7 the string pool is stored on the heap to allow for it to be garbage collected.
    2. Its purpose is to save space for the JVM by enabling multiple pointers to the same, immutable, Strings on the heap.
  3. How do you “add” a String to the string pool?
    1. String.intern()
  4. Further Java String study questions.

Comparison and Collections

  1. What is the difference between == and .equals()?
    1. == tests whether or not the two object reference variables refer to the exact same instance of an object.
    2. .equals(T other) tests whether or not the two objects being compared are quantitatively equivalent to each other, but they do not need to be the same object.
    3. == operating on boolean or primitive types compares the value of those primitives to each other similarly to the .equals() method of Objects
  2. What is the relationship between hashCode, equals, and compareTo?
    1. hashCode: a unique identifier for a given object as an int. The business logic for generating such an int can be user defined.
    2. equals: returns a boolean as to whether or not the two objects are equal based on user defined business logic.
    3. compareTo: Comparable interface implementation that allows for the sorting of items with the Collections. util.
    4. All three should be in sync so that an object that equals another should return 0 for compareTo as well as the same hashCode value.
  3. What is the sole member of the Comparable interface? Explain its purpose and use-cases.
    1. compareTo(Object other).
    2. It is similar to hashCode and equals, but not quite. It enables a means of fully ordering objects.
    3. It is the implementation of an algorithm tied to a specific class, and/or child classes, that allows objects to be sorted similar to sorting a database result set on a composite key.
    4. Consistency with equals is highly recommended, but can be modified based on the business logic. If you want to use it in a sorted collection, you must ensure that x.compareTo(y) == 0, if and only if x.equals(y).
    5. It enables:
    6. The sorting of objects in Collections by calling
      1. Collections.sort
      2. Collections.binarySearch
      3. Arrays.sort
      4. Arrays.binarySearch
      5. Using objects as keys in TreeMap
      6. Using objects as elements in TreeSet
  4. How should floats and doubles (primitives) be compared for equality?
    1. Using Double.compare(double, double), and Float.compare(float, float)
  5. How should booleans be compared?
    1. In almost all cases you should NOT use the wrapper Boolean class as it opens up the potential for NullPointerException.
  6. What are the differences between final, finally, finalize (deprecated in Java 17)?
    1. final
      1. final method cannot be overridden
      2. final field once set a value cannot be assigned again
      3. final class cannot be extended. Variables declared outside of and used in an inner anonymous class, must be declared final.
    2. finally.
      1. Part of a try-catch statement. The code in a finally block always executes
      2. What if there is a return statement in a catch, or try?
        1. The finally block will still execute before returning
    3. finalize
      1. A method that invoked on an object just before it is garbage collected. Similar to a destructor in C++.
  7. What is the difference between RuntimeException (and sub-classes) and Exception (and sub-classes)?
    1. You are not required to throw or catch RuntimeExceptions.
  8. Explain the difference between Interfaces and Abstract classes.

Java Specific
NIO
IO
generics
Comparable interface
boolean compareTo(Object o)
int equals(Object o)
int hashCode()
Java 8 specifics

Java Lambdas:

Both approaches have the same effect: a Runnable-implementing object whose run() method is being invoked to print something to the console. Under the hood, however, the Java 8 version is doing a little more than just generating an anonymous class that implements the Runnable interface—some of which has to do with the invoke dynamic bytecode that was introduced in Java 7. We won’t get to that level of detail here, but know that this is more than “just” an anonymous class instance.

From http://www.oracle.com/technetwork/articles/java/architect-lambdas-part1-2080972.html

. Figure out exactly what is meant by the invoke dynamic bytecode that is mentioned above.

Generics

Java Big-O:

           get      add      contains   next   remove   Iterator.remove

Array: O(1) O(1) O(n) O(1) O(1)

ArrayList: O(1) O(1) O(n) O(1) O(1) O(n)
O(n) if
create new

LinkedList: O(n) O(1) O(n) O(1) O(1) O(1)

HashMap: O(1) O(1) O(n/h) [h is table capacity], more
probably is that it is O(1), but O(n/h) is worst

LinkedHashMap: O(1) O(1) O(1)

TreeMap: O(log n) O(log n) O(log n)

ConcurrentH: O(1) O(1) O(h/n)

http://www.leepoint.net/notes-java/algorithms/big-oh/bigoh.html

HashSet: O(1) O(1) O(h/n) [h is table capacity]

LinkedHashSet: O(1) O(1) O(1)

TreeSet: O(log n) O(log n) O(log n)

Type bits ranges
byte 8 -128 – 127
short 16 -32,768 – 32,767
char 16 ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 0 – 65,535 inclusive)
int 32 -2,147,483,648 – 2,147,483,647 (2.147 Billion)
long 64 -9,223,372,036,854,775,808 – 9,223,372,036,854,775,807 (9.223 quintillion)
float 32
double 64

. Formatting output

    . Format specifiers for gen char and numeric syntax: %[argument_index$][flags][width][.precision]conversion

    . Format specifiers for dates and times syntax: %[argument_index$][flags][width]conversion

    . Format specifiers which do not correspond to arguments syntax: %[flags][width]conversion

    . Strings:
            . http://www.homeandlearn.co.uk/java/java_formatted_strings.html

            . Formatting output with leading spaces: |  45foo| -> |45  foo|
                    . String.format("%4sfoo", 45);
                    . String.format("%-4sfoo", 45);

    . Calendar/Dates:
            . Sample data formatting:  String.format("%1$tY-%1$tm-%1$td", new Date())  =  2013-01-22

. Go over regex Pattern.compile(“regex”) syntax

. Basic methods of String and Array

. Basic I/O

. Threading

. Key concept: without synchronization or using a declared volatile variable the Thread doesn’t know that there might be other Threads accessing the variable and it can cache the value of the variable outside of main memory in a register or in it’s local memory, thus causing inconsistency problems.

. Explain “synchronizing cached variables with main memory”: The process by which the locally cached variables in a Threads scope are read and written back to main memory from inside the synchronized block of code. Meaning, the reads and writes to main memory have to happen inside the block of synchronized code in the right order to maintain consistency between Threads.
. common mistake is to allow reads to happen outside of a synchronized block and only synchronize writes. You can still get some problems with this one. see http://www.javamex.com/tutorials/synchronization_concurrency_synchronized2.shtml

. volatile variables:
. a variable’s value will be modified by different threads.
. never be cached thread-locally, all r/w directly to main memory.
. access acts as though it is enclosed in a synchronized block, synchronized on itself.

    . can declare a primitive (instead of synchronizing on an object)
    . can never block
    . not suitable for read-update-write, unless OK with missing and update
    . volatile variable that is null can be null because you are synchronizing on the reference not the actual object

    . When to use:
            . w a variable in one thread and read in another
            . a w does not depend on the current value
                    . or you don't care about missing an update

    . One-off variable in a class instantiated a small number of time, AtomicInteger (or like) clas
    . large number of instances of classes, volatile and access via AtomicReferenceFieldUpdater

. Great articles on multi-threading in Java:
http://tutorials.jenkov.com/java-concurrency/index.html
http://tutorials.jenkov.com/java-util-concurrent/lock.html
http://tutorials.jenkov.com/java-concurrency/read-write-locks.html
http://tutorials.jenkov.com/java-concurrency/starvation-and-fairness.html

Concurrent Programming in Java: Design Principles and Pattern (2nd

Edition) by Doug Lea. A comprehensive work by a leading expert, who’s also the
architect of the Java platform’s concurrency framework.
Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch,
Joseph Bowbeer, David Holmes, and Doug Lea. A practical guide designed to be
accessible to the novice.
Effective Java Programming Language Guide (2nd Edition) by Joshua Bloch.
Though this is a general programming guide, its chapter on threads contains
essential “best practices” for concurrent programming.
Concurrency: State Models & Java Programs (2nd Edition), by Jeff Magee and
Jeff Kramer. An introduction to concurrent programming through a combination
of modeling and practical examples.
Java Concurrent Animated: Animations that show usage of concurrency
features.