Chapters Premium | Chapter-10: Past Question Part 2
Note: For all 10 chapters, please refer to the navigation section above.

Chapter-10: Past Interview Question Part 2.

Question: What is Latch in Java and can you give the example where you want to use it?
Answer: A Latch in Java is a concurrency synchronization aid that allows one or more threads to wait until a set of operations are done.
'CountDownLatch' is a classic example, which allows a thread to wait until a certain number of operations complete. It's used in scenarios where a thread needs to wait for one or more threads to complete tasks before it starts its operation. For example, you might use a 'CountDownLatch' to ensure that a service waits until several configuration files are loaded before it starts processing requests.

Question: Why Java is called static type of Programming Language?
Answer: Java is called a static type of programming language because the type checking (the process of verifying and enforcing the constraints of types) is done at compile-time rather than run-time.
In Java, all variable types are explicitly declared, and any type mismatches will result in compile-time errors.

Question: What is Dynamic Type of programming language, can you give an example of such programming language?
Answer: A dynamic type of programming language is one where the type checking is done at run-time rather than at compile-time.
This means variables can hold values of any type and their types can be changed during the execution of the program. Examples of dynamically typed languages include Python, Ruby, and JavaScript.

Question: What do you mean by Distributed application and have you worked on that application ever?
Answer: A distributed application is an application where parts of it run on multiple machines or processes to achieve a common goal. They can communicate with each other over a network.
A classic example is a web application where the front end runs on users' browsers and the backend runs on servers. Yes, I have worked on several distributed applications, including an e-commerce platform where different microservices were spread across multiple server instances for scalability and fault tolerance.

Question: What is Single Point of Failure and how would you take care of such a problem?
Answer: A Single Point of Failure (SPOF) is a part of a system that, if it fails, will cause the entire system to fail. To address SPOFs, redundancy and failover mechanisms are implemented.
For instance, instead of relying on a single server, you might deploy multiple instances of an application behind a load balancer. If one server fails, the load balancer routes traffic to the remaining healthy servers.

Question: Can you explain the internals of the ConcurrentHashMap?
Answer: 'ConcurrentHashMap' is a part of Java's concurrency package that allows concurrent reads and writes without the need for external synchronization. Internally, it divides the map into segments, each acting as an independent hashmap with its own lock.
So, instead of locking the whole map for a write operation, only a segment (or a fraction of the map) gets locked, allowing other write operations to proceed concurrently on other segments. This provides better scalability and performance in multi-threaded environments.

Question: What is the contract between equals and hashcode method?
Answer: The contract between 'equals()' and 'hashcode()' methods is:
- If two objects are equal (i.e., 'obj1.equals(obj2)' is true), then they must have the same hash code ('obj1.hashCode() == obj2.hashCode()').

- If two objects have the same hash code, they might or might not be equal.

Question: What are the minimum things required to have HashMap key?
Answer: For an object to be used as a key in a 'HashMap', it must implement the 'hashCode()' and 'equals()' methods appropriately.
A consistent implementation ensures that equal objects have the same hash code and helps in correctly retrieving the value associated with the key.

Question: Can you explain the put method on HashMap?
Answer: The 'put()' method in 'HashMap' is used to insert or set a key-value pair in the map. When 'put()' is called:
1.
The 'hashCode()' of the key is computed.
2. Using this hash code, a bucket location is determined where the key-value pair will be stored.
3. If the bucket is empty, the key-value pair is stored.
4. If the bucket already has some entries, it checks each entry's key using 'equals()' to determine if the new key is already present.
If yes, its value is updated. If not, the new key-value pair is added to the bucket.

Question: Can you explain pop, offer and remove method on the Queue Data structure?
Answer: In the context of the 'Queue' interface in Java:
- 'pop()': This method is not part of the standard 'Queue' interface but is present in the 'Stack' class.
It removes the element on the top of the stack.
- 'offer(E e)': Adds the specified element to the end of the queue if it's possible to do so without violating capacity restrictions, returning true upon success and false if no space is currently available.
- 'remove()': Retrieves and removes the head of the queue.
It throws an exception if the queue is empty.

Question: How would you get all the keys from a HashMap?
Answer: You can obtain all the keys from a 'HashMap' by calling the 'keySet()' method, which returns a 'Set' view of the keys in the map.


