Java Basics: Features, Core Concepts, and Common Interview Questions
This article provides a comprehensive overview of Java fundamentals, covering language features, value vs. reference passing, equality operators, string immutability, static and final keywords, collections, concurrency, memory management, I/O, design patterns, and many typical interview topics.
Java Basics
Java is a concurrent, object‑oriented, platform‑independent language that runs on a virtual machine, making it simple, portable, secure, dynamic, distributed, robust, high‑performance, and interpreted.
Key Features of Java
Concurrency: multiple statements can execute without sequential ordering. Object‑Oriented: class‑based programming model. Portability: "write once, run anywhere" via bytecode.
Value vs. Reference Passing
Value passing copies the actual argument, so modifications inside the method do not affect the caller. Reference passing passes the object’s address; changes to the parameter affect the original object.
"==" vs. equals
==compares primitive values for equality, but for reference types it checks whether two references point to the same memory location. equals (defined in Object) compares the logical value of objects and can be overridden.
String equals Implementation
String overrides equals by first checking reference equality, then confirming the other object is a String, comparing lengths, and finally comparing each character.
if (this == anObject) {
return true;
}
if (!(anObject instanceof String)) {
return false;
}
String anotherString = (String) anObject;
int n = value.length;
if (n != anotherString.value.length) {
return false;
}
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;Why Overriding equals Requires Overriding hashCode
Objects that are equal must return the same hash code; otherwise collections like HashMap may violate the contract and cause incorrect behavior.
String Immutability
String objects are final and immutable; any modification creates a new object. Internally, strings are stored in the runtime constant pool (moved to the heap after JDK 1.7).
Static Keyword
staticdenotes class‑level members: static variables (class variables), static methods (invoked via ClassName.method()), static blocks, static inner classes, and static imports.
Final Keyword
finalmakes classes non‑extendable, variables immutable (reference cannot change, primitive value fixed), and methods non‑overridable.
Abstract Class vs. Interface
Abstract class can contain both abstract and concrete methods; interface (pre‑Java 8) only declares abstract methods.
Interface variables are implicitly public static final; abstract class variables are ordinary fields.
Override vs. Overload
Override occurs in a subclass with the same signature as a superclass method; overload occurs within the same class with different parameter lists.
Byte Range
Byte occupies 8 bits, ranging from –128 to 127, using two’s‑complement representation.
HashMap vs. Hashtable
Both implement Map but HashMap is non‑synchronized, allows null keys/values, and has a default capacity of 16 (powers of two). Hashtable is synchronized, disallows null, and starts with capacity 11.
In JDK 1.7 HashMap uses bucket‑list; in JDK 1.8 buckets with >8 entries become red‑black trees.
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
// simplified insertion logic
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// handle collisions, treeify, etc.
}
// resize if needed
if (++size > threshold)
resize();
return null;
}ConcurrentHashMap
Provides thread‑safe access using segment locks (or striped locks in newer versions) and is the preferred map for high‑concurrency scenarios.
Integer Cache
Java caches Integer objects for values –128 to 127 via IntegerCache, reducing object allocation for frequently used numbers.
UTF‑8 vs. Unicode
Unicode assigns a unique code point to each character; UTF‑8 encodes these code points using 1‑4 bytes, preserving ASCII compatibility.
Arrays.asList
Converts an array to a fixed‑size List; structural modifications (add/remove) throw UnsupportedOperationException. It does not support primitive arrays.
Collection vs. Collections
Collectionis the root interface for all collection types; Collections is a utility class offering static methods such as sort, synchronizedList, reverse, and fill.
Fail‑Fast vs. Fail‑Safe
Fail‑fast iterators detect concurrent modifications and throw ConcurrentModificationException. Fail‑safe iterators (e.g., those from java.util.concurrent) work on a snapshot copy, avoiding the exception.
ArrayList, LinkedList, Vector
ArrayList: backed by a dynamic array, fast random access, slower insert/delete, non‑thread‑safe. LinkedList: doubly‑linked list, fast insert/delete, slower traversal, non‑thread‑safe. Vector: synchronized dynamic array, thread‑safe but slower due to locking.
Exception vs. Error
Exceptionrepresents recoverable conditions (checked and unchecked). Error indicates serious problems that applications should not catch.
String, StringBuilder, StringBuffer
Stringis immutable; StringBuilder is mutable and not synchronized (fast for single‑thread); StringBuffer is synchronized (thread‑safe).
Dynamic Proxy
Implemented via reflection; JDK dynamic proxies create runtime proxy classes that implement interfaces.
int vs. Integer
intis a primitive 32‑bit value stored on the stack; Integer is an object stored on the heap, supports methods, and participates in caching.
Java I/O
Traditional blocking I/O (BIO) uses streams; NIO (since JDK 1.4) introduces channels, selectors, and buffers for non‑blocking I/O; AIO (since JDK 1.7) adds asynchronous I/O.
Design Patterns
Common patterns include Singleton, Strategy, Template, Adapter, Composite, Decorator, Proxy, etc.
Comparator vs. Comparable
Comparabledefines natural ordering via compareTo; Comparator provides external, custom ordering.
Object Class Methods
Key methods: hashCode, equals, toString, clone, wait, notify, notifyAll, finalize, getClass.
Generics and Type Erasure
Java generics are implemented via type erasure; generic type information is removed at compile time.
Reflection Basics
Reflection enables runtime inspection and manipulation of classes, fields, methods, and constructors. Instances can be created via obj.getClass(), Class.forName(), or Class.newInstance().
Reference Types
Strong: normal reachable objects.
Soft: SoftReference, cleared only under memory pressure.
Weak: WeakReference, cleared eagerly.
Phantom: PhantomReference, used after finalization.
final, finally, finalize
finalmodifies classes, methods, or variables to make them immutable. finally is a block that always executes after try. finalize is a deprecated method called by the garbage collector before object reclamation.
Inner Classes
Four types: member, local, anonymous, and static inner classes, each with different access rules.
Common Exceptions
NullPointerException
NoSuchMethodException
IllegalArgumentException
IndexOutOfBoundsException
IOException
ClassNotFoundException
NumberFormatException
InterruptedException
Static vs. Dynamic Binding
Static binding occurs at compile time for private, static, final methods and constructors. Dynamic binding resolves method calls at runtime based on the actual object type, enabling polymorphism.
—End of summary—
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
