Java Questions - Top 10 Most Viewed Questions on Stack Overflow

Java Questions - Top 10 Most Viewed Questions on Stack Overflow

In this Java Interview Questions we are going to examine the top 10 most viewed Java question on Stack Overflow since creation of this platform. This questions are covering essential parts of Java and because of that we all should know and understand them!

In this course we are going to examine the top 10 most viewed Java question on Stack Overflow since creation of this platform (*state October 2019)

Stack Overflow itself has according to wikipedia over 10 million registered users and has exceeded over 16 million questions.

This is why I believe that every software developer should get in touch with them. They are covering the essential parts of the programming language and because of that we all should know about them.

I will explain everything what you will need to first understand the questions and then be able to answer them on your own.

What topics can you expect within this course?

  • I will explain to you what references on objects are and how Java saves them internally. We take a closer look to the so called null reference that often results in NullPointerExceptions.

  • We get to know several data structures, such as Maps, HashMaps, Sets and many more.

  • How do I compare two strings, or more general two objects with each other? And what has Java's String pool to do with it?

  • We become acquainted with syntactical abbreviations like the for-each-loop or try-with-resource statement.

  • We answer the eternal question if Java is a call by reference or call by value language or maybe both?

  • How can I create random numbers in general or within specific range? And what do I have to take account of, if I am developing multi-threaded applications?

  • We learn what FileOutputStreams and PrintWriters are for and how to use them to create files and fill them with datas.

  • And many more

What you'll learn

  • 🚀 References on objects, how Java handles them internally, NullPointerException
  • 🚀 Comparison of objects via == and equals.
  • 🚀 How to create and fill files with the help of streams
  • 🚀 What does call by value and call by reference mean? And what does Java use?
  • 🚀 Syntactical sugar like the for-each-loop
  • 🚀 and many more

50+ Java Interview Questions for Programmers

50+ Java Interview Questions for Programmers

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection Framework, Java Multithreading and Concurrency, Java IO, JDBC, JVM Internals, Coding Problems, Object-Oriented programming, etc.

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection Framework, Java Multithreading and Concurrency, Java IO, JDBC, JVM Internals, Coding Problems, Object-Oriented programming, etc.

Are you ready for your next Java interview?

Hello, guys! Recently, I have been sharing a lot of Java Interview questions and discussion individually, and many of my readers requested to bring them together so that they can have them in the same page and prepare better and this post is the result of that.

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection Framework, Java Multithreading and Concurrency, Java IO, JDBC, JVM Internals, Coding Problems, Object-Oriented programming, etc.

The questions are also picked up from various interviews and they are, by no means, very difficult, and you might have seen them already in your telephonic or face-to-face round of interview.

The questions are also very good to revise important topics like multithreading and collections as I have also shared some useful resources for further learning and improvement like The Complete Java MasterClass to brush up and fill gaps in your Java skills.

So what are we waiting for here is the list of some of the frequently asked Java questions from interviews from both beginner and experienced Java developer of 2 to 5 years experience:

Java Interview Questions and Answers
  1. How Java achieves platform independence? (answer)
  2. hint: bytecode and Java Virtual Machine
  3. What is **ClassLoader** in Java? (answer)
  4. hint: part of JVM that loads bytecodes for classes. You can write your own.
  5. Write a Java program to check if a number is Even or Odd? (answer)
  6. hint: you can use bitwise operator, e.g. bitwise AND &, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.
  7. Difference between **ArrayList** and **HashSet** in Java? (answer)
  8. hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc.
  9. What is double checked locking in Singleton? (answer)
  10. hint: two-time check whether instances is initialized or not, first without locking and second with locking.

6) How do you create thread-safe Singleton in Java? (answer)

hint: many ways, e.g. using Enum or by using double-checked locking pattern or using a nested static class.

7) When to use volatile variable in Java? (answer)

hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

8) When to use a transient variable in Java? (answer)

hint: when you want to make a variable non-serializable in a class, which implements the Serializable interface. In other words, you can use it for a variable whose value you don’t want to save. See The Complete Java MasterClass to learn about transient variables in Java.

9) Difference between the transient and volatile variable in Java? (answer)

hint: totally different, one used in the context of serialization while the other is used in concurrency.

10) Difference between Serializable and Externalizable in Java? (answer)

hint: Externalizable gives you more control over the Serialization process.

11) Can we override the private method in Java? (answer)

hint: No, because it’s not visible in the subclass, a primary requirement for overriding a method in Java.

12) Difference between **Hashtable** and **HashMap** in Java? (answer)

hint: several but most important is Hashtable, which is synchronized, while HashMap is not. It’s also legacy and slow as compared to HashMap.

13) Difference between **List**and **Set**in Java? (answer)