Question: What do you mean by FailFast, give an example?
Answer: FailFast refers to iterators that immediately throw a 'ConcurrentModificationException' if they detect that the underlying collection has been modified after the iterator was created, excluding the iterator's own 'remove' method.
This behavior ensures that inconsistencies and unpredictable behaviors do not arise. Example: The iterator of the 'ArrayList' class in Java exhibits this FailFast behavior.

Question: Can you give the difference between C++ and Java?
Answer: C++ is a multiparadigm language that supports both procedural and object-oriented programming, while Java is primarily an object-oriented language.
Some other key differences include:
- Memory Management: Java has an in-built garbage collector, whereas in C++ memory allocation and deallocation must be done manually using 'new' and 'delete'.
- Platform Dependency: Java is platform-independent due to its "Write Once, Run Anywhere" philosophy, while C++ compiled code is platform-specific.

- Pointers: C++ supports pointers; Java does not.

Question: Can you give the difference between Java and Python?
Answer: Java is statically-typed and compiled, whereas Python is dynamically-typed and interpreted. Python syntax is more concise and often considered more readable. Java has a more verbose syntax.
Additionally, Java is typically faster in execution because it's compiled to byte-code and runs on the JVM, while Python is interpreted.

Question: Write an algorithm to reverse a LinkedList?
Answer: Please check code below.
Amazon Payscale



Question: What is SQL Injection?
Answer: SQL Injection is a type of attack where malicious SQL code is inserted into a query. It exploits vulnerabilities in an application's software when user input is incorrectly sanitized or parameterized, allowing attackers to gain unauthorized access, retrieve, modify, or delete data in a database.


Question: What is the difference between an int and double and when do you use which one?
Answer: 'int' is a data type used to represent integer values, while 'double' is used for floating-point numbers.
Use 'int' when you have whole numbers without decimal points, and use 'double' when dealing with numbers that require decimal precision, such as measurements or monetary calculations.

Question: What is Asymmetric and Symmetric Encryption, can you give an example which one can be used and where?
Answer: Symmetric encryption uses a single key for both encryption and decryption. Example: AES. It's fast and suitable for large data volumes but requires the secure distribution of the key.
Asymmetric encryption uses a pair of keys: a public key for encryption and a private key for decryption. Example: RSA. It's typically used for securely transmitting keys or small amounts of data, such as in SSL/TLS for web browsers.

Question: Write a Function which can represent numbers from 0 to billion as camel case for instance HadoopExamLearningResourcesIsGoodWebSiteForPreparingCertificationAndCareerDevelopment?
Answer: This seems like a misinterpretation. Camel case convention is used for naming variables, methods, etc., by capitalizing every word except the first.
To create a camel case representation, one would split a sentence by spaces and capitalize each word's initial letter except the first one.

Question: Write an algorithm, where you can find a given point is in a rectangle or not?
Answer: Please check sample code below.
Amazon Payscale



Question: What is the Java Memory Model?
Answer: The Java Memory Model (JMM) is an abstract specification that describes how threads in Java interact with memory.
It defines how and when changes made by one thread become visible to others, guarantees about the atomicity and ordering of operations, and provides a framework for building thread-safe programs without having direct hardware-level memory semantics.

Question: Can you give the use of POST, GET, and PUT method example and use cases?
Answer:
- 'GET': Used to retrieve data from a server. Example: Fetching a webpage or retrieving data from an API. Use Case: Displaying user profile information.
- 'POST': Used to send data to a server to create a new resource.
Example: Submitting a form to create a new account. Use Case: User registration.
- 'PUT': Used to update an existing resource or create a new resource if it doesn't exist. Example: Updating user settings. Use Case: Modifying user profile information.


Question: How does MVC work in Struts?
Answer: Struts follows the MVC (Model-View-Controller) design pattern. In Struts:
- Model represents data and business logic.
- View displays the data (typically JSPs in Struts).

- Controller (Struts Action classes) handles user requests, interacts with the Model, and selects the appropriate View for response. Struts' configuration is typically defined in 'struts.xml'.


Question: Can you write an algorithm to sort an Array?
Answer: Here's a simple Bubble Sort algorithm:
Amazon Payscale


