Hello guys, thank you for your big support on my last article How ConcurrentHashMap works in Java, a lot of people subscribed and a few of them also became paid subscribers which means a lot to me. Since I am going to put more focus on my newsletter this year, I also asked if you guys like to receive Java interview questions and discussions on newsletter more often and many of you said yes. So in this post, I am going to discuss one more classic core Java interview question “Why String is Immutalbe in Java” or “Why String is final in Java?
This question was asked to me multiple times in the last 20 years of my career as a Java developer and I have also asked this question a couple of times to check how much candidates know about String class in Java.
This question required a good understanding of not just Java but key programming concepts like immutability, security, and caching to answer, and if you know them well, you can also impress your interviewer and present yourself as a senior Java developer and expert.
So let’s jump into the answer now:
In Java, strings are immutable, which means once a String
object is created, its value cannot be changed. This design choice was made for several reasons:
Security: Strings are often used to store sensitive information such as passwords, network URLs, file paths, etc. If strings were mutable, an attacker could modify the contents of a string, potentially compromising security. Immutability helps in creating secure applications.
Keep reading with a 7-day free trial
Subscribe to Javarevisited Newsletter to keep reading this post and get 7 days of free access to the full post archives.