What are the scenario based Java interview questions you have come across?

As an experienced professional, it is natural to feel a little apprehensive when you are asked to attend a Java interview. It is an area that can be difficult to gauge your current level of skill and comfort with. After all, there is always something new to learn and the scenarios posed in the interview can be daunting. We understand your worries, which is why we have compiled a list of Java scenario based interview questions to help you prepare for your upcoming interview. These questions are focused on testing your knowledge of the fundamentals of Java and ensuring that you can apply them to a given situation. Our goal is to provide you with the resources to demonstrate your abilities as an experienced professional and ace that job interview.

Tricky Java Interview Questions

Mention a scenario where a hotspot will be able to optimize your code? Tell us how a decorator design pattern works in I/O classes? How can one call one constructor to another constructor in a class? Mention the purpose of the intern() method in the String class?

Tricky tricky scenario based java inheritance interview question[Very important for Interview]

Using real-world work experience, the automated pre-employment skill testing platform TestDome determines a candidate’s suitability for the position. By providing work skill tests to their prospects, employers can use it to quickly hire the best candidates for a position. It offers assessments for a variety of fields, including finance, programming, project management, and more.

Over 35 billion skilled workers will be needed in India over the next few years in a range of industries, including logistics, banking and financial services, security, housekeeping, call centers, and healthcare.

250 applications are reportedly received for each corporate job posting; however, only four to six of those applicants are called for interviews, and only one eventually receives a job offer. In other words, only the top 250 applicants are hired.

Q01. Scenario: For performance reasons, you must load stock exchange security codes from a database and cache them. Refreshing the security codes, say every 30 minutes, is necessary. This cached data must be updated and filled in by a…

Toptal sourced essential questions that the best Java developers and engineers can answer. Driven from our community, we encourage experts to submit questions and offer feedback.

Describe and compare fail-fast and fail-safe iterators. Give examples.

