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.