Java Interview Questions Cheat Sheet

java

About

For refreshing one’s memory before an interview.

Core Java

  • About: Strict typed, class-based, OO, platform-agnostic
  • Lifecycle: compile .java to .class bytecode, run just-in-time by the JVM, no reference, finalize(), GC
  • Keywords: import, finally, super, class, package, int, synchronized (one thread at a time, avoids data race [multiple threads access same data], method or block), volatile (modified by other threads)…many more!
  • Objects:
    • state = fields, behaviour = methods
    • == (compares references i.e. same object in memory, shallow comparison), equals method can be overridden for deep comparison of properties
    • hashCode (unique hash) — used by maps, same object should produce same hash must override both
    • Dog puppy [declaration] = new [instantiation] Dog(“fido”) [initialisation]
  • Class: object creation blueprint, load manually by ClassLoader (dynamic plugins), top-level can’t be private/protected, auto loads java.lang.package, inner classes, nested class (static within class)
  • Interface: collection of abstract methods, Externalizable (serialisation), Enumerator (loops), Iterator (looping with support for removing, thread safe), Comparable (natural order), Comparator (custom order), Marker (empty, use annotation instead)
  • Scope: local (within method), instance (property), class (static)
  • Constructor: invoked only once on creation, if private no instantiation no subclassing (e.g. singletons)
  • Primitives: boolean, char (16-bit unicode), byte (8-bit), short (16), int (32), long (64), float (32), double (64)
  • Wrappers: Autoboxing, unboxing (e.g. Integer)
  • Collections:
    • Set (no duplicates), TreeSet (sorted), Vector (heterogeneous [different types], dynamic, sync), ArrayList (dynamic, random access), LinkedList (sequential add/remove), Map, HashTable (sync, no null)
    • ordered longer insert, faster lookup
  • Loops: do executes at least once
  • Streams: Reader/Writer (char), Input/OutputStream (byte, serialisation), System.out (PrintStream)
  • Modifiers:
    • final (variable = immutable, methods = no override, class = no extend)
    • protected (access by same package and subclasses)
    • default (same package)
  • Switch: byte, short, int, char (why?)
  • Strings: immutable, final (can’t subclass and make a mutable string), stored on stack, thread-safe, StringBuffer (sync), StringBuilder
  • OO: simple, modular, modifiable, extensible, maintainable, reusable
  • Abstraction: partial implementation, enforcing blueprint, class only extended
  • Encapsulation: data hiding through getters/setters, maintainability, modifiable
  • Inheritance: no multiple inheritance (no circular dependency, ambiguous calls e.g. super = diamond problem), extend one class, implement many interfaces
  • Polymorphism: Dynamic Method Dispatch, “many forms”, method overloading at runtime, method overriding at runtime
  • Acronyms: JAR (Java ARchive), WAR (Web ARchive), JDBC (Java DataBase Connectivity), Java EE (Enterprise Edition), Java SE (Standard Edition), JDK (Java Development Kit), JRE (Java Runtime Environment)
  • JDBC: PreparedStatement precompiled faster
  • Threads:
    • single execution in a process
    • sleep, wait (up to until notify), yield, suspend, notify, notifyAll, isAlive,
    • newborn > runnable > running > blocked > dead
    • daemon = background low priority
    • implement Runnable or extend Thread (manage manually)
  • Errors:
    • Error: irrecoverable (e.g. OutOfMemory)
    • Exception: recoverable (e.g. FileNotFoundException), Checked: throws BadInputException
    • Assertion: never-happen scenarios and tests (e.g. assert dependency exists)
  • Binding: dynamic (late, generics, polymorphism), static (static, final, private)
  • Sockets: lightweight TCP/IP (Transmission Control Protocol)
  • Env: CLASSPATH (.class files), PATH (executables)
  • Casting: downcast to a more specific type down the hierarchy (e.g. Animal > Dog), implicit (inferred, lossy), explicit, promotion (e.g. short to int)
  • Big O Notation: O(1) constant, O(n) linear loop, O(n2) quadratic nested loop, O(n3) cubic double-nested loop, O(log n) logarithmic half list each time binary search
  • Cookies: client-side sent every request, Session: server-side (or encrypted cookies)
  • Date: sql date (no time) extends util
  • Parameters:
    • definitions, Arguments: actual values
    • pass by value, object properties can still be modified!
  • Bean: encapsulation (getters/setters), public constructor, serialisable
  • Terms:
    • Referential Transparency: no outside influence, don’t need to understand full context/globals.
    • Boundary Condition: extreme inputs.
    • Composition: class holding reference to another class.
    • SOLID Principle: open to extension, closed to modification.
    • Demarcate: to define boundaries (e.g. transaction).
    • Non-blocking API: don’t wait for 3rd party API calls (e.g. threads).
    • Single responsibility principle: each variable/method/class should define a single responsibility (only one reason to change).
    • Idempotent: calling same method multiple times doesn’t hurt (e.g. remove item from list).
    • Separation of concerns: modular.
    • (String) Interpolation: String with placeholders (e.g. $foo).
    • Method vs function: methods are functions tied to an object (e.g. it’s behaviour).
  • Memory Leaks: Thread running ClassLoader (ThreadLocal keeps reference), String.intern, unclosed streams/connections, static, setAttribute (context, session)
  • Improve Java: less verbose (e.g. getters/setters), as-needed modular (Jigsaw), kill servlets, not Oracle
  • Performance: monitoring, java startup arguments (e.g. heap), pooling, caching, refactoring, latest versions, scale up, scale out
  • Sort:
    • Bubble (quad, compare and swap adjoining elements, pass through until no swaps, low memory > performance, simple)
    • Insertion(quad, one element at a time, insert in the right spot, linked list pointers, simple, efficient small data)
    • Quick (log to quad, choose pivot/middle value, from left>right if value less than pivot, replace with first lesser value working from the right, recursive)
    • Merge (log, divide and conquer, split until single elements, combine in order until sorted, simple, requires space)
  • Search: linear (n, for loop), binary (sorted, half each pass, recursion)
  • Annotations:
    • meta-data through introspection, less code, dev time (documentation, checking), runtime (wiring, descriptions)
    • @NotNull, @Controller, @Transaction, @Entity, @Override
  • IDE: auto-completion, code generation, static code checks, plugins, highlighting (CheckStyle, FindBugs)
  • Java Versions:
    • 5 (generics, annotations, enums, for-each), 6 (meh), 7 (string switch, try with resources, <> operator), 8 (lamdbas)
    • Java SE = JVM, JDK = JRE + compilers
  • Testing: mock objects, stub methods, unit = smallest component (e.g. a method), integration = multiple components together (e.g. log in), user acceptance = customer expectations, non-regression = re-running all tests for confidence (e.g. Continuous Integration), spec = declarative specification style (non-programmers, readable, Domain Specific Language)
  • Design Patterns: singleton (instantiated once, shared resources e.g. log, pooling), prototype (copy), facade (abstract away complexity), factory (create objects), abstract factory (create factories), observer (notifies, AOP), MVC, MVVM (ViewModel = exposed data bindings to the view rather than rendering, separate UI), adapter (connect two interfaces), strategy (common functionality e.g. sort), state (?), proxy (control access), DI, builder (create complex objects), chain of responsibility (pass request e.g. filter, log), template (outline, subclasses do steps), decorator (add functionality to existing e.g. override). Gang of Four (GoF) authors.

