Java interview-questions-and-answers

615 views

Published on

Crack your Java interview by knowing all the questions that your interviewer may ask. Brush up your knowledge with this superb set of Java interview questions & answers prepared by BestOnlineTrainers

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
615
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
63
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Java interview-questions-and-answers

  1. 1. 1 1. To implement key Object in HashMap which two methods are used? In HashMap, to use any object as Key it must implement equals and HashCode method in Java. 2. What is an immutable object? Mention an immutable object? Objects that cannot be modified once created are immutable objects in JAVA. A new object can be resulted due to any modification in an immutable object. For example, in JAVA, String is immutable. In order to prevent sub class from overriding methods in Java which can compromise Immutability, immutable object are mostly final in JAVA. This same functionality can be achieved by making member as non final but private and not modifying them except in constructor. 3. State the difference between creating String as new() and literal? When string is created with new() Operator, it’s created in a heap and not added into string pool whereas using literal String are created in String pool itself which exists in PermGen area of heap, Example: String s = new String("Test"); It does not put the object in String pool , but needs to be called String.intern() method which is used to put them into String pool explicitly. It’s only then that’s it create String object as String literal. For e.g. String s = "Test" Java automatically put that into String pool. 4. What is difference between StringBuffer and StringBuilder in Java? Classic Java questions can seem to be tricky and very easy. In Java 5, StringBuilder is introduced and the only difference between both of them is that StringBuffer methods are synchronized while StringBuilder is non- synchronized. 5. Overriding HashCode() method has any difference in performance implication? Yes .A poor HashCode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map. 6. While writing stored procedure or accessing stored procedure from java how is the error condition handled? This is one of the tough questions normally asked in Java interview. The stored procedure should return error code if some operation fails but if stored procedure itself fails than catching SQLException is the only choice left. 7. At the compile time are the imports checked for validity? That is, will the code containing an import such as java.lang.ABCD compile up? Yes. The imports are checked for the semantic validity at the compile time. The above line of import will not compile if it has the code, an error is shown saying, cannot resolve symbol. Symbol: class ABCD Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com
  2. 2. 2 Location: package io Import java.io.ABCD; 8. State difference between Executor.submit() and Executer.execute() method? When looking at exception handling, there is a difference. If the tasks throws an exception and if it was submitted with the execute then this exception will go to the uncaught exception handler (that is when one explicitly is not provided, the default one will just print the stack trace to System.err). If the task is submitted with any thrown exception or a checked exception or not, is then part of the task's return status. And for a task that was submitted with submit and that terminates with an exception, the future.get will re-throw this exception wrapped in an ExecutionException. 9. What is the difference between factory and abstract factory pattern? One more level of abstraction is provided by Abstract Factory .Different factories from each Abstract Factory responsible for the creation of different hierarchies of objects based on type of factory are considered. For example; Abstract Factory extended by AutomobileFactory, UserFactory, RoleFactoryetc.For every object created in that genre, each individual factory would be responsible. 10. Define Singleton? Which is better: to make whole method synchronized or only critical section synchronized? Singleton in JAVA is a class with just one instance in the whole Java application. One such example is java.lang.Runtime is a Singleton class .With the introduction Enum by Java 5, creating a Singleton is easy rather than being tricky as earlier. 11. Differentiate between a constructor and a method? A member function of a class that is used to create objects of that class is called a Constructor is. Its name is same as the class itself, has no return type. It is invoked using the new operator. An ordinary member function of a class is called Method. It has its own name and a return type (which may be void).It is invoked using the dot operator. 12. State the purpose of garbage collection in Java, and also when is it used? Identifying and discarding objects that are no longer needed by a program so that their resources can be reclaimed and reused is the purpose of garbage collection. When a Java object is subjected becomes unreachable to the program in which it is used; it is subjected to garbage collection. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com
  3. 3. 3 13. When is HashCode and equals() overridded ? To do equality check or use object as a key in HashMap, HashCode and equals() are overridden. 14. What is the issue if HashCode() method are not overridded ? If the HashCode() is not overridded , the object will not be recovered from the HashMap if used as key. 15. State which is better: to synchronize critical section of getInstance() method or whole getInstance() method ? Here the answer is a bit critical as if we lock the whole method than every time then this method will be called and would have to wait even though any object is not being created. 16. When String gets created using literal or new() operator , what difference is seen? When a string is created with new() its created in heap and not added into string pool while using literal , String can be created in String pool itself which exists in Perm area of heap. 17. Does overriding HashCode() method have any performance implication or not ? Poor HashCode function results in frequent collision in HashMap which eventually increases the time for adding an object into Hash Map. 18. In multithreaded environment what’s wrong in using HashMap? When does get() method go to infinite loop ? This happens during concurrent access and re-sizing. 19. What is thread-safety? Why is it required? And how to achieve thread-safety in Java Applications? The legal interaction of threads with the memory in a real computer system defines Java Memory Model. It also describes what behaviors are legal in a multi-threaded code. It can also determine when a Thread can reliably see writes to variables made by other threads. It also defines semantics for volatile, final and synchronize, that makes guarantee of visibility of memory operations across the Threads. In a Memory Barrier which there are two type of memory barrier instructions in JMM - read barriers and write barrier. To make the changes made by other threads visible to the current Thread, the read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory .To make the changes made by current Thread visible to other Thread, a Write barrier flushes out the contents of the processor’s local memory to the main memory. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com
  4. 4. 4 20. What happens if you call return statement or System.exit on try or catch block? Will it finally block execute? This is a very popular tricky Java question because many programmers think that finally the block always gets executed. This question challenges the concept by putting return statement in try or catch block or calling System.exit from try or catch block. In Java, this finally block will execute even if you put return statement in the try block or catch block finally block won't run even if you call System.exit form to try or catch. 21. How are strings compared Using “==” or equals ()? “==” tests if references are equal and equals () tests if values are equal. To check if two strings are the same object, equals() is always used. 22.Char[] is preferred over String for security sensitive information. Why? Strings are immutable, that is once they are created, and they stay unchanged until Garbage Collector kicks in. Its elements can be explicitly changed with an array. Hence, security sensitive information like password will not be present anywhere in the system. 23. Can string be used to switch statement? String can be used to switch statement to version 7. From JDK 7, string can be used as switch condition. Before version 6, string cannot be used as switch condition. 24. Can string be converted to int? Yes .It can be .But its frequently used and ignored at times. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com view source print? 1.int n = Integer.parseInt("10"); view source print? 01.// java 7 only! 02.switch (str.toLowerCase()) 03.case "a": 04.value = 1; 05.break; 06.case "b": 07.value = 2; 08.break; 09.}
  5. 5. 5 25. How can a string be split with white space characters? String can be slit using regular expression. White space characters are represented as “s”. 26. What does substring() method do ? The existing String is represented by the substring() method which gives a window to an array of chars as in JDK 6.A new one is not created. An empty string needs to be added to create a new one. This creates a new char array representing a new string. This method can help to code faster because the Garbage Collector collects the unused large string and the keeps the substring. 27. What is String vs StringBuilder vs StringBuffer In String vs StringBuilder, StringBuilder is mutable, that is it means it can be modified after its creation. In StringBuilder vs StringBuffer, StringBuffer is synchronized, that is it means it is thread-safe but would be slower than StringBuilder. 28. How is a string repeated ? In Python, to repeat a string just multiple a number. In Java, the repeat() method of StringUtils from Apache Commons Lang package can be used. 29. In Java, what is the default value of byte datatype? 0 is the default value of byte datatype. Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com print ? 1.str.substring(m,n)+ "" view source print? 1.String [] strArray = aString.split("s+");
  6. 6. 6 30. In a string how to count # of occurrences of a character? StringUtils from apache commons lang can be used. WANT TO LEARN JAVA OR ANY OTHER PROGRAMMING COURSE? Ask for FREE DEMO Today Register NOW http://www.bestonl inetrainers.com/ demo/index.htmlUSA: +(1) 6783896789 | UK: +(44)- 2032393637 | India: +(91) 9246449191 info@bestonlinetrainers.com | www.bestonlinetrainers. com Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com view source print? 1.int n = StringUtils.countMatches("11112222", "1"); 2.System.out.println(n);
  7. 7. 6 30. In a string how to count # of occurrences of a character? StringUtils from apache commons lang can be used. WANT TO LEARN JAVA OR ANY OTHER PROGRAMMING COURSE? Ask for FREE DEMO Today Register NOW http://www.bestonl inetrainers.com/ demo/index.htmlUSA: +(1) 6783896789 | UK: +(44)- 2032393637 | India: +(91) 9246449191 info@bestonlinetrainers.com | www.bestonlinetrainers. com Java Interview Questions & Answers by BestOnlineTrainers http://www.bestonlinetrainers.com view source print? 1.int n = StringUtils.countMatches("11112222", "1"); 2.System.out.println(n);

×