Question: Can you write a sample 'hashCode()' method implementation?
Answer: Please check sample code below.
Amazon Payscale



Question: Write an algorithm to find a lowercase letter in a String and Capitalize it?
Answer: Please check sample code below.
Amazon Payscale



Question: What is normalization?
Answer: Normalization is a process in database design that organizes tables to minimize redundancy and dependency by dividing them into smaller tables and defining relationships among them. It aims to ensure data integrity and efficient data retrieval.


Question: Can explain and give an example of Java Stream Operations?
Answer: Java Stream operations are divided into intermediate and terminal operations. For example:
Here, 'filter' and 'map' are intermediate operations, and 'forEach' is a terminal operation.
Amazon Payscale


Question: Can you explain the difference between Cookies and Session and which one you would use and when?
Answer: Cookies are small pieces of data stored on the client-side, sent with every HTTP request. Sessions are server-side storage mechanisms that maintain data across multiple requests from the same client.
Use Cookies for lightweight, non-sensitive data (like user preferences). Use Sessions for more substantial or sensitive data (like user authentication status).

Question: Can you design a Snake and Ladder game using a Java Class Diagram?
Answer: A simple class design:
- 'Game': Contains the main game loop, players, board.

- 'Player': Has properties like ID, current position.
- 'Board': Contains cells, snakes, ladders.
- 'Snake': Has start and end points.
- 'Ladder': Has start and end points.
- 'Dice': A method to roll and get a value between 1 and 6.
(Note: Actual implementation would be more detailed and complex.
)

Question: Can you normalize given data in the third normal form?
Answer: To answer this, I'd need to see the given data and its structure. Third Normal Form (3NF) ensures that all the attributes in a table are functionally dependent only on the primary key and no non-prime attribute is dependent on another non-prime attribute.


Question: Reverse a given string without using in-built function of doing it?
Answer: Please check sample code below.

Question: Can you explain what is a black tree?
Answer: I believe you mean "Red-Black tree.
Amazon Payscale
" A Red-Black tree is a self-balancing binary search tree where each node has an extra bit for denoting the color of the node, either red or black. It ensures that the tree remains approximately balanced, so operations like addition, deletion, and lookup can be done in logarithmic time.

Question: What are the indexes in a Database?
Answer: Indexes in databases are data structures that improve the speed of data retrieval operations on a database table. They work similarly to an index in a book. However, while they speed up data retrieval, they can slow down insertion, update, and deletion operations.


Question: Given two arrays write a program which can give you unique numbers of both?
Answer: Please check sample code below.

Question: What is DevOps?
Answer: DevOps is a set of practices, principles, and cultural philosophies that bridge the gap between development (Dev) and operations (Ops).
Amazon Payscale
It emphasizes collaboration, automation, and continuous integration/continuous delivery (CI/CD) to improve the speed and quality of software delivery.

Question: Which all tools have you used for DevOps?
Answer: Some commonly used DevOps tools include Jenkins (CI/CD), Docker (Containerization), Kubernetes (Container Orchestration), Ansible (Configuration Management), Git (Version Control), Prometheus (Monitoring), and Terraform (Infrastructure as Code).
The specific tools one might have used depend on their personal or organizational preferences and needs.

Question: What are ACID properties?
Answer: ACID stands for Atomicity, Consistency, Isolation, and Durability.
They are a set of properties that guarantee that database transactions are processed reliably:
- Atomicity: The whole transaction is treated as a single unit which either completes entirely or not at all.
- Consistency: The database must move from one consistent state to another after a transaction.

- Isolation: Transactions are executed in isolation from each other.
- Durability: Once committed, the effects of a transaction are permanent and can survive failures.


Question: What is TCP and UDP protocol and difference between these two?
Answer: TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are core protocols of the Internet Protocol suite.
The main differences:
- TCP: Connection-oriented, ensures data delivery, provides error checking and correction, and is used for applications requiring high reliability like web browsing, file transfer, emails.

- UDP: Connectionless, does not guarantee data delivery, faster than TCP, and is used for streaming and real-time applications like video calls, online gaming.

Question: Can you tell me what do you like about Java?
Answer: Java is platform-independent, object-oriented, and has a vast ecosystem with a plethora of libraries and frameworks.
Its strong memory management, security features, and vibrant community make it a popular choice for various application domains, from mobile to enterprise-level systems. Its motto, "Write Once, Run Anywhere," emphasizes its portability across platforms.