hint: List is ordered and allows duplicate. Set is unordered and doesn’t allow duplicate elements.

14) Difference between **ArrayList** and **Vector** in Java (answer)

hint: Many, but most important is that ArrayList is non-synchronized and fast while Vector is synchronized and slow. It’s also legacy class like Hashtable.

15) Difference between **Hashtable** and **ConcurrentHashMap** in Java? (answer)

hint: more scalable

16) How does **ConcurrentHashMap** achieve scalability? (answer)

hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an **Object** to be used as **Key** in **HashMap**? (answer)

hint: equals and hashcode

18) Difference between wait and sleep in Java? (answer)

hint: The wait() method releases the lock or monitor, while sleep doesn’t.

19) Difference between **notify** and **notifyAll** in Java? (answer)

hint: notify notifies one random thread is waiting for that lock while notifyAll inform to all threads waiting for a monitor. If you are certain that only one thread is waiting then use notify, or else notifyAll is better. See Threading Essentials Mini-Course by Java Champion Heinz Kabutz to learn more about threading basics.

20) Why you override hashcode, along with **equals()** in Java? (answer)

hint: to be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes, e.g. HashMap or ArrayList.

21) What is the load factor of **HashMap** means? (answer)

hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means HashMap resize itself if it’s 75 percent full.

22) Difference between **ArrayList** and **LinkedList** in Java? (answer)

hint: same as an array and linked list, one allows random search while other doesn’t. Insertion and deletion easy on the linked list but a search is easy on an array. See Java Fundamentals: Collections Richard Warburton course on Pluralsight to learn more about essential Collection data structure in Java.

23) Difference between **CountDownLatch** and **CyclicBarrier** in Java? (answer)

hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse CountDownLatch  after the count reaches to zero.

24) When do you use **Runnable** vs **Thread** in Java? (answer)

hint: always

25) What is the meaning of Enum being type-safe in Java? (answer)

hint: It means you cannot assign an instance of different Enum type to an Enum variable. e.g. if you have a variable like DayOfWeek day then you cannot assign it value from DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? (answer)

hint: using valueOf() method

27) Difference between **PATH** and **Classpath** in Java? (answer)

hint: PATH is used by the operating system while Classpath is used by JVM to locate Java binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn more about PATH, Classpath, and other Java environment variable.

28) Difference between method overloading and overriding in Java? (answer)

hint: Overriding happens at subclass while overloading happens in the same class. Also, overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? (answer)

hint: just make its constructor private

30) How do you restrict your class from being used by your client? (answer)

hint: make the constructor private or throw an exception from the constructor

31) Difference between **StringBuilder** and **StringBuffer** in Java? (answer)

hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? (answer)

hint: Inheritance allows code reuse and builds the relationship between class, which is required by Polymorphism, which provides dynamic behavior. See Java Fundamentals: Object-Oriented Design to learn more about OOP features.

33) Can we override static method in Java? (answer)

hint: No, because overriding resolves at runtime while static method call is resolved at compile time.

34) Can we access the private method in Java? (answer)

hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? (answer)

hint: from Java 8, the difference is blurred. However, a Java class can still implement multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? (answer)

hint: DOM loads whole XML File in memory while SAX doesn’t. It is an event-based parser and can be used to parse a large file, but DOM is fast and should be preferred for small files.

37) Difference between throw and throws keyword in Java? (answer)

hint: throws declare what exception a method can throw in case of error but throw keyword actually throws an exception. See Java Fundamentals: Exception Handling to learn more about Exception handling in Java.

38) Difference between fail-safe and fail-fast iterators in Java? (answer)

hint: fail-safe doesn’t throw ConcurrentModificationException while fail-fast does whenever they detect an outside change on the underlying collection while iterating over it.

39) Difference between Iterator and Enumeration in Java? (answer)

hint: Iterator also gives you the ability to remove an element while iterating while Enumeration doesn’t allow that.

40) What is **IdentityHashMap** in Java? (answer)

hint: A Map, which uses the == equality operator to check equality instead of the equals() method.

41) What is **String** pool in Java? (answer)

hint: A pool of String literals. Remember it’s moved to heap from perm gen space in JDK 7.

42) Can a **Serializable** class contain a non-serializable field in Java? (answer)

hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? (answer)

hint: this refers to the current instance while super refers to an instance of the superclass.

44) Difference between **Comparator** and **Comparable** in Java? (answer)

hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String. See The Complete Java MasterClass to learn more about sorting in Java.

45) Difference between **java.util.Date** and **java.sql.Date** in Java? (answer)

hint: former contains both date and time while later contains only date part.

46) Why wait and notify method are declared in **Object** class in Java? (answer)

hint: because they require lock which is only available to an object.