The ability to modify the collection while iterating is the primary difference between fail-fast and fail-safe iterators. Fail-safe iterators allow this; fail-fast iterators do not.

  • Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).
  • Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.
  • 2 .

    The List interface is implemented by ArrayList, LinkedList, and Vector. Explain your response, mentioning any other options you may be aware of, and which of them is most effective for adding and removing elements from the list.

    Of the three, LinkedList is generally going to give you the best performance. Here’s why:

    ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

    LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

    However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC. 3 .

    Why would storing sensitive information, like a password or social security number, be more secure? ) in a character array rather than in a String?.

    In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.

    In contrast, if you use a mutable object to store the value, such as a character array, you can set it to blank once you are finished with it and be sure that it won’t be kept in memory.

    Apply to Join Toptals Development Network

    and enjoy reliable, steady, remote Freelance Java Developer Jobs

    What is the ThreadLocal class, how would it be used, and why?

    A single ThreadLocal instance can store different values for each thread independently. Each thread that accesses the get() or set() method of a ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID). The example below, from the ThreadLocal Javadoc, generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

    As long as a thread is active and the ThreadLocal instance is reachable, it retains an implicit reference to its copy of a thread-local variable; once a thread terminates, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist). 5 .

    What, how, and why would you use the volatile keyword?

    Each thread in Java has a stack with its own copy of variables that it can access. The thread copies the values of all variables that are accessible into its own stack when it is first created. The JVM is essentially informed by the volatile keyword that “Warning, this variable may be modified in another Thread.”

    The volatile keyword ensures global ordering on reads and writes to a variable in all versions of Java. Accordingly, each thread accessing a volatile field will read the variable’s most recent value rather than (possibly) using a cached value.

    In Java 5 or later, volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.

    Using volatile may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.

    For 64-bit types like long and double, which are written in two operations, the volatile keyword is also helpful. Without the volatile keyword you risk stale or invalid values.

    For a flag to end a thread, using volatile is a typical example. You can instruct a thread to periodically check a flag (i.e., a flag) if you want to be able to safely interrupt it from another thread after you’ve started one. e. , to stop it, set the flag to true). Without even using a synchronized block, you can ensure that the thread that is checking the value of the flag will notice that it has been set to true by making the flag volatile. For example:

    Java’s sleep() and wait() methods are compared, along with when and why you might use each. the other.

    The blocking operation sleep() maintains a hold on the shared object’s monitor / lock for the specified number of milliseconds.

    While wait() does not hold onto the shared object’s monitor or lock, it simply pauses the thread for the specified number of milliseconds or until it receives a desired notification from another thread (whichever comes first).

    The most popular applications of sleep() are polling and periodic results checks. In multithreaded applications, wait() is typically used in conjunction with notify() and notifyAll() to achieve synchronization and prevent race conditions. 7 .

    Tail recursion is functionally equivalent to iteration. Explain how to convert a straightforward tail recursive function into a loop since Java does not yet support tail call optimization and why one is typically preferred over the other.

    Computing the arithmetic series 1, 2, 3…N is an example of a typical recursive function. Notice how the addition is performed after the function call. We increase the stack by one frame for each iteration of the recursive step.

    When the recursive call is in the tail position within its enclosing context, tail recursion occurs; after the function calls itself, it doesn’t do any more work. In other words, the answer is obvious once the base case is finished. For example:

    You can see how a functions as an accumulator in this example. Rather than computing the sum on the way down the stack, we compute it on the way up, effectively eliminating the need for the return trip because a doesn’t store any additional state or carry out any additional computation. The work is finished once we reach the base case; below is the same function “unrolled.”

    The JVM does not natively support tail call optimization, unlike many functional languages. We must be aware of this restriction in order to implement recursive functions in Java in order to prevent StackOverflowErrors. In Java, iteration is almost universally preferred to recursion. 8 .

    How can two numerical variables’ values be switched without using any other variables?

    Without using any other variables, you can swap the values a and b as shown below:

    In Java, how do you catch an exception that another thread has thrown?

    This can be done using Thread.UncaughtExceptionHandler.

    Here’s a simple example:

    List the three different types of class loaders, describe what each one does, and define the Java classloader.

    The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web.

    Three class loaders are used when the JVM first launches: 1 Bootstrap Classloader: Loads core java API file rt. jar from folder. 2. Extension Classloader: Loads jar files from folder. 3. The CLASSPATH environment variable specifies the path from which the system/application classloader loads jar files. 11 .

    When an exception is thrown from a try block without a catch block, is a finally block executed, and if so, when?

    Even if an exception is thrown or propagated to the calling code block, a finally block is still executed.

    Example:

    Output can vary, being either:

    Why should you avoid calling abstract methods inside an abstract class’s constructor when designing one?

    This is a problem of initialization order. There is no way to make the subclass constructor run before the parent class because it won’t have had a chance to run yet. Consider the following example class:

    An abstract widget that allows subclasses to fill in width and height and caches their initial values seems to be a good place to start. But consider the following when you specify a typical subclass implementation:

    Now we’ve introduced a subtle bug: Widget. cachedWidth and Widget. For SquareWidget instances, cachedHeight will always be 0. This is because the size = size assignment occurs after the Widget constructor runs.

    Avoid calling abstract methods in the constructors of your abstract classes as this limits the implementation options for those abstract methods. 13 .

    How much control does Java give you over the variance imposed on generic type parameters?

    Java’s generic type parameters are invariant. This means for any distinct types A and B, G is not a subtype or supertype of G. As a real world example, List is not a supertype or subtype of List. So even though String extends (i.e. is a subtype of) Object, both of the following assignments will fail to compile:

    In the form of use-site variance, Java does give you some control over this. We can use? extends Type on individual methods to generate a covariant parameter. Here’s an example:

    Longs can be passed to sum even though it is not a List but a List called longs.

    Similarly, ? super Type lets a method parameter be contravariant. Consider a function with a callback parameter:

    Any callback that manages a supertype of Number will work because forEachNumber permits Callback to be a subtype of Callback:

    The provision of a callback that only deals with Long (a subtype of Number) will, however, fail as expected:

    Applying use-site variance liberally can stop many unsafe casts from occurring in Java code, which is essential when designing interfaces used by multiple developers. 14 .

    What are static initializers and when would you use them?

    When a class is first loaded, you have the option to run code, and a static initializer ensures that this code will only run once and will be finished before your class can be accessed in any way.

    They come in handy when initializing intricate static objects or when registering a type with a static registry, as JDBC drivers do.

    Consider making a static, immutable Map with a few feature flags. You can use static initializers in Java since there isn’t a good one-liner for initializing maps:

    Since multiple static initializers are permitted within a single class, you can repeat this pattern of declaring a static field and initializing it right away. 15 .

    How do you choose between HashSet and Set if you need one? TreeSet?.

    HashSet appears to be nearly unbeatable at first glance: O(1) add, remove, and contains vs O(log(N)) for TreeSet.

    However, TreeSet is essential if you want to keep the inserted elements in order or search for a specific subset of the set’s elements.

    Consider a Set of timestamped Event objects. They could be kept in a HashSet with equals and a timestamp-based hashCode. This is effective storage and enables looking up events by a specific timestamp, but how do you get all the events that occurred on a given day? That would require a traversal of the HashSet in O(n), but with TreeSet, the tailSet method, it’s only an O(log(n)) operation:

    TreeSet allows us to pass in our own Comparator if Event is a class that we cannot extend or that does not implement Comparable:

    In general, TreeSet is a good option when reads are balanced against the higher cost of writes and when order is important. 16 .

    What are method references, and how are they useful?

    Since Java 8’s introduction of method references, constructors and methods—whether static or not—can be used as lambdas. When the method reference matches an expected signature, they permit one to remove the boilerplate of a lambda.

    As an illustration, let’s say we have a service that needs to be terminated by a shutdown hook. Before Java 8, we would have code like this:

    With lambdas, this can be cut down considerably:

    However, stop matches the signature of Runnable. run (void return type, no parameters), allowing us to add a method reference to that particular SomeBusyService instance’s stop method:

    In contrast to verbose code, this is terse and communicates the situation clearly.

    Additionally, method references aren’t restricted to a single instance; they can be used to refer to any object, which is advantageous for Stream operations. For instance, let’s say we have a Person class and only want a group of people’s lowercase names:

    Another option is to insert a complex lambda into a static or instance method and then use a method reference to access it. Compared to if the code were “trapped” in the lambda, it is now more reusable and testable.

    Therefore, it is clear that method references are primarily used to enhance the organization, clarity, and conciseness of code. 17 .

    How can this capability be used to make Java enums more powerful than integer constants?

    In essence, enums are final classes with a predetermined number of instances. They can implement interfaces but cannot extend another class.

    When implementing the strategy pattern, for instance, when the number of strategies is fixed, this flexibility is helpful. Consider an address book that records multiple methods of contact. We can represent these methods as an enum and include fields for any corresponding behavior, such as how to initiate contact using that method, as well as the filename of the icon that will be displayed in the user interface:

    By using instances of ContactMethod, we can completely avoid switch statements:

    What is possible with enums is just getting started. Enums should typically be used instead of integer constants due to their safety and flexibility, and switch statements can be avoided by using a lot of abstract methods. 18 .

    What does it mean for a collection to be “backed by” another collection? Describe the use cases for this property.

    If one collection supports another, changes made to one will be reflected in the other and vice versa.

    Assume, for instance, that we wanted to develop a whitelist function that would eliminate invalid keys from a Map. This is made far easier with Map. keySet, which gives a set of keys supported by the initial map, returns Keys are also removed from the backing map when we remove them from the key set:

    We can easily implement something that would otherwise require iterating over the entries in the input map and comparing them against allowedKey, etc., by using retainAll, which writes through to the backing map.

    Note that it’s critical to review the backing collection’s documentation to determine which modifications will write through. In the example above, map. keySet(). We cannot add a key to the backing map without a value, so add(value) would fail. 19 .

    Give a definition of reflection and an illustration of a feature that can only be implemented using reflection.

    Programmatic access to information about the types of a Java program is made possible by reflection. A class’s available methods and fields, interfaces it implements, and runtime-retained annotations on its classes, fields, and methods are examples of information that is frequently used.

    Examples given are likely to include:

  • Annotation-based serialization libraries often map class fields to JSON keys or XML elements (using annotations). These libraries need reflection to inspect those fields and their annotations and also to access the values during serialization.
  • Model-View-Controller frameworks call controller methods based on routing rules. These frameworks must use reflection to find a method corresponding to an action name, check that its signature conforms to what the framework expects (e.g. takes a Request object, returns a Response), and finally, invoke the method.
  • Dependency injection frameworks lean heavily on reflection. They use it to instantiate arbitrary beans for injection, check fields for annotations such as @Inject to discover if they require injection of a bean, and also to set those values.
  • Object-relational mappers such as Hibernate use reflection to map database columns to fields or getter/setter pairs of a class, and can go as far as to infer table and column names by reading class and getter names, respectively.
  • An easy example of concrete code would be to copy the fields from an object into a map:

    Such techniques are beneficial for debugging and for utility methods like the toString method, which can be used with any class.

    Direct use of reflection is uncommon outside of the implementation of generic libraries, but it is still a useful tool to have. Understanding reflection is helpful for when these mechanisms break down.

    However, reflection should generally be avoided unless absolutely necessary because it can cause runtime errors to arise from simple compiler errors. 20 .

    Nested classes, also known as inner classes, can be static or non-static. How do you decide which to use? Does it matter?.

    Inner classes have complete access to the fields and methods of the enclosing class, which is the primary distinction between and. Event handlers may find this useful, but it has a drawback: Every instance of an inner class maintains and needs a reference to its enclosing class.

    There are numerous instances where we should favor static nested classes keeping this cost in mind. To avoid memory leaks, nested classes should be static when their instances will outlive those of the enclosing class. Consider this implementation of the factory pattern:

    This design appears to be good at first glance: the WidgetParserFactory conceals the parser’s implementation details with the nested class WidgetParserImpl. WidgetParserFactory will leak along with all the references it contains because WidgetParserImpl is not static and cannot be discarded after the WidgetParser is created.

    If WidgetParserImpl needs access to any of WidgetParserFactory’s internals, they should be passed to WidgetParserImpl’s constructor rather than being made static. Additionally, should WidgetParserImpl outgrow its parent class, this makes it simpler to extract it into a new class.

    Due to their “hidden” reference to the enclosing class, inner classes are also more difficult to construct via reflection. This reference can also become entangled during reflection-based serialization, which is probably not intended.

    As a result, it is crucial to consider whether to make nested classes static. Nested classes should ideally be static in situations where instances will “escape” the enclosing class or when reflection on those nested classes is required. 21 .

    Which is superior, and why, between String s = “Test” and String s = new String(“Test”)?

    In general, using String s = “Test” instead of String s = new String(“Test”) is more effective.

    A String with the value “Test” will be created in the String pool if String s = “Test.” If a second String is created with the same value (e.g. g. , String s2 = “Test”), the String pool will contain a reference to the same object.

    However, if you use String s = new String(“Test”), that String object will also be passed to the constructor of the String Object (i) in addition to creating a String with the value “Test” in the String pool. e. , new String(“Test”)) will generate a new String object with that value that isn’t in the String pool. Therefore, every such call will produce an additional String object (e g. Instead of just using the same String object from the String pool, String s2 = new String(“Test”) would create an additional String object.)

    These are only meant to be a guide because there are other aspects of interviews besides trying technical questions. Not all “A” candidates who are worth hiring will be able to respond to all of them, and responding to all of them does not guarantee an “A” candidate. Hiring is still ultimately a science, an art, and a lot of work.

    Not sure what questions to ask to land a top hire or sick of interviewing candidates?

    Let Toptal find the best people for you.

    Our Exclusive Network of Java Developers

    Looking to land a job as a Java Developer?

    Let Toptal find the right job for you.

    Job Opportunities From Our Network

    Submissions are subject to review and editing by Toptal, LLC, who has the sole authority to decide whether or not to post them.

    Looking for Java Developers? Check out Toptal’s Java developers.

    Radek is a blockchain engineer certified by Toptal who has a particular interest in Ethereum and smart contracts. He has worked on big data and machine learning projects for Fiat. He co-created the PlayStation 4’s back end, won three awards in two international IBM Apache Spark competitions, competed successfully in hackathons, and has spoken at conferences in Australia, Poland, and Serbia.

    Rizwan is known for overcoming complex problems by using clear thinking, creative solutions, and improving communication within organizations. Throughout his career, he has consistently produced profitable project outcomes in difficult environments by maximizing the efforts of diverse and dispersed teams of IT professionals.

    James has a long history of offering technological solutions to complex issues. His craft is software engineering, and he is constantly looking to learn new things to raise the caliber of his output. James has earned the respect of his former employers and coworkers for his quick comprehension of a problem domain, his transparent and open communication, and his timely creation of well-structured technological solutions.

    The Top 3% of Freelancers in the World Are Connected by Toptal

    FAQ

    How can I prepare for Java experienced interview?

    Which topics to prepare for Java interviews?
    1. Java Fundamentals.
    2. Data Structure and Algorithms.
    3. Object-Oriented Concepts.
    4. Multithreading, concurrency, and thread basics.
    5. Java Collections Framework.
    6. Date type conversion and fundamentals.
    7. Array.
    8. Garbage Collection.

    How do I prepare for Java interview for 12 years experience?

    Which Topics to Prepare for Java Interviews?
    1. Java Fundamentals.
    2. Object-Oriented Concepts (questions)
    3. Data Structure and Algorithms (questions)
    4. Multithreading, concurrency, and thread basics (questions)
    5. Date type conversion and fundamentals (questions)
    6. Garbage Collection (questions)
    7. Java Collections Framework (questions)

    What are the scenarios for Java?

    A Java program called a scenario is used to test various aspects of your application. The following methods are necessary for your scenario: A play(GhostRunner runner) method, which specifies the user interaction sequence to play; this is the order in which the tests are run.

    What are scenario based questions examples?

    Here are more examples of situational questions that interviewers may ask during an interview:
    • Describe a time when you had to put something else ahead of your work.
    • If you didn’t agree with a choice your manager made, what would you do?
    • Describe a time when you had to deal with a irate client.

    Related Posts

    Leave a Reply

    Your email address will not be published. Required fields are marked *