Question: Can you catch the 'Error'?
Answer: Yes, in Java, you can technically catch an 'Error' using a try-catch block, just as you would for exceptions. However, it's generally not recommended because errors often indicate serious problems that normal applications shouldn't attempt to handle, like 'OutOfMemoryError'.


Question: Can we have “try” block without Catch and Finally?
Answer: Yes, you can have a "try" block without a "catch" block, but in that case, you must have a "finally" block. Conversely, you can also have a "try" block with just a "catch" block and no "finally" block.
However, you can't have a "try" block standing alone without either a "catch" or "finally" block.

Question: What is the use of finalize() method and in which class it is defined?
Answer: The 'finalize()' method is used to perform clean-up operations or resource deallocations before an object's memory is reclaimed by the garbage collector.
It's defined in the 'java.lang.Object' class. However, it's important to note that relying on 'finalize()' can be unpredictable since there's no guarantee when the garbage collector will call it. It's recommended to use other resource management techniques, like the 'try-with-resources' statement.

Question: In which class 'toString()' method is defined?
Answer: The 'toString()' method is defined in the 'java.lang.Object' class. This method is often overridden in derived classes to provide a meaningful representation of the object's data.


Question: What is the difference between 'wait()' and 'sleep()' method?
Answer: The primary differences between 'wait()' and 'sleep()' are:
- 'wait()' is a method of 'Object' class, while 'sleep()' is a static method of 'Thread' class.

- 'wait()' releases the lock or monitor on the object, allowing other threads to access synchronized blocks on the same object, whereas 'sleep()' retains any locks the thread has, preventing other threads from accessing synchronized blocks on the same object.

- 'wait()' is generally used for inter-thread communication, while 'sleep()' just pauses the execution of the current thread.

Question: What all methods are used to do communication between Threads?
Answer: For inter-thread communication, Java provides methods like 'wait()', 'notify()', and 'notifyAll()' which are part of the 'Object' class.
These methods are used within synchronized blocks or methods to communicate between threads, especially in the producer-consumer problem scenarios.

Question: How can you design your own executor pool?
Answer: Designing an executor pool involves creating a pool of worker threads and managing tasks submitted for execution.
At a high level:
- Create a 'BlockingQueue' to hold tasks.
- Initialize a set number of worker threads.
- Worker threads should continuously poll the task queue and execute tasks.
- Provide methods to submit tasks, shut down the pool, etc.
However, Java already provides a robust 'ThreadPoolExecutor' in the 'java.util.
concurrent' package, which provides advanced features and is recommended for most use cases.

Question: What is the use of Executor pool?
Answer: The Executor pool, also known as a thread pool, manages a pool of worker threads.
It helps in reusing a fixed number of threads to execute a vast number of tasks, thus improving performance by reducing the overhead of thread creation and destruction. It also provides better control over resource usage and can limit the number of simultaneous threads.

Question: How do you sort 1TB file with the 128GB RAM on a single Machine using Java?
Answer: Sorting such a large file with limited RAM typically involves an external sorting algorithm:
- Divide the 1TB file into smaller chunks that can fit into memory.
- Sort each chunk in memory and then write it back to the disk.

- Once all chunks are sorted, merge the sorted chunks. This can be done using a priority queue to pick the smallest value from the top of each chunk and write it to the result file.


Question: What is JMS, and which tool have you used for that?
Answer: JMS (Java Message Service) is a Java API that allows applications to create, send, receive, and read messages in a loosely coupled, reliable, and asynchronous way.
Tools or providers that implement JMS include Apache ActiveMQ, IBM MQ, RabbitMQ, and JBoss HornetQ, among others.

Question: What is the difference between Topic and Queue?
Answer: Both Topic and Queue are destinations in JMS, but they support different messaging patterns:
- Queue (Point-to-Point messaging model): In this model, a message sent by a producer to a queue is received by one consumer only.
If multiple consumers are listening, only one will receive and process the message.
- Topic (Publish/Subscribe messaging model): In this model, a message sent by a publisher to a topic can be received by all subscribed consumers. Each subscriber gets its own copy of the message.