47) Why Java doesn’t support multiple inheritances? (answer)

hint: It doesn’t support because of bad experience with C++, but with Java 8, it does in some sense — only multiple inheritances of Type are not supported in Java now.

48) Difference between checked and unchecked Exception in Java? (answer)

hint: In case of checked, you must handle exception using catch block, while in case of unchecked, it’s up to you; compile will not bother you.

49) Difference between Error and Exception in Java? (answer)

hint: I am tired of typing please check the answer

50) Difference between race condition and deadlock in Java? (answer)

hint: both are errors that occur in a concurrent application, one occurs because of thread scheduling while others occur because of poor coding.

Best Java Microservices Interview Questions In 2019

Best Java Microservices Interview Questions In 2019

In this Microservices interview questions article, I have collected the most frequently asked questions by interviewers. These questions are collected after consulting with Microservices Certification Training experts. Let's discuss the best Java Microservices Interview Questions In 2019

Top Microservices Interview Questions

According to Gartner, **microservices **are the new application platform for cloud development. **Microservices **are deployed and managed independently, and once implemented inside containers they have very little interaction with the underlying OS. So, if you are planning to start your career in the **Microservices **and you wish to know the skills related to it, now is the right time to dive in, when the technology is in its nascent state.

In case you have attended any **Microservices interview **in the recent past, do paste those interview questions in the comments section and we’ll answer them ASAP. You can also comment below if you have any **questions **in your mind, which you might face in your Microservices interview.

You may go through this recording of Microservices Interview Questions and **Answers **where our instructor has explained the topics in a detailed manner with examples that will help you to **understand **this concept better.

Q1. List down the advantages of Java Microservices Architecture.

Q2. What do you know about Microservices?

Microservices, aka Microservice Architecture, is an architectural style that structures an application as a collection of small autonomous services, modeled around a **business domain.**In layman terms, you must have seen how bees build their honeycomb by aligning hexagonal wax cells.They initially start with a small section using various materials and continue to build a large beehive out of it.These cells form a pattern resulting in a strong structure which holds together a particular section of the beehive.Here, each cell is independent of the other but it is also correlated with the other cells.This means that damage to one cell does not damage the other cells, so, bees can reconstruct these cells without impacting the complete beehive.

Fig 1: Beehive Representation of Microservices – Microservices Interview Questions

Refer to the above diagram. Here, each hexagonal shape represents an individual service component. Similar to the working of bees, each agile team builds an individual service component with the available frameworks and the chosen technology stack. Just as in a beehive, each service component forms a strong microservice architecture to provide better scalability. Also, issues with each service component can be handled individually by the agile team with no or minimal impact on the entire application.

Q3. What are the features of Microservices?

Fig 3: Features of Microservices – Microservices Interview Questions
Decoupling – Services within a system are largely decoupled. So the application as a whole can be easily built, altered, and scaled
Componentization
– Microservices are treated as independent components that can be easily replaced and upgradedBusiness Capabilities – Microservices are very simple and focus on a single capabilityAutonomy – Developers and teams can work independently of each other, thus increasing speedContinous Delivery – Allows frequent releases of software, through systematic automation of software creation, testing, and approvalResponsibility – Microservices do not focus on applications as projects. Instead, they treat applications as products for which they are responsibleDecentralized Governance – The focus is on using the right tool for the right job. That means there is no standardized pattern or any technology pattern. Developers have the freedom to choose the best useful tools to solve their problemsAgility – Microservices support agile development. Any new feature can be quickly developed and discarded again## Q4. What are the best practices to design Microservices?

The following are the best practices to design microservices:

**Fig 4: **Best Practices to Design Microservices – Microservices Interview Questions

Q5. How does Microservice Architecture work?

A microservice architecture has the following components:

**Fig 5: **Architecture of Microservices – Microservices Interview Questions
Clients – Different users from various devices send requests.Identity Providers – Authenticates user or clients identities and issues security tokens.API Gateway – Handles client requests.Static Content – Houses all the content of the system.Management – Balances services on nodes and identifies failures.Service Discovery – A guide to find the route of communication between microservices.Content Delivery Networks – Distributed network of proxy servers and their data centers.Remote Service – Enables the remote access information that resides on a network of IT devices.## Q6. What are the pros and cons of Microservice Architecture?

Q7. What is the difference between Monolithic, SOA and Microservices Architecture?

**Fig 6: **Comparison Between Monolithic SOA & Microservices – Microservices Interview Questions
Monolithic Architecture is similar to a big container wherein all the software components of an application are assembled together and tightly packaged.A Service-Oriented Architecture is a collection of services which communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity.Microservice Architecture is an architectural style that structures an application as a collection of small autonomous services, modeled around a business domain.## Q8. What are the challenges you face while working Microservice Architectures?

