
Prepare for core Java interviews with a curated collection of interview questions and detailed explanations from diverse Java developers.
HashMap uses a bucket array of linked nodes; it computes index as hashcode & (n-1), inserts and updates by traversing the chain, and uses equals for collision handling and retrieval.
Explore platform independency in Java, the build once, run anywhere concept, where bytecode runs on any operating system via the Java Virtual Machine.
Explore how the Java class loader dynamically loads classes into the Java virtual machine, locating libraries and reading their contents across the bootstrap, extension, and system loaders.
Use the join method to make one thread wait for another to finish, pausing the main thread until ThreadB terminates. Observe how the arraylist gains four players after join completes.
Java is strictly pass-by-value; primitives pass by value and a copy of the reference is used for objects; reassigning a reference inside a method doesn't affect the original.
Explore how generics enforce strong compile-time type safety, eliminate excessive casts, and enable reusable algorithms by expressing element types in containers rather than using raw objects.
Explain the difference between path and classpath, noting that the bin directory contains javac and java, while path enables running executables from directory and classpath locates .class files and jars.
Java isn’t 100% object-oriented because primitive types are not objects, and you can interact with objects without calling their methods, even though wrapper classes exist.
Explain how static initialization blocks initialize static variables when a class loads, showing that blocks run in source order before main, can be multiple, and may create static resources.
Wrap primitive types as objects with wrapper classes to allow null values and use primitives in collections; Java autoboxing converts between primitives and objects, as shown in the Batsman example.
Compare string and StringBuffer: string is immutable, StringBuffer is mutable and faster for concatenations, while StringBuffer is synchronized and string is not, with + working only on string.
Compare StringBuffer and StringBuilder to understand thread safety and performance trade-offs. Choose StringBuffer for thread-safe operations, while StringBuilder offers better performance; both are mutable.
Explain how Java's object law governs hashCode and equals, showing that equal objects have matching hashcodes, and that overriding equals requires overriding hashCode.
Explain method overloading demonstrates that multiple methods share the same name but differ in argument lists for caller convenience, with no polymorphism and no inheritance involved.
Overriding lets a subclass redefine inherited methods to change or extend their behavior. Ensure arguments match and return types are compatible, and not less accessible rules apply.
Explains why Java does not allow multiple inheritance for classes due to ambiguity. Shows how to achieve it through interfaces and composition, as illustrated with front-end and back-end examples.
Explain interface features in Java, including public static final variables and abstract methods by default. Java 8 adds default and static methods, main method inside interfaces, and no Object inheritance.
Compare abstract classes and interfaces in Java: abstract classes have abstract and non-abstract methods; interfaces now support default and static methods, enabling multiple inheritance and public by default members.
Learn how to call a super class constructor in Java with super(), why it must be the first statement, and how Bowler extends Player to invoke the parent constructor.
Explains the uses of the this keyword in Java, including referring to the current object, accessing instance variables or methods, invoking the current class constructor, and returning the current instance.
If a subclass does not call a superclass constructor, the superclass's no-argument constructor runs automatically; if that constructor doesn't exist, the compiler errors unless the subclass uses super with arguments.
Polymorphism lets a Shape supertype be substituted by any Rectangle or Square subclass to enable runtime polymorphism through their printShape implementations, reducing maintenance when new shapes appear.
Explore encapsulation in Java, hiding object data and exposing only public interfaces. The hotel example shows private fields with validated setters to protect state.
Explain nested and regular inner classes as full-fledged outer-class members with access modifiers and optional abstract or final modifiers, and how to instantiate them using an outer-class reference.
Explain method-local inner classes defined inside a method, including their instantiation and the rule that they cannot access non-final variables or use access modifiers; they can be abstract or final.
Explain anonymous inner classes, one of the four inner class types with no name, that extend a named class or implement a named interface, seen with a Runnable anonymous class.
Explain the static nested class, one of four inner class types, marked with the static modifier. It can access static members of the enclosing class and cannot access non-static members.
Explain how the default access modifier works when no modifier is specified for class, method, or field. It permits access within the same package and restricts access from other packages.
Explain the protected access modifier, showing access within the same package and by all subclasses, while non-subclasses in different packages cannot access protected members, as Vehicle and Car illustrate.
Understand the private access modifier in Java: private fields or methods are accessible only within the same class, as shown when TextditorTest cannot access the field Text in textEditor.
Explain how final modifier governs class, variable, method, and argument behavior: final classes cannot be extended; final variables initialize once; final methods cannot be overridden; final arguments cannot be modified.
Explore the enhanced for loop, a compact form of iteration for arrays and collections, and see how it makes code easier to read and write.
Run code in the finally block regardless of exceptions or returns, ensuring cleanup and resource recovery. Use finally to prevent resource leaks when closing files or releasing resources.
Explore scenarios where a finally block may not run, such as when the JVM exits during try or catch, or when the executing thread is interrupted or killed.
Explore the exception handling class hierarchy, with Exception extending Throwable, RunTimeException extending Exception, and examples like NullPointerException and ClassCastException extending from RuntimeException.
Differentiate between error and exception in core Java interview questions; both subclass java.lang.Throwable, but errors are unrecoverable runtime failures, while exceptions are recoverable via try-catch, with checked versus unchecked distinctions.
Explain the difference between checked and unchecked exceptions in Java, with RuntimeException and compile-time rules using throws or try-catch for FileReader, FileNotFoundException, and IOException.
Explain how try-with-resources, introduced in Java 7, automatically closes resources like BufferedReader, removing the need for a finally block, and closes them in the opposite order of creation.
Understand what an enum is and how it represents a set of predefined constants, with methods like toString, valueOf, and ordinal, including directions and days of the week.
discover how varargs simplify adding multiple numbers by using the final argument position, allowing a sequence of arguments or an array, without overloading methods.
Explain automatic garbage collection by identifying in-use versus unreferenced objects in heap memory and reclaiming memory. The JVM destroys eligible objects, and you can request collection via System.gc() or Runtime.getRuntime().gc().
Override finalize() to clean up resources before an object is garbage-collected; GC calls it before destruction; it's invoked at most once, and exceptions are ignored, and the program terminates normally.
Serialization converts an object's state to a platform independent byte stream, enabling persistence. Objects become serializable by implementing java.io.Serializable or java.io.Externalizable.
Define serialVersionUID and show how it stamps serialized objects with a version id. Illustrate how class changes affect the UID and deserialization, emphasizing declaring a fixed serialVersionUID to maintain compatibility.
Core collection interfaces form a hierarchy with Collection as root, followed by Set, List, Deque, and Queue; Map sits separately, while SortedSet and SortedMap provide ordered variants.
Explore essential methods declared in the collection interface, including containsAll, addAll, removeAll, retainAll, and clear. Learn how these operations modify and query collections.
Explain ArrayList as a resizable list implementation with null support and no synchronization. Review fail-fast iterators and key methods like add, addAll, contains, indexOf, get, iterator, and size.
Explain how the Enumeration interface generates elements one at a time via nextElement, hasMoreElements, its legacy status for Vector and Hashtable, and how the Iterator duplicates it with optional remove.
Learn how the iterator replaces Enumeration in the Java collections framework, enabling removal of elements during iteration with well-defined semantics, via hasNext, next, and remove methods.
Explore the list iterator's bidirectional traversal, cursor positioning between elements, and in-place modification via next, previous, add, remove, and set methods, with index helpers.
Learn how to sort an ArrayList using the Comparable interface by implementing compareTo to define natural ordering, enabling Collections.sort to order objects by id or other fields.
Learn how to sort an ArrayList using the Comparator interface by creating comparator classes, implementing compare for id and name, and passing them to Collections.sort.
Explore whether enumeration is fail-fast by examining a scenario where a collection changes during iteration, causing no exception and revealing that enumeration is not fail-fast.
Explain how iterators are fail-fast, and show how modifying a collection during iteration throws a ConcurrentModificationException.
Vector is synchronized, allowing one thread at a time, unlike ArrayList which is not. Vector supports Enumeration and Iterator; ArrayList uses only Iterator, with Vector slower due to synchronization.
Explore java's LinkedList, a doubly linked list implementing List and Deque, with head-tail traversal and fast insertions, unlike ArrayList, and key methods like getFirst, getLast, addFirst, addLast, and poll.
Explore why strings are immutable in Java, highlighting the string pool for memory efficiency, security, and thread safety. Explain hashcode caching and use as keys in HashMap.
Explain the queue interface, its relationship to collection, its sub interfaces such as Deque, BlockingDeque, BlockingQueue, TransferQueue, and core methods like add, offer, poll, remove, peek, and element.
Explore the key interfaces and classes of the set hierarchy, including NavigableSet and SortedSet, and how AbstractSet, TreeSet, HashSet, LinkedHashSet, ConcurrentSkipListSet, and CopyOnWriteArraySet relate.
How a HashSet implements the Set interface with a hash table backing, supports null elements, offers constant time basic operations, and features fail-fast iterators and non-synchronization.
Preserve insertion order using a hash table and a doubly linked list in LinkedHashSet. Compare its iteration and performance to HashSet, noting constant-time operations and fail-fast iterators.
Explore NavigableSet, a sorted set with navigation methods like lower, floor, higher, and ceiling, plus pollFirst and pollLast, to retrieve or remove boundary elements in ascending order.
Explore TreeSet in detail, compare it with HashSet, and understand how TreeSet implements Set, SortedSet, and NavigableSet via a TreeMap, using natural ordering or a comparator and ensuring log(n) operations.
Explain the default toString() behavior in Java when not overridden: it returns the class name followed by '@' and the toHexString of the hashCode, with a Student example.
Explore the deque interface, a double-ended queue that supports insertion and removal at both ends, with paired methods that throw exceptions or return special values.
Explore the BlockingQueue interface, focusing on blocking put and take, and the timed offer and poll variants for producer-consumer patterns in a thread-safe arrayblockingqueue.
explain how sorted map extends map with total ordering of keys via natural order or a comparator, including headMap, tailMap, firstKey, lastKey, and implementations like TreeMap and ConcurrentSkipListMap.
Explore how NavigableMap extends SortedMap and is implemented by TreeMap and ConcurrentSkipListMap, and examine navigation methods such as lowerEntry, floorEntry, lowerKey, floorKey, and ceilingKey.
CopyOnWriteArrayList is a thread-safe variant of ArrayList in java.util.concurrent, where mutative operations copy the underlying array; iterators operate on a snapshot, not reflecting concurrent changes.
Observe how fail-fast iterators throw ConcurrentModificationException on structural modification after creation, whereas fail-safe iterators on concurrent collections avoid the exception by updating on a separate copy.
Explore atomic classes in java.util.concurrent.atomic for lock-free, thread-safe programming on single variables, with a look at AtomicInteger and its methods like addAndGet, decrementAndGet, intValue, and updateAndGet.
Declare a generic class by placing a type parameter after the class name in angle brackets. Use a type argument to form a parameterized type and instantiate with new.
Learn to restrict generics to a subclass of a class using bounded type parameters. Apply parameterized types constrained to Number or its subtypes and observe compile-time errors on violations.
Learn how generic methods introduce their own type parameters and limit their scope to the method, with static and non-static variants, plus generic class constructors and an example invocation.
Explore two thread creation methods: extending the Thread class and implementing the Runnable interface, then start threads with the start method and implement run accordingly.
Describe the thread life cycle from new to dead, covering ready-to-run, running, sleeping, waiting, and blocked states such as I/O, join, lock acquisition, and notifications.
Explore how thread priority guides the scheduler in Java, how to set and get priority, and the roles of max priority, min priority, and norm priority.
Synchronize static methods to protect class-level static variables in multithreading. Illustrate how a class-wide playerCount is incremented and decremented to avoid data inconsistency.
Understand how the yield method signals the scheduler to relinquish the CPU, moving the current thread to ready-to-run, and that it does not affect any locks.
Explain how wait() and notify() drive producer-consumer synchronization with synchronized blocks, object locks, and handling illegal monitor state exceptions during thread wake-up.
Understand streams as pipelines that convey elements from a source through lazy intermediate operations to terminal results, enabling short-circuiting and supporting infinite streams without modifying the source.
Explain how intermediate and terminal operations in Java streams form pipelines, where intermediate operations like filter and map are lazy and return streams, and terminal operations like collect consume pipelines.
Use method references to replace lambdas with static, instance (for a particular object or arbitrary object), and constructor references, and apply them in streams to filter primes or evens.
Learn Java class naming conventions by using noun class names in mixed case, with each internal word capitalized, keeping names simple and descriptive, avoiding acronyms.
Learn Java coding standards for interfaces, including capitalizing interface names like classes, and reviewing examples.
Learn how to name Java methods as verbs using camelCase, starting with a lowercase letter and capitalizing internal words, with practical examples.
Learn how the instanceof operator acts as a type comparison tool to verify whether an object is an instance of a class, superclass, or interface, with null always returning false.
Learn how to declare multiple classes in one .java file, ensuring one class shares the file name and at most one public class matches the file name.
Top level classes allow only public or default access modifiers. Private or protected cause a compilation error, while public exposes it everywhere and default limits visibility to the same package.
Explain naming conventions for packages, using all lower case and reversed domain names like com.example.mypackage. Use region or project identifiers to prevent collisions, and underscore when a domain is invalid.
Explore whether you can write code after a throw statement. Discover that the JVM stops execution after a throw, making subsequent statements unreachable and triggering a compile-time error.
NoClassDefFoundError is raised when the JVM or ClassLoader cannot load class definition during method call or new expression, because the definition existed at compile time but is missing at runtime.
ClassNotFoundException is thrown when a class cannot be found by loading it via a string name. The example uses class.forName to load a class by name and finds no definition.
Explore the two types of multitasking, process based and thread based, and how each runs tasks concurrently, with Java supporting thread based multitasking and multithreading.
Learn the difference between process and thread, including address space, multitasking, and inter-process versus inter-thread communication, with examples of a game process and its threads.
Use a lock to prevent multiple threads from accessing a shared resource, allowing only one thread to execute at a time; acquire the lock, then release it after execution.
Explore two synchronization approaches in Java: synchronized methods and synchronized blocks, with threads acquiring locks on BankAccount objects for addAmount and withdrawAmount, and on myString for getBalance.
Explain that a thread holding a lock remains locked while sleep is invoked, as sleep does not release the lock during the specified interval.
Discover why the best way to create threads is by implementing the Runnable interface, since extending Thread class prevents multiple inheritance and misses inheritance benefits.
Explain how the interrupt() method signals a thread to stop and how a thread responds through its own interruption handling, potentially terminating or continuing based on its code.
Explain which methods release the lock in Java, contrasting yield, sleep, and join with wait, notify, and notifyAll to clarify thread synchronization.
Learn how daemon threads in Java provide background services to user threads, allowing the JVM to exit after user threads finish, with examples like garbage collection and cache maintenance.
Explain why the main thread cannot be changed to a daemon, and why its non-daemon nature remains fixed.
Explain how nested classes in Java group classes that are used in one place. Show how encapsulation is enhanced by hiding nested classes inside their outer classes.
Learn how the Java compiler does not create a default no-argument constructor when a class defines a parameterized constructor, as shown by the Configuration example.
explain why static methods cannot be overridden in Java. Static methods are hidden in subclasses with the same signature, and calls are resolved at compile time by reference type.
Use static imports in Java to access static members without qualifying with their class. Use them sparingly; overuse harms readability and pollutes the namespace, so import only needed members.
Define immutable objects by preventing state changes after construction, using private final fields, no setters, and final classes. Copy mutable references to avoid external modification, a strategy for concurrent applications.
Demonstrate how CountDownLatch serves as a synchronization aid that initializes with a given count, blocks until await, and releases waiting threads when the count reaches zero after countDown calls—one-shot.
Explore the ThreadLocal class and its per-thread copies, learning how each thread holds an independently initialized value via get and initialValue, with set and remove managing the current thread's copy.
Manage a set of threads and nested ThreadGroup instances as a tree, performing unit-wide operations on related threads with methods like activeCount, activeGroupCount, checkAccess, destroy, enumerate, getMaxPriority, and setMaxPriority.
Discover why the Object class is the root of the class hierarchy, providing common methods inherited by all classes and arrays, with an overview of its constructors and methods.
Explain how system.exit() in a try block affects the finally block, noting that System.exit(0) terminates the program and avoids finally execution unless a security exception occurs.
Executors decouple thread management and creation from the rest of the application, replacing direct use of Runnable and Thread objects in large-scale Java applications.
Explore how the executor interface decouples task submission from execution mechanics like thread use and scheduling. Learn how to use executor.execute() to run Runnable tasks without creating threads.
Explore how the interface ExecutorService extends Executor, manages termination, and provides Future-based methods to track progress of asynchronous tasks, highlighting the key difference from Executor.
Explains how executorService.shutdown initiates an orderly shutdown, letting previously submitted tasks run while rejecting new ones and not waiting for their completion, with the main thread continuing.
shutdownNow() attempts to stop all running tasks, halts waiting tasks, and returns a list of tasks awaiting execution; it does not wait for termination and uses best-effort interrupts.
Explain how awaitTermination blocks until all tasks finish after shutdown, or a timeout occurs, or the thread is interrupted. Returns true if terminated, otherwise false on timeout.
Learn how the scheduled executor service extends executor service to schedule runnable or callable tasks with relative delays and periods, including schedule, scheduleAtFixedRate, and scheduleWithFixedDelay.
Explore the java.util.concurrent Executors class, offering factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable with configurable options.
Explain how the interface ThreadFactory creates new threads on demand, removing hardwiring of new Thread calls and enabling use of special thread subclasses and priorities.
CompletionService decouples task production from result consumption, enabling processing of completed tasks in order of completion via take from a queue of futures inside an executor service.
Explain how the cancel() method of the Future class cancels execution, using a boolean argument to decide interruption (true to interrupt, false to not), and returns true or false.
Explore tight coupling and loose coupling in object oriented design through a Journey example with Car and bike, using a Vehicle interface to decouple changes.
Explain when Java allows assigning a parameterized type to its raw type for backward compatibility, and why raw types bypass generics and should be avoided.
Explore restrictions on Java generics, including no primitive type instantiation, no type-parameter instances, no static fields with type parameters, no casts or instanceof, and no arrays of parameterized types.
Explore how default methods in interfaces enable backward compatibility, allowing new methods to be added without touching implementation classes, thus extending interface functionality.
Explore how private methods in interfaces boost code reusability by encapsulating common functionality for default methods, reducing redundancy in interfaces such as SubjectPrinter.
Demonstrate using the diamond operator with anonymous classes, enabled from Java 9, with a practical example that shows how it works.
Explore implicit casting as automatic type conversion when types are compatible and the target type is larger, illustrated by an integer cast to long.
Explore explicit casting as explicit type conversion between compatible Java types, with the target type smaller than the source. See an example that demonstrates the process.
Learn why OutOfMemoryError occurs when the Java Virtual Machine cannot allocate an object due to memory exhaustion and no memory is reclaimable by the garbage collector, illustrated by examples.
Describe how string literals are stored in the string constant pool on the heap and reused if identical, while new String() creates a separate heap object with no reuse.
Compare the == operator and the equals() method in Java, showing that == checks memory location while equals() compares object values.
Explore jar hell, a set of classpath issues including NoClassDefFoundError at runtime, version conflicts, lack of package isolation, and bloated rt.jar, now addressed by JPMS in Java 9.
Explain the Externalizable interface and its custom serialization, showing how writeExternal and readExternal control which fields, like name and age, are stored while dateOfBirth is ignored.
Learn exception handling best practices, including logging and not hiding errors, declaring and catching specific exceptions, avoiding flow control with exceptions, standardizing logging, and wrapping stack traces in custom exceptions.
Name the methods of an object class, including clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, and wait. These describe cloning, garbage-collection, runtime class, hash codes, and inter-thread synchronization.
Explain how heap pollution arises when a parameterized type variable refers to an object of a different type, often through unchecked warnings and raw types.
Understand when a Java collection throws UnsupportedOperationException by exploring unmodifiable list views, fixed-size lists from asList, and why add on these lists is not supported.
Explore how lambda expressions, method references, and constructor references create instances of functional interfaces and explain the relationship between lambda expressions and functional interfaces.
Shows that with Serializable, the no-argument constructor is not invoked during deserialization, while with Externalizable, the constructor is invoked, illustrated via an Employee example.
Explore where to use assertions in Java to validate internal invariants, control-flow invariants, and pre/postconditions, while avoiding argument checks and work that may be disabled.
Explain the purpose of @SafeVarargs and how it asserts that a varargs method avoids unsafe operations, suppresses unchecked warnings about parameterized array creation at call sites, and prevents heap pollution.
Contrast runnable and callable: runnable returns void and cannot throw checked exceptions, while callable returns a value and throws checked exceptions; runnable works with threads and the executor framework.
Explain how the load factor determines when a HashMap resizes, doubling buckets from 16 as entries exceed 0.75 times capacity, ensuring constant time get and put operations.
Explore the differences between synchronized and concurrent collections, highlighting performance limits, concurrent modification issues, and how CopyOnWriteArrayList and ConcurrentHashMap enable thread-safe reading and writing with proper memory consistency.
Explain the differences between synchronized map and concurrent hash map, including locking strategies (whole map vs bucket level), thread safety, performance, null key handling, and iterator behavior including ConcurrentModificationException differences.
Compare the lock interface with synchronized blocks, showing flexible locking, multiple condition objects, and hand-over-hand techniques, and learn non-blocking and timed acquisitions like tryLock and lockInterruptibly.
Differentiate final and immutable in Java by showing that final prevents changing an object's reference but allows state mutation, while immutable forbids state changes yet allows reassigning references.
Choose string types based on mutability and concurrency: use String for constants, and StringBuffer or StringBuilder for concatenation; use StringBuilder for single thread access and StringBuffer for multiple thread access.
Explore how Bill Pugh's inner static class makes singleton lazy and thread safe, avoiding synchronization, while weighing lazy versus eager initialization and multithreading risks.
Understand reentrant lock in Java, including the fairness parameter, multiple holds per thread, and checking hold counts with getHoldCount under contention.
Coordinate a fixed set of threads with a cyclic barrier, where each thread calls await until all parties reach the barrier. The barrier is reusable.
Compare CountDownLatch and CyclicBarrier by examining their synchronization roles, one-shot versus reusable behavior, and how await, countDown, and barrier waiting coordinate multiple threads.
Learn the five object creation methods in Java: new, Class.newInstance, Constructor.newInstance, clone, and deserialization, where clone does not invoke constructors and deserialization bypasses constructors.
Explore solid design principles, including single responsibility principle, open-closed principle, Liskov substitution principle, interface segregation principle, and dependency inversion principle, with practical examples to build modular, maintainable code.
Learn why character arrays are preferred to strings for storing passwords in Java, avoiding string constant pool persistence, immutability, and leakage through memory dumps or logs.
Explore exception chaining by wrapping lower-layer exceptions with custom exceptions across DAO, service, and main layers, preserving the stack trace from the lowest to the highest layer.
Develop the collection of core java interview questions by gathering and analyzing java developers' interview experiences, then add the curated questions to this course.
If you are a Java Developer working in a software company, and if you are interested in switching to a higher company either for the purpose of growth, or for the purpose of hike, then the first challenge you will be facing is an Interview.
No matter how many years of experience you have, or how expert you are in Java, clearing a Java interview requires calculated planning and preparation.
In general, you may have to revise all concepts of Core Java, and then assess yourself with the help of sets of Interview questions collected from various sources.
Revising all concepts of core java with perfection, is not as easy as you think.
More specifically speaking, if you have been working on particular areas of java for a long time, then it definitely takes time to conceptually revise all the topics, especially the topics on which you have not been working on.
What if an interview is scheduled in next 2 days, or in next 2 weeks?
The situation turns into a nightmare if you do not have appropriate sources which help you get through, in just 2 days.
The only source which helps you in these situations, is none other than a set or a Collection of Core Java Interview questions, which includes interview questions collected from various Java developers based on their interview experiences.
This Course, "Core Java Interview Questions" aims to provide you the same.
You get a Collection of Core java interview Questions, which includes interview questions collected from various Java developers based on their interview experiences, with indetail explanations, and the questions also cover all concepts of CoraJava.
Note that number of Questions you get is open ended.
Whenever an interview questions comes to our notice, we just add it in the set with indetail explanation.
Hence, by purchasing this course, you are obtaining something which helps you through out your Java Development Journey.
And finally, this course comes with a 30-days Money back guarantee.
Hence, there is really nothing you loose.
I am super excited to see you enrolled in this Course.
Thank You!