Question: What is the Bridge on Topic?
Answer: A bridge in messaging systems, including topics, refers to a mechanism that allows you to connect two separate messaging systems or two different destinations within the same system.
For topics, a bridge can be used to consume messages from one topic and forward them to another, possibly in a different messaging system. This is useful in scenarios where you need to integrate different applications that are not directly connected or are using different messaging systems.

Question: What is the use of JNDI and what is it?
Answer: JNDI (Java Naming and Directory Interface) is a Java API that allows applications to discover and look up data and objects via a name. It's primarily used for locating and accessing resources in various naming and directory services, like LDAP, DNS, or RMI Registry.
For example, in Java EE applications, JNDI allows you to look up data sources, EJBs, and other resources defined in the application server's context.

Question: What is Distributed transaction?
Answer: A distributed transaction spans multiple systems or databases.
It ensures that all parts of the transaction are completed successfully, and if any part fails, the entire transaction is rolled back across all systems. Two-phase commit (2PC) is a common protocol for ensuring the atomicity of distributed transactions.

Question: What is Brute Force Algorithm?
Answer: A brute force algorithm is a straightforward approach to solving a problem by trying all possible solutions until a satisfactory solution is found. While often being the simplest approach, it can be highly inefficient, especially for problems where the solution space is vast.


Question: What is the Junit code coverage for your last project?
Answer: As an AI model, I don't personally work on projects. However, for a real-world developer, a typical answer might be, "In our last project, we achieved a code coverage of around 85% using JUnit and tools like JaCoCo for measuring coverage.
"

Question: Can you tell me how does Junit helps to a developer?
Answer: JUnit is a unit testing framework that helps developers in several ways:
- It ensures code correctness by allowing developers to write test cases that validate code behavior.

- It promotes the practice of Test-Driven Development (TDD), where tests are written before the actual code.
- It helps catch regressions, ensuring that new changes don't break existing functionality.
- Provides documentation, as the tests describe expected behavior.

- Boosts confidence when refactoring, ensuring changes don't introduce new defects.

Question: Do you think writing Junit is an overhead for a developer and forced by seniors and it really reduces developer productivity?
Answer: Writing unit tests, including JUnit tests, may seem like an initial overhead.
However, in the long run, it often saves time by catching errors early, preventing costly debugging sessions, and ensuring the stability of the codebase. While it might take extra time upfront, the benefits of reduced debugging and increased code reliability usually outweigh the initial time investment.

Question: What is the meaning of Disaster recovery and how do you have it?
Answer: Disaster recovery (DR) refers to the strategies and processes in place to recover and restore an organization's critical functions and systems after a disaster or outage.
This often involves setting up backup systems or data centers, frequent data backups, and plans to switch to these systems rapidly in case of a disaster. It's essentially a strategy to ensure continuity of operations when unforeseen events occur.

Question: What is the difference between Sustainable Recovery and Disaster Recovery?
Answer: While both terms deal with recovery, their focus is different:
- Disaster Recovery (DR): As mentioned, DR is about restoring and recovering IT operations and data after a disaster. It primarily focuses on IT systems, data, and operations.

- Sustainable Recovery: This is a broader term and isn't just restricted to IT. It can refer to the long-term strategies and efforts to rebuild, restore, and sustain communities, economies, and environments after major disasters or crises.


Question: What is Divide and Conquer strategy?
Answer: Divide and Conquer is an algorithmic paradigm where a problem is divided into subproblems that are similar but smaller in size to the original problem. These subproblems are solved independently, and their solutions are combined to solve the original problem.
Classic examples of algorithms using this strategy include Merge Sort, Quick Sort, and the Fast Fourier Transform (FFT).

Question: What is the difference between OOPs and Procedural programming language?
Answer: OOP (Object-Oriented Programming) and Procedural Programming are two different programming paradigms.
The main differences are:
- OOP focuses on the creation of objects which contain both data and methods, while Procedural Programming focuses on creating reusable procedures or functions.
- OOP promotes code reusability through inheritance and polymorphism, whereas Procedural Programming typically reuses code via function calls.

- OOP structures code around real-world entities or objects, whereas Procedural Programming structures code around actions or logic.


