1 / 15

Java Interview Questions and Answers

Credo Systemz is the best software training institute in chennai

Télécharger la présentation

Java Interview Questions and Answers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVA INTERVIEW QUESTIONS AND ANSWERS 1. What is difference between JDK,JRE and JVM? JVM JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. It is a specification. JVMs are available for many hardware and software platforms (so JVM is platform dependent). JRE JRE stands for Java Runtime Environment. It is the implementation of JVM. JDK JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools. 2. How many types of memory areas are allocated by JVM? Many types: Class(Method) Area Heap Stack Program Counter Register Native Method Stack 3. What is JIT compiler? Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU. 4. What is platform? A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

  2. 5. What is the main difference between Java platform and other platforms? The Java platform differs from most other platforms in the sense that it’s a software-based platform that runs on top of other hardware-based platforms.It has two components: Runtime Environment API(Application Programming Interface) 6. What gives Java its ‘write once and run anywhere’ nature? The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform. 7. What is classloader? The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc. 8. What is the default value of the local variables? The local variables are not initialized to any default value, neither primitives nor object references. 9. Why Java does not support pointers? Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand. 10. Can I import same package/class twice? Will the JVM load the package twice at runtime? One can import the same package or same class multiple times. Neither compiler nor JVM complains about it.But the JVM will internally load the class only once no matter how many times you import the same class. 11. Why string objects are immutable in java? Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object “sachin”.If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java. 12. What is the purpose of toString() method in java ? The toString() method returns the string representation of any object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation. 13. What are the access modifiers in Java?

  3. There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly. 14. What is JDBC? JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications. 15. What is the Java API? The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. 16. Why there are no global variables in Java? Global variables are globally accessible. Java does not support globally accessible variables due to following reasons: 1)The global variables breaks the referential transparency 2)Global variables creates collisions in namespace. 17. What are Encapsulation, Inheritance and Polymorphism? Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions. 18. What is method overloading and method overriding? Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding. 19. What is covariant return type? Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. 20. What is JIT and its use? Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. 21. Can we use String in the switch case?

  4. Yes from Java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch. 22. How HashSet works internally in Java? HashSet is internally implemented using an HashMap. Since a Map needs key and value, a default value is used for all keys. Similar to HashMap, HashSet doesn’t allow duplicate keys and only one null key, I mean you can only store one null object in HashSet. 23. How do you print Array in Java? You can print an array by using the Arrays.toString() and Arrays.deepToString() method. Since array doesn’t implement toString() by itself, just passing an array to System.out.println() will not print its contents but Arrays.toString() will print each element. 24. Explain Java Heap space and Garbage collection? When a Java process is started using java command, memory is allocated to it. Part of this memory is used to create heap space, which is used to allocate memory to objects whenever they are created in the program. Garbage collection is the process inside JVM which reclaims memory from dead objects for future allocation. 25. How do WeakHashMap works? WeakHashMap works like a normal HashMap but uses WeakReference for keys, which means if the key object doesn’t have any reference then both key/value mapping will become eligible for garbage collection. 26. What is the right data type to represent a price in Java? BigDecimal if memory is not a concern and Performance is not critical, otherwise double with predefined precision. 27. The difference between sleep and wait in Java? Though both are used to pause currently running thread, sleep() is actually meant for short pause because it doesn’t release lock, while wait() is meant for conditional wait and that’s why it release lock which can then be acquired by another thread to change the condition on which it is waiting. 28. What is meant by binding in RMI ? Binding is the process of associating or registering a name for a remote object, which can be used at a later time, in order to look up that remote object. A remote object can be associated with a name using the bind or rebind methods of the Naming class. 29. What is Servlet Chaining ?

  5. Servlet Chaining is the method where the output of one servlet is sent to a second servlet. The output of the second servlet can be sent to a third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client. 30. What is the purpose Class.forName method ? This method is used to method is used to load the driver that will establish a connection to the database. 31. Explain the life cycle of a Servlet On every client’s request, the Servlet Engine loads the servlets and invokes its init methods, in order for the servlet to be initialized. Then, the Servlet object handles all subsequent requests coming from that client, by invoking the service method for each request separately. Finally, the servlet is removed by calling the server’s destroy method. 32. What is the purpose of using RMISecurityManager in RMI ? RMISecurityManager provides a security manager that can be used by RMI applications, which use downloaded code. The class loader of RMI will not download any classes from remote locations, if the security manager has not been set. 33. What is the role of the java.rmi.Naming Class ? The java.rmi.Naming class provides methods for storing and obtaining references to remote objects in the remote object registry. Each method of the Naming class takes as one of its arguments a name that is a String in URL format. 34. What advantage do Java’s layout managers provide over traditional windowing systems ? Java uses layout managers to lay out components in a consistent manner, across all windowing platforms. Since layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems. 35. What is the applet security manager, and what does it provide ? The applet security manager is a mechanism to impose restrictions on Java applets. A browser may only have one security manager. The security manager is established at startup, and it cannot thereafter be replaced, overloaded, overridden, or extended. 36. What are untrusted applets ? Untrusted applets are those Java applets that cannot access or execute local system files. By default, all downloaded applets are considered as untrusted. 37. What is the purpose of garbage collection in Java, and when is it used ?

  6. The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application, in order for the resources to be reclaimed and reused. 38. What is the tradeoff between using an unordered array versus an ordered array ? The major advantage of an ordered array is that the search times have time complexity of O(log n), compared to that of an unordered array, which is O (n). The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n), because the elements with higher values must be moved to make room for the new element. Instead, the insertion operation for an unordered array takes constant time of O(1). 39. What is the importance of hashCode() and equals() methods ? In Java, a HashMap uses the hashCode and equals methods to determine the index of the key-value pair and to detect duplicates. More specifically, the hashCode method is used in order to determine where the specified key will be stored. Since different keys may produce the same hash value, the equals method is used, in order to determine whether the specified key actually exists in the collection or not. Therefore, the implementation of both methods is crucial to the accuracy and efficiency of the HashMap. 40. What is an Iterator ? The Iterator interface provides a number of methods that are able to iterate over any Collection. Each Java Collection contains the iterator method that returns an Iterator instance. Iterators are capable of removing elements from the underlying collection during the iteration. 41. What is the difference between processes and threads ? A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads. A Thread is sometimes called a lightweight process. 42. Can you access non static variable in static context ? A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance. 43. What is J2EE? J2EE means Java 2 Enterprise Edition. The functionality of J2EE is developing multitier web-based applications. The J2EE platform is consists of a set of services, application programming interfaces (APIs), and protocols. 44. What are the four components of J2EE application?

  7. Application clients components. Servlet and JSP technology are web components. Business components (JavaBeans). Resource adapter components 45. What are types of J2EE clients? Applets Application clients Java Web Start-enabled clients, by Java Web Start technology. Wireless clients, based on MIDP technology. 46. What is considered as a web component? Java Servlet and Java Server Pages technology components are web components. Servlets are Java programming language that dynamically receives requests and make responses. JSP pages execute as servlets but allow a more natural approach to creating static content. 47. What is JSF? JavaServer Faces (JSF) is a user interface (UI) designing framework for Java web applications. JSF provides a set of reusable UI components, a standard for web applications. JSF is based on MVC design pattern. It automatically saves the form data to the server and populates the form date when display at the client side. 48. Define Hash table HashTable is just like Hash Map, Collection having key(Unique), value pairs. Hashtable is a collection Synchronized object. It does not allow duplicate values or null values. 49. What is Hibernate? Hibernate is an open source object-relational mapping and query service. In hibernate we can write HQL instead of SQL which save developers to spend more time on writing the native SQL. Hibernate has a more powerful association, inheritance, polymorphism, composition, and collections. It is a beautiful approach for persisting into the database using the Java objects. Hibernate also allows you to express queries using Java-based criteria. 50. What is the limitation of hibernate? Slower in executing the queries than queries are used directly. Only query language support for composite keys. No shared references to value types. 51. What are the advantages of hibernate?

  8. Hibernate is portable i mean database independent, Vendor independence. Standard ORM also supports JPA Mapping of the Domain object to the relational database. Hibernate is better than plain JDBC. JPA provider in JPA based applications. 52. Define connection pooling? Connection pooling is a mechanism reuse the connection.which contains the number of already created object connection. So whenever it is necessary for an object, this mechanism is used to directly get objects without creating it. 53. How to Create Object without using the keyword “new” in java? Without new, the Factory methods are used to create objects for a class. For example Calender c=Calender.getInstance(); here Calender is a class and the method getInstance() is a Factory method which can create an object for Calendar class. 54. What is Spring? Spring is a light weight open source framework for the development of enterprise application that resolves the complexity of enterprise application development also providing a cohesive framework for J2EE application development. Which is primarily based on IOC (inversion of control) or DI (dependency injection) design pattern. 55. What is action mapping? In action mapping, we specify action class for particular URL ie path and different target view ie forwards on to which request response will be forwarded.The ActionMapping represents the information that the ActionServlet knows about the mapping of a particular request to an instance of a particular Action class.The mapping is passed to the execute() method of the Action class, enabling access to this information directly. 56. What is the MVC on struts? MVC stands Model-View-Controller. Model: Model in many applications represent the internal state of the system as a set of one or more JavaBeans. View: The View is most often constructed using JavaServer Pages (JSP) technology. Controller: The Controller is focused on receiving requests from the client and producing the next phase of the user interface to an appropriate View component. The primary component of the Controller in

  9. the framework is a servlet of class ActionServlet. This servlet is configured by defining a set of ActionMappings. 57. Is that Servlet is pure java object or not? Yes, Servlet is pure java object. 58. What is called JSP directive? JSP directive is the mechanism to provide Metadata information to web container about JSP file. In the translation and compilation phases of the JSP life cycle, these Metadata use by the web container. 59. What are the Benefits Spring Framework? Light weight container Spring can effectively organize your middle tier objects Initialization of properties is easy. No need to read from a properties file application code is much easier to unit test Objects are created Lazily, Singleton – configuration Spring’s configuration management services can be used in any architectural layer, in whatever runtime environment 60. How to disable caching on back button of the browser? <% response.setHeader(“Cache-Control”,”no-store”); response.setHeader(“Pragma”,”no-cache”); response.setHeader (“Expires”, “0”); //prevents caching at the proxy server %> 61. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. 62. What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 63. How to Create Object without using the keyword “new” in java?

  10. Without new, the Factory methods are used to create objects for a class. For example Calender c=Calender.getInstance(); here Calender is a class and the method getInstance() is a Factory method which can create an object for Calendar class. 64. Explain the jspDestroy() method. jspDestry() method is invoked from javax.servlet.jsp.JspPage interface whenever a JSP page is about to be destroyed. Servlets destroy methods can be easily overridden to perform cleanup, like when closing a database connection. 65. How is JSP better than Servlet technology? JSP is a technology on the server’s side to make content generation simple. They are document centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside HTML template file. It provides the framework for development of a Web Application. 66. How to delete a Cookie in a JSP? The following code explain how to delete a Cookie in a JSP : Cookie mycook = new Cookie(“name1″,”value1”); addCookie(mycook1); Cookie killmycook = new Cookie(“mycook1″,”value1”); killmycook . set MaxAge ( 0 ); killmycook . set Path (“/”); killmycook . addCookie ( killmycook 1 ); 67. What are the basic interfaces of Java Collections Framework ? Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are: Collection, which represents a group of objects known as its elements. Set, which is a collection that cannot contain duplicate elements. List, which is an ordered collection and can contain duplicate elements. Map, which is an object that maps keys to values and cannot contain duplicate keys.

  11. 68. Is it necessary that each try block must be followed by a catch block? It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method. 69. What does the JDBC Connection interface? The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData. 70. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. 71. Can we call the run() method instead of start()? yes, but it will not work as a thread rather it will work as a normal object so there will not be context- switching between the threads. 72. What is Session Facade? Session Facade is a design pattern to access enterprise bean through local interface. It abstracts the business object interactions and provides a service layer. It makes the performance fast over network. 73. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” %> within your JSP page. 74. How is JSP used in the MVC model? JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client. 75. What are context initialization parameters? Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP. 76. What does modelDriven interceptor?

  12. The modelDriven interceptor makes other model as the default object of ValueStack. By default, action is the default object of ValueStack. 77. What is the role of IOC container in spring? IOC container is responsible to: create the instance configure the instance, and assemble the dependencies 78. What are the transaction management supports provided by spring? Spring framework provides two type of transaction management supports: Programmatic Transaction Management: should be used for few transaction operations. Declarative Transaction Management: should be used for many transaction operations. 79. What is the advantage of NamedParameterJdbcTemplate? NamedParameterJdbcTemplate class is used to pass value to the named parameter. A named parameter is better than ? (question mark of PreparedStatement). 80. Why we override equals() method? The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property. For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method. 81. What does the JDBC Connection interface? The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData. 82. Is it necessary that each try block must be followed by a catch block? It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method. 83. How does execution phase work in JSF (JavaServer Faces) lifecyle? In execute phase, when first request is made, application view is built or restored. For other subsequent requests other actions are performed like request parameter values are applied, conversions and

  13. validations are performed for component values, managed beans are updated with component values and application logic is invoked. 84. What is h:inpuText tag in JSF (JavaServer Faces)? The JSF <h: inputText> tag is used to render an input field on the web page. It is used within a <h: form> tag to declare input field that allows user to input data. 85. What is f:convertNumber tag in JSF (JavaServer Faces)? It is used to convert component (user input) data into a Java Number type. You can convert a component’s data to a java.lang.Number by nesting the convertNumber tag inside the component tag. The convertNumber tag has several attributes that allow you to specify the format and type of the data. 86. How to create a Fecelet view? Facelets views are XHTML pages. You can create a web page or view, by adding components to the page, wire the components to backing bean values and properties, and register converters, validators, or listeners on the components. 87. What are Facelets Templates? It is a tool which provides the facility to implement the user interface. Templating is a useful Facelets feature that allows you to create a page that will act as the base for the other pages in an application. By using templates, you can reuse code and avoid recreating similarly pages again and again. 88. What does the JDBC DatabaseMetaData interface? The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc. 89. What are the features of JUnit? Opensource Annotation support for test cases Assertion support for checking the expected result Test runner support to execute the test case 90. What is the default size of load factor in hashing based collection? The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map. 91. What are Directives ?

  14. Directives are instructions that are processed by the JSP engine, when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >.The different types of directives are shown below: Include directive: it is used to include a file and merges the content of the file with the current page. Page directive: it is used to define specific attributes in the JSP page, like error page and buffer. Taglib: it is used to declare a custom tag library which is used in the page. 92. What is the difference between HashSet and HashMap? HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated. 93. What is the difference between HashSet and HashMap? HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated. 94. What are Scriptlets ? In Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between these tags, a user can add any valid scriplet. 95. What are Decalarations ? Declarations are similar to variable declarations in Java. Declarations are used to declare variables for subsequent use in expressions or scriptlets. To add a declaration, you must use the sequences to enclose your declarations. 96. What are Expressions ? A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client, by the web server. Expressions are defined between <% = and %> tags. 97. Explain the role of Driver in JDBC. The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each driver must provide implementations for the following classes of the java.sql package:Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver. 98. What is the purpose Class.forName method ? This method is used to method is used to load the driver that will establish a connection to the database.

  15. 99. What is the advantage of PreparedStatement over Statement ? PreparedStatements are precompiled and thus, their performance is much better. Also, PreparedStatement objects can be reused with different input values to their queries. 100. What is the use of CallableStatement ? Name the method, which is used to prepare a CallableStatement. A CallableStatement is used to execute stored procedures. Stored procedures are stored and offered by a database. Stored procedures may take input values from the user and may return a result. The usage of stored procedures is highly encouraged, because it offers security and modularity.The method that prepares a CallableStatement is the following: CallableStament.prepareCall(); Contact Info: +91 9884412301 | +91 9884312236 Know more about JAVA New # 30, Old # 16A, Third Main Road, Rajalakshmi Nagar, Velachery, Chennai (Opp. to MuruganKalyanaMandapam) info@credosystemz.com BOOK A FREE DEMO

More Related