Developing a number of smaller microservices sounds easy, but the challenges often faced while developing them are as follows.
Automate the Components: Difficult to automate because there are a number of smaller components. So for each component, we have to follow the stages of Build, Deploy and, Monitor.Perceptibility: Maintaining a large number of components together becomes difficult to deploy, maintain, monitor and identify problems. It requires great perceptibility around all the components.Configuration Management: Maintaining the configurations for the components across the various environments becomes tough sometimes.Debugging: Difficult to find out each and every service for an error. It is essential to maintain centralized logging and dashboards to debug problems.## Q9. What are the key differences between SOA and Microservices Architecture?

The key differences between SOA and microservices are as follows:

Q10. What are the characteristics of Microservices?

You can list down the characteristics of microservices as follows:

**Fig 7: **Characteristics of Microservices – Microservices Interview Questions

Q11. What is Domain Driven Design?

**Fig 8: **Principles of DDD – Microservices Interview Questions

Q12. Why there is a need for Domain Driven Design (DDD)?

**Fig 9: **Factors Why we need DDD – Microservices Interview Questions

Q13. What is Ubiquitous language?

If you have to define the** Ubiquitous Language (UL)**, then it is a common language used by developers and users of a specific domain through which the domain can be explained easily.

The ubiquitous language has to be crystal clear so that it brings all the team members on the same page and also translates in such a way that a machine can understand.

Q14. What is Cohesion?

The degree to which the elements inside a module belong together is said to be cohesion.

Q15. What is Coupling?

The measure of the strength of the dependencies between components is said to be coupling. A good design is always said to have High Cohesion and** Low Coupling**.

Q16. What is REST/RESTful and what are its uses?

Representational State Transfer (REST)/RESTful web services are an architectural style to help computer systems communicate over the internet. This makes microservices easier to understand and implement.

Microservices can be implemented with or without RESTful APIs, but it’s always easier to build loosely coupled microservices using RESTful APIs.

Q17. What do you know about Spring Boot?

It’s a knows fact that spring has become more and more complex as new functionalities have been added. If you have to start a new spring project, then you have to add build path or add maven dependencies, configure application server, add spring configuration. So everything has to be done from scratch.

Spring Boot is the solution to this problem. Using spring boot you can avoid all the boilerplate code and configurations. So basically consider yourself as if you’re baking a cake spring is like the ingredients that are required to make the cake and spring boot is the complete cake in your hand.

**Fig 10: **Factors of Spring Boot – Microservices Interview Questions

Q18. What is an actuator in Spring boot?

Spring Boot actuator provides restful web services to access the current state of running an application in the production environment. With the help of actuator, you can check various metrics and monitor your application.

Q19. What is Spring Cloud?

According to the official website of Spring Cloud, Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, leadership election, distributed sessions, cluster state).

Q20. What problems are solved by Spring Cloud?

While developing distributed microservices with Spring Boot we face few issues which are solved by Spring Cloud.
**The complexity associated with distributed systems – **This includes network issues, Latency overhead, Bandwidth issues, security issues.**Ability to handle Service Discovery – **Service discovery allows processes and services in a cluster to find each other and communicate.**Solved redundancy issues – **Redundancy issues often occur in distributed systems.**Load balancing – **Improves the distribution of workloads across multiple computing resources, such as a computer cluster, network links, central processing units.**Reduces performance issues – **Reduces performance issues due to various operational overheads.## Q21. What is the use of WebMvcTest annotation in Spring MVC applications?

WebMvcTest annotation is used for unit testing Spring MVC Applications in cases where the test objective is to just focus on Spring MVC Components. In the snapshot shown above, we want to launch only the ToTestController. All other controllers and mappings will not be launched when this unit test is executed.

Q22. Can you give a gist about Rest and Microservices?

REST

Though you can implement microservices in multiple ways, REST over HTTP is a way to implement Microservices. REST is also used in other applications such as web apps, API design, and MVC applications to serve business data.

Microservices

Microservices is an architecture wherein all the components of the system are put into individual components, which can be built, deployed, and scaled individually. There are certain principles and best practices of Microservices that help in building a resilient application.

In a nutshell, you can say that REST is a medium to build Microservices.

Q23. What are different types of Tests for Microservices?

While working with microservices, testing becomes quite complex as there are multiple microservices working together. So, tests are divided into different levels.
At the bottom level, we have technology-facing tests like- unit tests and performance tests. These are completely automated.At the middle level, we have tests for exploratory testing like the stress tests and usability tests.At the **top level, **we have acceptance tests that are few in number. These acceptance tests help stakeholders in understanding and verifying software features.## Q24. What do you understand by Distributed Transaction?