Question: What happens if you don’t handle an exception?
Answer: If an exception is not handled, it propagates up the call stack, potentially causing the executing thread to terminate abruptly, and may lead to the entire program or application being terminated.
If the exception propagates to the top-level method (like 'main' in Java) without being caught, the program terminates with an error message.

Question: What is Runtime Exception and Compile time exception, which is difficult to manage?
Answer: Runtime exceptions (unchecked exceptions in Java) are exceptions that can occur during the execution of a program, while compile-time exceptions (checked exceptions) are those that are detected by the compiler.
Runtime exceptions typically represent defects in the program logic, whereas compile-time exceptions represent conditions that a well-written application should anticipate and recover from. Often, runtime exceptions are considered more difficult to manage because they don't have to be declared or caught, leading to potential overlooked issues.

Question: What is Heap Dump and why do you use it?
Answer: A heap dump is a snapshot of the memory of a Java process. It provides detailed information about the Java objects and classes in the heap at the moment the snapshot is triggered. Heap dumps are mainly used for debugging memory issues such as memory leaks or high memory consumption.


Question: What is thread dump and what is the use of it?
Answer: A thread dump is a snapshot of all threads that are part of a process. It provides a detailed view of what each thread is doing, including its current state, stack trace, and other diagnostic information.
Thread dumps are vital for debugging concurrency issues, deadlocks, and performance bottlenecks related to threads.

Question: How do you get the Heap Dump?
Answer: In Java, you can obtain a heap dump using tools like 'jmap'.
For instance, using the command 'jmap -dump: format=b,file= ', where '' is the name of the heap dump file and '' is the process ID of the Java process.

Question: How do you get thread dump?
Answer: In Java, you can obtain a thread dump by sending a 'SIGQUIT' signal to the JVM (using 'kill -3 ' on Unix systems) or by pressing 'Ctrl+Break' on Windows. Additionally, tools like 'jstack' can be used to capture a thread dump.


Question: Can you get heap dump and thread dump if your application is down?
Answer: If the JVM process has terminated or crashed, you won't be able to obtain a heap dump or thread dump using regular tools. However, if you've configured the JVM with certain flags, it might generate a heap dump automatically upon an 'OutOfMemoryError'.
For future instances, proactive monitoring and periodic capturing might be helpful.

Question: How do you handle the situations when your Core Java application is down in the middle of the night and you receive a call from L1 team?
Answer: In such scenarios, it's essential to have a systematic approach:
- Begin with an initial assessment: check logs, system health, network connectivity, etc.

- If the cause isn't immediately evident, consider restarting the application as a temporary measure to restore service.
- Capture necessary diagnostics, such as thread dumps and heap dumps, for post-mortem analysis.
- Coordinate with related teams or services if the issue might be external.

- Once the immediate issue is resolved, ensure a root cause analysis is performed and preventive measures are put in place.

Question: How do you make sure that whenever your Java Application is down, you or your team member immediately notified?
Answer: Implement monitoring tools and alerting systems.
Tools like Nagios, Prometheus, Grafana, or APM solutions like New Relic or Dynatrace can monitor application health and performance metrics. If any anomalies or downtimes are detected, these systems can send notifications via email, SMS, or other alerting mechanisms to the designated on-call personnel.

Disclaimer:
This ReadioBook, is intended solely for educational purposes. The author and the associated publishers have made every effort to ensure the accuracy and completeness of the information provided. However, neither the author nor the publishers can guarantee the applicability of the content in any specific circumstance.
The content presented in this ReadioBook is based on public information and feedback from candidates who have undergone the interview process with the Company. It does not contain, promote, or use any insider or proprietary information from company or any of its affiliates. The views and opinions expressed in this ReadioBook are those of the author and do not reflect or represent the views, policies, or positions of company or any of its subsidiaries.
Company, its logo, and any associated trademarks are the property of respective company. No claim is made to any rights in company's trademarks or other proprietary rights. Readers and listeners are advised to use this material as a guide and are encouraged to conduct their own research and due diligence when preparing for interviews or making career decisions. Neither the author nor the publishers are affiliated with, endorsed by, or sponsored by JP Morgan or any of its affiliates. By consuming this content, you agree not to hold the author, publishers, or any affiliated parties liable for any decisions, outcomes, or actions taken based on the information provided in this audio book.






ReadioBook.com