Spring

  • About: framework, open-source, IoC container
  • Modules: core, bean, context, JDBC, ORM, JMS, web (context, binding), AOP, transactions…
  • Inversion of Control (IoC): loose coupling of code from metadata and dependencies, easier to test in isolation, Dependency Injection (DI via constructor or setters)
  • Service-Oriented Architecture (SOA): Loosely coupled services (Law of Demeter), interact as black boxes, distributed, modular, interoperability
  • BeanFactory: creates container
  • Container: lifecycle of a bean (invokes, config, dependencies, security, transactions, management, destroy), override setup/destroy methods
  • Pattern: default Singleton, otherwise prototype (inner bean)
  • Annotations: declarative management, @Autowired (auto resolve dependencies), @Required (must be initialised at runtime), @Service/Component/Repository (labels), @Transactional, @Test(expected=IOException.class), @Before, @After
  • AOP: Aspect (encapsulation), Joinpoint, Pointcut (1+ Joinpoints), Advice (actual code)
  • DAO: JPA and Hibernate, lazy/eager loading
  • JMS: Message-Driven Beans (MDB), queues, process messages async
  • Dispatcher: DispatcherServlet reads incoming requests, calls the right class/method, combines result with the right view and returns response
  • Context: WebAppContext extends AppContext and adds ServletContext (resources, defined contexts in web.xml)
  • Deployment Descriptor: web.xml, describes classes, resources, config, request mapping
  • Classloader: Executes hierarchy top to bottom (superclasses first), different strategies per app server
  • TDD: JUnit (assertEquals), Mockito (mock foo, when foo.bar thenReturn, verify foo.doh), Hamcrest (assertThat, is, not, any, anything, equalTo, isA)