Distributed Transaction is any situation where a single event results in the mutation of two or more separate sources of data which cannot be committed atomically. In the world of microservices, it becomes even more complex as each service is a unit of work and most of the time multiple services have to work together to make a business successful.

Q25. What is an Idempotence and where it is used?

Idempotence is the property of being able to do something twice in such a way that the end result will remain the same i.e. as if it had been done once only.

Usage: Idempotence is used at the remote service, or data source so that, when it receives the instruction more than once, it only processes the instruction once.

Q26. What is Bounded Context?

Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD’s strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their inter-relationships.

Q27. What is Two Factor Authentication?

Two-factor authentication enables the second level of authentication to an account log-in process.

**Fig11: **Representation of Two Factor Authentication – Microservices Interview Questions

So suppose a user has to enter only username and password, then that’s considered a single-factor authentication.

Q28. What are the types of credentials of Two Factor Authentication?

The three types of credentials are:

**Fig 12: **Types of Credentials of Two Factor Authentication – Microservices Interview Questions

Q29. What are Client certificates?

A type of digital certificate that is used by client systems to make authenticated requests to a remote server is known as the** client certificate**. Client certificates play a very important role in many mutual authentication designs, providing strong assurances of a requester’s identity.

Q30. What is the use of PACT in Microservices architecture?

**PACT **is an open source tool to allow testing interactions between service providers and consumers in isolation against the contract made so that the reliability of Microservices integration increases.

Usage in Microservices:

Used to implement Consumer Driven Contract in Microservices.Tests the consumer-driven contracts between consumer and provider of a Microservice.## Q31. What is OAuth?

**OAuth **stands for open authorization protocol. This allows accessing the resources of the resource owner by enabling the client applications on HTTP services such as third-party providers Facebook, GitHub, etc. So with this, you can share resources stored on one site with another site without using their credentials.

Q32. What is Conway’s law?

“Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization’s communication structure.” –*** Mel Conway***

**Fig 13: **Representation of Conway’s Law – Microservices Interview Questions

This law basically tries to convey the fact that, in order for a software module to function, the complete team should communicate well. Therefore the structure of a system reflects the social boundaries of the organization(s) that produced it.

Q33. What do you understand by Contract Testing?

According to Martin Flower,** contract test **is a test at the boundary of an external service which verifies that it meets the contract expected by a consuming service.

Also, contract testing does not test the behavior of the service in depth. Rather, it tests that the inputs & outputs of service calls contain required attributes and the response latency, throughput is within allowed limits.

Q34. What is End to End Microservices Testing?

End-to-end testing validates each and every process in the workflow is functioning properly. This ensures that the system works together as a whole and satisfies all requirements.

In layman terms, you can say that end to end testing is a kind of tests where everything is tested after a particular period.

**Fig 14: **Hierarchy of Tests – Microservices Interview Questions

Q35. What is the use of Container in Microservices?

Containers are a good way to manage microservice based application to develop and deploy them individually*.* You can encapsulate your microservice in a container image along with its dependencies, which then can be used to roll on-demand instances of microservice without any additional efforts required.

**Fig 15: **Representation of Containers and How they are used in Microservices – Microservices Interview Questions

Q36. What is DRY in Microservices architecture?

DRY stands for Don’t Repeat Yourself. It basically promotes the concept of reusing the code. This results in developing and sharing the libraries which in turn result in tight coupling.

Q37. What is a Consumer-Driven Contract (CDC)?

This is basically a pattern for developing Microservices so that they can be used by external systems. When we work on microservices, there is a particular provider who builds it and there are one or more consumers who use Microservice.

Generally, providers specify the interfaces in an XML document. But in Consumer Driven Contract, each consumer of service conveys the interface expected from the Provider.

Q38. What is the role of Web, RESTful APIs in Microservices?

A microservice architecture is based on a concept wherein all its services should be able to interact with each other to build a business functionality. So, to achieve this, each microservice must have an interface. This makes the web API a very important enabler of microservices. Being based on the open networking principles of the Web, RESTful APIs provide the most logical model for building interfaces between the various components of a microservice architecture.

Q39. What do you understand by Semantic monitoring in Microservices architecture?

Semantic monitoring, also known as** synthetic monitoring** combines automated tests with monitoring the application in order to detect business failing factors.

Q40. How can we perform Cross-Functional testing?

Cross-functional testing is a verification of non-functional requirements, i.e. those requirements which cannot be implemented like a normal feature.

Q41. How can we eradicate non-determinism in tests?

Non-Deterministic Tests (NDT) are basically unreliable tests. So, sometimes it may happen that they pass and obviously sometimes they may also fail. As and when they fail, they are made to re-run to pass.

Some ways to remove non-determinism from tests are as follows:
QuarantineAsynchronousRemote ServicesIsolationTimeResource leaks## Q42. What is the difference between Mock or Stub?

