Top 30 Core Java Interview questions and answers for freshers
Here is the list of some of the most common Questions & answers for Java interviews. It’s not limited to any particular company as well, in fact, all major IT companies in India e.g. TCS, CTS, Infosys, Tech Mahindra, HCL, Oracle Financial Services, and many of the major investment asked this kind of fact-based question on their Java recruitment drives. By the way, some questions are really easy, and some are real tough, so it’s mixed of both, but one thing is common, they are the most frequently asked questions from Java interviews for freshers.
1) What is an immutable object? How do you create an Immutable object in Java?
- Immutable objects offer several benefits over a conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s sta but also can be shared among other threads without any external synchronization. In fact, JDK itself contains several immutable classes like String, Integer, and other wrapper classes.For those, who doesn’t know what is immutable class or object, Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase.All modification in String results in a new object, how to write an immutable class in Java or how to make a class immutable. By the way making a class immutable is not difficult on the code level, but its the decision to make, which class mutable or immutable which makes difference. Immutable classes are those class, whose object can not be modified once created,it means any modification on the immutable object will result in another immutable object. the best example to understand immutable and mutable objects are, String and StringBuffer. Since String is an immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating a substring from String, all result in new objects.While in the case of a mutable object like StringBuffer, any modification is done on the object itself and no new objects are created. Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.