JavaScript

  • About: ECMAScript, scripting language, loosely typed, prototypical (prototype-based), object-based
  • Modules: wrap in function block, namespacing, alias (e.g. $.foo)
  • Scope: var foo (local), foo (global). Only functions create new scope, not blocks.
  • Data Types: undefined (default), number, string, boolean, object (e.g. foo = {}, foo = new Array), function, null
  • Operators: == (type conversion), === (no type conversion)
  • Inheritance: prototype (i.e. chained parent refs, inherit properties, parent not modified) or Object.create(Object.create) = recommended
  • Strict Mode: no accidental globals, duplicate property names etc.
  • Number: no integer, floating point precision (nearest binary point) = weird stuff! Don’t use for precision!
  • DOM: Document Object Model, object of rendered page, interact with
  • Event Bubbling: parent nodes triggered
  • jQuery: lightweight, cross-browser, plugins, CSS3, supported, selectors, manipulation, loops, events, animations, AJAX, utilities…
  • Hoisting: Variable declarations and function declarations (not function expressions) are invisibly moved to the top of their scope.
  • Isomorphic: Code that can be run client or server-side.
  • Function Types: Function expression (i.e. unnamed/anonymous, parse-time available when assignment line hit) vs function declaration (i.e. named, run-time scope before any step-by-step code is executed, can’t put inside conditional blocks such as if/try/while, proper name when debugging). It’s possible to combine both styles, but has IE8 issues. Never use the Function() constructor. ECMAScript6 will attempt to infer expression names from context.
    // Function expression
    var foo = function() {}
    // Function declaration
    function foo() {}
    // Combined/Named Function Expression
    var foo = function bar(){};
    // Combined with proper aliasing across browsers
    function bar(){};
    var foo = bar;
  • Cross Browser: JavaScript can’t POST cross-domain (use a library like easyXDM or back-end)
  • Weird: null is an object (default undefined), foo(2)(3) returns annon function, semicolons optional, negative infinity (negative / 0)

Functional

  • Predicate: function that runs against every item in a collection — returning true or false. Used for filtering without nested for/if statements.
  • Lambdas: function that can be passed around like an object.
  • Closures: private variables made possible through self-invoking functions (i.e. outer function contains private variables and returns function expression — outer only ever called once). Example:
// self-invoking run only once
var add = (function () {
  // counter protected by anonymous scope (private)
  var counter = 0;
  // add function associated with returned function expression
  return function () {return counter += 1;}
})();

add(); // counter = 1
add(); // counter = 2

Tips

  • BDD/TDD!
  • Whiteboarding use pseudo code placeholders to guide the thought process — then replace pseudo with implementation. Don’t get stuck on implementation before solution is mapped out.
  • Don’t commit boilerplate code, IDE files and comments to the repository
  • Be involved in the community (follow people, read blogs, stream, attend events, network, work on projects)
  • Commit often to your local Git repository and every day or so to the remote origin
  • Never say “can’t” — don’t lie, but back yourself to learn it. Most things are not that hard.

Room For Improvement

  • Encoding, bit shifting, octal/hex, Applets (Swing, AWT), JVM heap, GC (WeakReference), PermGen (class metadata), RMI, Servlets/JSP, Angular, monoids.

Java Frameworks 2012

About

A cheat sheet for choosing the best Java framework for the job — or if we’re lucky, overall. That’s not to say you can’t deliver solutions using almost any framework, but why make things hard for yourself? You can send a shuttle into space using the imperial system, but it would be easier and more accurate to just use the metric system.

Main emphasis is given to a non-enterprise startup web application with mobile support.

What to look for…

  1. Top tier: Developer productivity, scalability, testing, multi-language support, documentation/tutorials, REST support, mobile support
  2. Middle tier: Learning curve, project health, developer availability, AJAX support, plugins, validation
  3. Bottom tier: Perception, jobs, templating, components, i18n, books, risk

Before we start

  • Don’t bother with Struts or JSF — they are a sinking ship!
  • Best process is to eliminate frameworks based on what they can’t do

Statistics

Framework Grails Spring MVC Play! Vaadin GWT Tapestry 5 Wicket
Overall Weighted Ranking 90% 85% 82.5% 82.5% 80% 75% 67.5%
Performance 2nd 1st
Least Lines of Code 2nd 1st
Marketplace Jobs 25 65 3 65 8 10
LinkedIn Skills 20 20 10 40 10 10
Marketplace Job Postings 4% 14% 5% 1% 6.5% 3% 3%
Amazon Books 40 70 5 60 5
Code Releases (2011) 1 1 15 2 3 0
Popularity Report (2010) 5% 48% 11% 1% 7%
Innovators Yes Yes
Productivity Report (2012) 7% 30% 8% 7% 14% 2% 7%