Stub

A dummy object that helps in running the test.Provides fixed behavior under certain conditions which can be hard-coded.Any other behavior of the stub is never tested.
For example, for an empty stack, you can create a stub that just returns true for empty() method. So, this does not care whether there is an element in the stack or not.

Mock

A dummy object in which certain properties are set initially.The behavior of this object depends on the set properties.The object’s behavior can also be tested.
For example, for a Customer object, you can mock it by setting name and age. You can set age as 12 and then test for isAdult() method that will return true for age greater than 18. So, your Mock Customer object works for the specified condition.

Q43. What do you know about Mike Cohn’s Test Pyramid?

Mike Cohn provided a model called Test Pyramid. This describes the kind of automated tests required for software development.

**Fig 16: **Mike Cohn’s Test Pyramid – Microservices Interview Questions

As per pyramid, the number of tests at first layer should be highest. At service layer, the number of tests should be less than at the unit test level, but more than at the end-to-end level.

Q44. What is the purpose of Docker?

Docker provides a container environment that can be used to host any application. In this, the software application and the dependencies which support it are tightly-packaged together.

So, this packaged product is called a Container and since it is done by Docker, it is called Docker container!

Q45. What is Canary Releasing?

Canary Releasing is a technique to reduce the risk of introducing a new software version in production. This is done by slowly rolling out the change to a small subset of users before giving it out to the entire infrastructure, i.e. making it available to everybody.

Q46. What do you mean by Continuous Integration (CI)?

Continuous Integration (CI) is the process of automating the build and testing of code every time a team member commits changes to version control. This encourages developers to share code and unit tests by merging the changes into a shared version control repository after every small task completion.

Q47. What is Continuous Monitoring?

**Continuous monitoring **gets into the depth of monitoring coverage, from in-browser front-end performance metrics, through application performance, and down to host virtualized infrastructure metrics.

Q48. What is the role of an architect in Microservices architecture?

An architect in microservices architecture plays the following roles:
Decides broad strokes about the layout of the overall software system.Helps in deciding the zoning of the components. So, they make sure components are mutually cohesive, but not tightly coupled.Code with developers and learn the challenges faced in day-to-day life.Make recommendations for certain tools and technologies to the team developing microservices.Provide technical governance so that the teams in their technical development follow principles of Microservice.## Q49. Can we create State Machines out of Microservices?

As we know that each Microservice owning its own database is an independently deployable program unit, this, in turn, lets us create a State Machine out of it. So, we can specify different states and events for a particular microservice.

For Example, we can define an Order microservice. An Order can have different states. The transitions of Order states can be independent events in the Order microservice.

Q50. What are Reactive Extensions in Microservices?

Reactive Extensions also are known as Rx. It is a design approach in which we collect results by calling multiple services and then compile a combined response. These calls can be synchronous or asynchronous, blocking or non-blocking. Rx is a very popular tool in distributed systems which works opposite to legacy flows.

Hope these Microservices Interview Questions would help you in your Microservices Architect Interviews.

Introduction to Java String Interview Questions and Answers

Introduction to Java String Interview Questions and Answers

String is one of the most widely used Java Class. Here I am listing some important Java String Interview Questions and Answers.

1. Introduction

The String class is one of the most widely used classes in Java, which prompted language designers to treat it specially. This special behavior makes it one of the hottest topics in Java interviews.

In this tutorial, we’ll go through some of the most common interview questions about String.

2. String Fundamentals

This section consists of questions that concern the String internal structure and memory.

Q1. What is a String in Java?

In Java, a String is represented internally by an array of byte values (or char values before JDK 9).

In versions up to and including Java 8, a String was composed of an immutable array of Unicode characters. However, most characters require only 8 bits (1 byte) to represent them instead of 16 bits (char size).

To improve memory consumption and performance, Java 9 introduced compact Strings. This means that if a String contains only 1-byte characters, it will be represented using Latin-1 encoding. If a String contains at least 1 multi-byte character, it will be represented as 2 bytes per character using UTF-16 encoding.

In C and C++, String is also an array of characters, but in Java, it’s a separate object with its own API.

Q2. How can we create a String object in Java?

java.lang.String defines 13 different ways to create a String. Generally, though, there are two:

  • Through a String literal:
String s = "abc";

  • Through the new keyword:
String s = new String("abc");

All String literals in Java are instances of the String class.

Q3. Is String a Primitive or a Derived Type?

A String is a derived type since it has state and behavior. For example, it has methods like substring(), indexOf(), and _equals(), _which primitives cannot have.

But, since we all use it so often, it has some special characteristics that make it feel like a primitive:

  • While strings are not stored on the call stack like primitives are, they are** stored in a special memory region called the string pool**
  • Like primitives, we can use the _+ _operator on strings
  • And again, like primitives, we can create an instance of a _String _without the _new _keyword

Q4. What are the benefits of strings being immutable?

According to an interview by James Gosling, strings are immutable to improve performance and security.

And actually, we see several benefits to having immutable strings:

  • The string pool is only possible if the strings, once created, are never changed, as they are supposed to be reused
  • The code can safely pass a string to another method, knowing that it can’t be altered by that method
  • Immutably automatically makes this class thread-safe
  • Since this class is thread-safe, there is no need to synchronize common data, which in turn improves performance
  • Since they are guaranteed to not change, their hashcode can be easily cached

Q5. How is a String stored in memory?

According to the JVM Specification, String literals are stored in a runtime constant pool, which is allocated from the JVM’s method area.

Although the method area is logically part of the heap memory, the specification does not dictate the location, memory size, or garbage collection policies. It can be implementation-specific.

This runtime constant pool for a class or interface is constructed when the class or interface is created by the JVM.

Q6. Are interned strings eligible for garbage collection in Java?

Yes, all _String_s in the string pool are eligible for garbage collection if there are no references from the program.

Q7. What is the String constant pool?

The string pool, also known as the String constant pool or the String intern pool, is a special memory region where the JVM stores String instances.

It optimizes application performance by reducing how often and how many strings are allocated:

  • The JVM stores only one copy of a particular String in the pool
  • When creating a new String, the JVM searches in the pool for a String having the same value
  • If found, the JVM returns the reference to that String without allocating any additional memory
  • If not found, then the JVM adds it to the pool (interns it) and returns its reference

Q8. Is String thread-safe? How?

Strings are indeed completely thread-safe because they are immutable. Any class which is immutable automatically qualifies for thread-safety because its immutability guarantees that its instances won’t be changed across multiple threads.

For example, if a thread changes a string’s value, a new String gets created instead of modifying the existing one.

Q9. For which _String _operations is it important to supply a Locale?

The Locale class allows us to differentiate between cultural locales as well as to format our content appropriately.

When it comes to the _String _class, we need it when rendering strings in format or when lower- or upper-casing strings.

In fact, if we forget to do this, we can run into problems with portability, security, and usability.

Q10. What is the underlying character encoding for strings?

According to _String’_s Javadocs for versions up to and including Java 8, Strings are stored in the UTF-16 format internally.

The char data type and java.lang.Character objects are also based on the original Unicode specification, which defined characters as fixed-width 16-bit entities.

Starting with JDK 9, Strings that contain only 1-byte characters use Latin-1 encoding, while Strings with at least 1 multi-byte character use UTF-16 encoding.

3. The String API

In this section, we’ll discuss some questions related to the String API.

Q11. How can we compare two Strings in Java? What’s the difference between str1 == str2 and str1.equals(str2)?

We can compare strings in two different ways: by using equal to operator ( == ) and by using the equals() method.

Both are quite different from each other:

  • **The operator (str1 == str2) **checks for referential equality
  • **The method (str1.equals(str2)) **checks for lexical equality

Though, it’s true that if two strings are lexically equal, then _str1.intern() == str2.intern() _is also true.

Typically, for comparing two Strings for their content, we should always use String.equals.

Q12. How can we split a String in Java?

The String class itself provides us with the _String#__split _method, which accepts a regular expression delimiter. It returns us a String[] array:

String[] parts = "john,peter,mary".split(",");
assertEquals(new String[] { "john", "peter", "mary" }, parts);

One tricky thing about split is that when splitting an empty string, we may get a non-empty array:

assertEquals(new String[] { "" }, "".split(","));

Of course, _split _is just one of many ways to split a Java String.

Q13. What is StringJoiner?

_StringJoiner _is a class introduced in Java 8 for joining separate strings into one, like taking a list of colors and returning them as a comma-delimited string. We can supply a delimiter as well as a prefix and suffix:

StringJoiner joiner = new StringJoiner(",", "[", "]");
joiner.add("Red")
  .add("Green")
  .add("Blue");

assertEquals("[Red,Green,Blue]", joiner.toString());

Q14. Difference between String, StringBuffer and StringBuilder?

Strings are immutable. This means that if we try to change or alter its values, then Java creates an absolutely new _String. _

For example, if we add to a string _str1 _after it has been created:

String str1 = "abc";
str1 = str1 + "def";

Then the JVM, instead of modifying str1, creates an entirely new String.

However, for most of the simple cases, the compiler internally uses StringBuilder and optimizes the above code.

But, for more complex code like loops, it will create an entirely new String, deteriorating performance. This is where StringBuilder and StringBuffer are useful.