Pros and Cons

  • Grails
    • + good for Java devs, Groovy, plugins, Grails 2 released, mature
    • – stack traces
  • GWT
    • + Java produces optimised JS, easy to learn, community
    • – slow compile, difficult test, more like tag library
  • Spring MVC
    • + annotation configs, conventions, view integration (e.g. Tiles, JSP), REST support, popular commercial choice
    • – no instant reload, tied to SpringSource, 3rd party Ajax
  • Vaadin
    • + GWT API for view, community, themes and layouts
    • – memory footprint, state stored in session
  • Wicket
    • + good for Java devs, tight binding between pages and views, community
    • – no jobs, stateful, HTML templates beside code
  • Tapestry
    • + instant reload, performance, scalability, exception reporting
    • – no jobs, prototype JS library, annotations vs conventions
  • Play!
    • + full stack web framework, instant reload, stateless, reload/back buttons work, clean URLs
    • – static methods, doesn’t use servlet API

Play! 2

The new version of Play! is a major semantic version and no longer compatible — more of a spiritual successor. It is the future of web programming, but too new to adopt as it is a complete rewrite and has only been out for 3 months. The module support has also not had a chance to catch up.

Changes

  • Core rewritten in Scala
  • Templates in Scala instead of Groovy
  • More compile type checking and pre-compiling of  templates/JavaScript/CoffeeScript/LESS resulting is slower compile, but smaller footprint
  • Build and deployment now uses the SBT build system, which is a standard and more modular. Allows publishing to any repository.
  • Java can still be used, but Scala is the “first class citizen”
  • Asynchronous tasks delegated to Akka for massive concurrency (each request doesn’t tie up a JVM thread) and pushing realtime data
  • Non blocking I/O
  • ORM uses eBean instead of Hibernate because it’s statless
  • Compile-time type safety
  • Commercially supported and now part of the Typesafe stack
  • Less bytecode magic
  • Better prepared for NoSQL datastores
  • Components more loosely coupled for greater choice
  • Python to SBT
  • Long polling (i.e. Comet) requests easier to optimise
  • Promotes Scala functional (web) programming
  • Really good functional testing API
  • Methods return an action
  • Request body parsers
  • Powerful iteratees/enums/enumeratees
  • Great documentation and samples (as per Play! 1)
  • Compared to Grails 2: 40% less files, 10% less transactions, 20% more requests per second
 Minor Criticisms 
  • Netbeans Scala IDE support not great, but fine for IntelliJ and Eclipse
  • Controller more verbose
  • Deployed slug twice the size ~80Mb)
  • Dependency management more difficult than the YML file
  • Not as lightweight or clean (number of files, complexity)
  • Plugin required to deploy to WAR
Major Criticisms
  • Learning curve for Java developers to learn Scala (e.g. debugging)
  • Non-instant compile time (optimisations planned)
  • Lack of modules (for now)
  • Migration not trivial, especially modules
  • Not optimised for database apps out-of-the-box (JDBC can cause blocking timeouts, requires longer timeouts and more threads)
  • Not yet mature enough (only 3 months old!)
Opinions
  • “If it’s a critical project, to be finished before next March 2012, I would go with Play 1.x”
  • “The main difference is that play 1.x tried to build it’s own stack while escaping away from J2EE, now they are part of a new and alternative stack, based on Scala, Akka, SBT and with the support of a company like Typesafe…”
  • “It depends on the project, but as of yet I have not come across a problem that Play 1.x could not solve. So, I would probably stick with Play 1. Now, I understand why people aren’t fully bought into Play 2 yet, I get it. I am still so happy with Play 1.x, I am not ready to move across yet. But what I don’t get is why people are so upset that Play 2 exists? It has its place, and will grow into another great framework.”
  • “Play 1 can be used in production, and is still a valid choice for projects that don’t need the new Play 2.0 (Scala, Async, etc.) features. It has an extensive knowledge base, books, and an active modules community (let’s make that better with the new modules manager).” 
  • “Play 2.x is the future. It is less mature currently (yet fully usable for production project), with a less active community. We are all working on it, to make it faster in development mode, and more polished. It took 3 years after the 1.0 release for Play 1.2.4 to reach this state. We need more time on Play 2.0 as well.”
  • Parts of the community have overreacted, because they are afraid of change and unsure about which version to use
  • Play! 1 is feature complete and will receive no new features, just maintenance
  • Plans to launch a community website for existing/new Play! 1 modules
  • Play! 2 is currently not as polished, but it will quickly catch up…at which point the community will no longer be torn

Conclusions

  1. There are tons of great options! But at present my recommendations for a Java startup web application are (in no particular order):
    1. Grails 2
    2. Spring 3 MVC
    3. Play! 1.x
  2. Either do a POC on a few frameworks and make a choice or just pick one and get to work!
  3. Once mature, watch out for Play! 2 and Vaardin

Resources