Both StringBuilder and StringBuffer in Java create objects that hold a mutable sequence of characters.** StringBuffer is synchronized and therefore thread-safe whereas StringBuilder is not.**

Since the extra synchronization in _StringBuffer _is typically unnecessary, we can often get a performance boost by selecting StringBuilder.

Q15. Why is it safer to store passwords in a char[] array rather than a String?

Since strings are immutable, they don’t allow modification. This behavior keeps us from overwriting, modifying, or zeroing out its contents, making Strings unsuitable for storing sensitive information.

We have to rely on the garbage collector to remove a string’s contents. Moreover, in Java versions 6 and below, strings were stored in PermGen, meaning that once a String was created, it was never garbage collected.

By using a char[] array, we have complete control over that information. We can modify it or wipe it completely without even relying on the garbage collector.

Using char[] over String doesn’t completely secure the information; it’s just an extra measure that reduces an opportunity for the malicious user to gain access to sensitive information.

Q16. What does _String’_s intern() method do?

The method intern() creates an exact copy of a String object in the heap and stores it in the _String _constant pool, which the JVM maintains.

Java automatically interns all strings created using string literals, but if we create a String using the new operator, for example, String str = new String(“abc”), then Java adds it to the heap, just like any other object.

We can call the intern() method to tell the JVM to add it to the string pool if it doesn’t already exist there, and return a reference of that interned string:

String s1 = "Baeldung";
String s2 = new String("Baeldung");
String s3 = new String("Baeldung").intern();

assertThat(s1 == s2).isFalse();
assertThat(s1 == s3).isTrue();

Q17. How can we convert String to Integer and Integer to String in Java?

The most straightforward approach to convert a String to an Integer is by using Integer#parseInt:

int num = Integer.parseInt("22");

To do the reverse, we can use Integer#toString:

String s = Integer.toString(num);

Q18. What is String.format() and how can we use it?

String#format returns a formatted string using the specified format string and arguments.

String title = "Baeldung"; 
String formatted = String.format("Title is %s", title);
assertEquals("Title is Baeldung", formatted);

We also need to remember to specify the user’s _Locale, _unless we are okay with simply accepting the operating system default:

Locale usersLocale = Locale.ITALY;
assertEquals("1.024",
  String.format(usersLocale, "There are %,d shirts to choose from. Good luck.", 1024))

Q19. How can we convert a String to Uppercase and Lowercase?

String implicitly provides String#toUpperCase to change the casing to uppercase.

Though, the Javadocs remind us that we need to specify the user’s L__ocale to ensure correctness:

String s = "Welcome to Baeldung!";
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase(Locale.US));

Similarly, to convert to lowercase, we have String#toLowerCase:

String s = "Welcome to Baeldung!";
assertEquals("welcome to baeldung!", s.toLowerCase(Locale.UK));

Q20. How can we get a character array from String?

String provides toCharArray, which returns a copy of its internal char array pre-JDK9 (and converts the String to a new char array in JDK9+):

char[] hello = "hello".toCharArray();
assertArrayEquals(new String[] { 'h', 'e', 'l', 'l', 'o' }, hello);

Q21. How would we convert a Java String into a byte array?

By default, the method String#getBytes() encodes a String into a byte array using the platform’s default charset.

And while the API doesn’t require that we specify a charset, we should in order to ensure security and portability:

byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII);
byte[] byteArray3 = "ijkl".getBytes("UTF-8");

4. String-Based Algorithms

In this section, we’ll discuss some programming questions related to _String_s.

Q22. How can we check if two Strings are anagrams in Java?

An anagram is a word formed by rearranging the letters of another given word, for example, “car” and “arc”.

To begin, we first check whether both the Strings are of equal length or not.

Then we convert them to char[] array, sort them, and then check for equality.

Q23. How can we count the number of occurrences of a given character in a String?

Java 8 really simplifies aggregation tasks like these:

long count = "hello".chars().filter(ch -> (char)ch == 'l').count();
assertEquals(2, count);

And, there are several other great ways to count the l’s, too, including loops, recursion, regular expressions, and external libraries.

Q24. How can we reverse a String in Java?

There can be many ways to do this, the most straightforward approach being to use the reverse method from StringBuilder (or StringBuffer):

String reversed = new StringBuilder("baeldung").reverse().toString();
assertEquals("gnudleab", reversed);

Q25. How can we check if a String is a palindrome or not?

A palindrome is any sequence of characters that reads the same backward as forward, such as “madam”, “radar” or “level”.

To check if a string is a palindrome, we can start iterating the given string forward and backward in a single loop, one character at a time. The loop exits at the first mismatch.

5. Conclusion

In this article, we went through some of the most prevalent String interview questions.

All the code samples used here are available on GitHub.