Search Interview Questions | ![]() ![]() Click here and help us by providing the answer. ![]() Click Correct / Improve and please let us know. |
|
| |||||
Java - Interview Questions and Answers - Order By Newest | |||||
![]() ![]() | |||||
![]() | |||||
| |||||
Ans. clone() - Creates and returns a copy of this object. equals() - Indicates whether some other object is "equal to" this one. finalize() - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. getClass() - Returns the runtime class of an object. hashCode() - Returns a hash code value for the object. toString() - Returns a string representation of the object. notify(), notifyAll(), and wait() - Play a part in synchronizing the activities of independently running threads in a program. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
![]() | |||||
| |||||
Ans. Overloading - Similar Signature but different definition , like function overloading. Overriding - Overriding the Definition of base class in the derived class. | |||||
![]() ![]() | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. HttpSession- places a limit on the number of sessions that can exist in memory. | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Volatile is an instruction that the variables can be accessed by multiple threads and hence shouldn't be cached. As volatile variables are never cached and hence their retrieval cannot be optimized. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. 1. Static class is a class which cannot be instantiated and all its members are static whereas Singleton is the class that only permit creation of single object and then the object is reused. 2. As there is no object in Static class, it cannot participate in runtime Polymorphism. 3. As Static class doesnt allow creating objects and hence it cannot be serialized. 4. Static class body is initialized eagerly at application load time whereas Singleton object can be initiated eagerly using static blocks or lazily on first need. 5. Its not recommended to use pure static class as it fails to use many OOPs concepts. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Simplest implementation we can have is a List wherein we can place ordered words and hence can perform Binary Search. Other implementation with better search performance is to use HashMap with key as first character of the word and value as a LinkedList. Further level up, we can have linked Hashmaps like , hashmap { a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value) b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value) .................................................................................... z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value) } upto n levels ( where n is the average size of the word in dictionary. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
![]() | |||||
| |||||
Ans. Final variable means a variable that has been declared final and hence cannot be de referenced after initialization. Effective final means a variable that has not been declared final but haven't been reassigned the value after initialization. First is the regulation that restricts the reassignment and will raise a compilation error if we try to do so. Second is the outcome without the restriction. Effective Final is the eventual treatment of the variable that is required for many features. For eq - Java 8 requires that local variables referenced from a lambda expression must be final or effectively final.It means all local referenced from lambda expressions must be such that their value shouldn't be changed after initialization whether declared final or not. | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
![]() | |||||
![]() | |||||
| |||||
Ans. 1. public is the access modifier that makes the method accessible from anywhere, static is the keyword that makes it accessible even without creating any object, void means it doesn't return anything , String args[] is the array of argument that the method receives. 2. If we use main without the string args , it will compile correctly as Java will treat it as just another method. It wont be the method "main" which Java looks for when it looks to execute the class and hence will throw Error: Main method not found in class , please define the main method as: public static void main(String[] args) 3. Main is not a keyword but a special string that Java looks for while initiating the main thread. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
![]() | |||||
| |||||
Ans. Abstract classes can have both abstract methods ( method declarations ) as well as concrete methods ( inherited to the derived classes ) whereas Interfaces can only have abstract methods ( method declarations ). A class can extend single abstract class whereas it can implement multiple interfaces. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. Synchronized | |||||
![]() | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. Car Engine is an example of encapsulation and abstraction. You ignite the car using an interface called starter and least bothered about how the tire actually moves (This is abstraction). The engine encapsulates the complete process to itself only and doesn't allow you to start the other components like the radiator etc ( this is excapsulation ) | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
| |||||
Ans. It's weird that compiler doesn't complain if we declare transient with static variable because it makes no sense. At least a warning message saying "transient is useless in this situation" would have helped with code cleaning. Static variables are never serialized and transient is an indication that the specified variable shouldn't be serialized so its kind of double enforcement not to serialize. It could be that as it makes no different to the variable behavior and hence using both keywords with a variable are permitted. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Because it doesn't make the change in the existing string but would create a new string by concatenating the new string to previous string. So Original string won't get changed but a new string will be created. That is why when we say str1.concat("Hello"); It means nothing because we haven't specified the reference to the new string and we have no way to access the new concatenated string. Accessing str1 with the above code will still give the original string. | |||||
![]() | |||||
![]() ![]() ![]() | |||||
| |||||
Ans. JDK(Java Development kit) = Development Kit comprising of JVM , library and development tools for developers JRE (Java Run time Environment) - Comprise of JVM and set of libraries JVM(Java Virtual Machine) = Interpreter which reads the .class file line by line. When we install JDK, JRE also get installed so we can write,compile and excute our code. Used by developer. Without JDK we can only execute the program using JRE. | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Private - Not accessible outside object scope. Public - Accessible from anywhere. Default - Accessible from anywhere within same package. Protected - Accessible from object and the sub class objects. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
![]() | |||||
| |||||
Ans. Its a method which cannot be overridden. Compiler throws an error if we try to override a method which has been declared final in the parent class. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. FALSE. == operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Storing the state of an object in a file or other medium is called serialization. Classes can communicate only if they are built together ( as they need Byte code for communication ). What if we need to enable communication between different applications ( i.e they have been built independently or even they reside at different locations ), We need a mechanism that will transfer the Bean state to a Medium than can be transferred to the receiving application. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product. Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest. Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies. Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data. Spring is web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks. Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions. Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources. Spring provides a consistent transaction management interface that can scale down to a local transaction | |||||
![]() | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. You want to write a runtime exception, you need to extend the RuntimeException class. | |||||
![]() | |||||
![]() ![]() ![]() | |||||
| |||||
Ans. In first case we are trying to initialize Inner class object using the instance of Outer Class whereas in second case we are trying to initialize the Inner class object directly using the Outer class name. In second case , Inner class is "static inner class" as we cannot access "non static inner class" using Classname alone. In first case, the inner class could be either "static inner class" or "non static inner class". | |||||
![]() | |||||
![]() ![]() ![]() | |||||
| |||||
Ans. 1. Regulation / Enforcement / Policy / Contract , It's primary use 2. Use as a collection of utility methods(since java 8 through default methods) 3. Collecting constants together, As Interface are lighter, it makes sense to use them instead of classes if no getters and setters required. 4. Creation of Custom Annotations 5. Special services like marker interface | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
| |||||
Ans. Modularity - First sign of good code is whether it has been segregated into methods and classes appropriately. I dont mind it in excess because I believe that is forward looking strategy as applications tends to expand and eventually become hard to read. Self Explanatory - Variables and methods should be named in a way that the code should be self explanatory even without comments. Use of Constant variables to explain use of literal. Proper Code Reuse - If there is anything being reused , it should be moved to parent classes / methods. Proper composition calls - Composed hierarchy should not be access in just single line. One or two levels is ok but having multiple levels make it hard to read and debug. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. The operator instanceOf is used to verify if the specified object is the instance of specified class or interface. Syntax if(x instanceOf ABC) where x is an object reference and ABC could be a class name or interface name. The above statement will be true if x holds an object that is an instance of ABC or any of the child class of ABC or if x holds an object that implements ABC. instanceOf operator is used to verify in case of downcasting. For ex - DerivedClass extends BaseClass x is the reference of BaseClass but holds DerivedClass object ( Polymorphism ) There is an operation that is defined in Derived Class, let's say derivedClassMethod() We cannot call derivedClassMethod() directly using x as x is reference of BaseClass and not DerivedClass and hence can only access methods that are defined in BaseClass and overridden in derived class. Though we can cast it to DerivedClass as following ((DerivedClass)x).derivedClassMethod(); But it may throw ClassCastException in case x doesn't hold an instance of DerivedClass at that point. So before casting it to DerivedClass we may like to make sure that it is an instance of DerivedClass and hence won't throw ClassCastException. So we make a check for it if(x instanceOf DerivedClass) { ((DerivedClass)x).derivedClassMethod(); } | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. Step 1 - We can create a Registry Class having Map of all created objects as key and References list as value. Step 2 - Whenever we create an object , we should update the Registry in the constructor to add the new object. Step 3 - Whenever we assign a new reference to the object , we need to update the entry in Map. Similarly if the reference get's removed ( end of scope etc ), we need to remove the entry of reference from the list. Step 4 - We can have threaded code to monitor the Map to see if any object looses all it's references and should call the method to destroy object and clean the memory. | |||||
![]() | |||||
![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. 1. Multithreading provides better interaction with the user by distribution of task 2. Threads in Java appear to run concurrently, so it provides simulation for simultaneous activities.The processor runs each thread for a short time and switches among the threads to simulate sim-ultaneous execution (context-switching) and it make appears that each thread has its own processor.By using this feature, users can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is running for only a brief time before the context is switched to the next thread. 3. We can do other things while waiting for slow I/O operations.In the java.iopackage, the class InputStreamhas a method, read(), that blocks until a byte is read from the stream or until an IOExceptionis thrown. The thread that executes this method cannot do anything elsewhile awaiting the arrival of another byte on the stream. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. No. Java doesn't allow multi thread access to object constructors so synchronization is not even needed. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. The JDBC is a pure Java API used to execute SQL statements. It provides a set of classes and interfaces that can be used by developers to write database applications. The steps needed to execute a SQL query using JDBC: 1. Open a connection to the database. 2. Execute a SQL statement. 3. Process th results. 4. Close the connection to the database. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. Yes.we cannot access them directly but we can access them using object reference.Static methods belong to a class and not objects whereas non static members are tied to an instance. Accessing instance variables without the instance handler would mean an ambiguity regarding which instance the method is referring to and hence its prohibited. | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
| |||||
Ans. Java does not support pointers. Java does not support multiple inheritances. Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework. C++ compiles to machine language , when Java compiles to byte code . In C++ the programmer needs to worry about freeing the allocated memory , where in Java the Garbage Collector takes care of the the unneeded / unused variables. Java is platform independent language but c++ is depends upon operating system. Java uses compiler and interpreter both and in c++ their is only compiler. C++ supports operator overloading whereas Java doesn't. Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used. Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods. There is no goto statement in Java. There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from. Java is pass by value whereas C++ is both pass by value and pass by reference. Java Enums are objects instead of int values in C++ C++ programs runs as native executable machine code for the target and hence more near to hardware whereas Java program runs in a virtual machine. C++ was designed mainly for systems programming, extending the C programming language whereas Java was created initially to support network computing. C++ allows low-level addressing of data. You can manipulate machine addresses to look at anything you want. Java access is controlled. C++ has several addressing operators . * & -> where Java has only one: the . We can create our own package in Java(set of classes) but not in c and c++. | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
| |||||
Ans. A DOM (Document Object Model) parser creates a tree structure in memory from an input document whereas A SAX (Simple API for XML) parser does not create any internal structure. A SAX parser serves the client application always only with pieces of the document at any given time whereas A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. A SAX parser, however, is much more space efficient in case of a big input document whereas DOM parser is rich in functionality. Use a DOM Parser if you need to refer to different document areas before giving back the information. Use SAX is you just need unrelated nuclear information from different areas. Xerces, Crimson are SAX Parsers whereas XercesDOM, SunDOM, OracleDOM are DOM parsers. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. A Stream is an abstraction that either produces or consumes information. There are two types of Streams : Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer. | |||||
![]() | |||||
![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. Inheritance means a object inheriting reusable properties of the base class. Compositions means that an abject holds other objects. In Inheritance there is only one object in memory ( derived object ) whereas in Composition , parent object holds references of all composed objects. From Design perspective - Inheritance is "is a" relationship among objects whereas Composition is "has a" relationship among objects. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. public static void main(String ar[]) { int n=5; if((n/2)*2==n) { System.out.println("Even Number "); } else { System.out.println("Odd Number "); } } | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. REST or Representational State Transfer is a flexible architecture style for creating web services that recommends the following guidelines - 1. http for client server communication, 2. XML / JSON as formatiing language , 3. Simple URI as address for the services and, 4. stateless communication. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
![]() | |||||
| |||||
Ans. When multiple external resources are trying to access the DB locks and runs into cyclic wait, it may makes the DB unresponsive. Deadlock can be avoided using variety of measures, Few listed below - Can make a queue wherein we can verify and order the request to DB. Less use of cursors as they lock the tables for long time. Keeping the transaction smaller. | |||||
![]() | |||||
![]() ![]() ![]() ![]() ![]() ![]() | |||||
| |||||
Ans. NullPointerException at line: "File file = new File("/folder", name);" | |||||
![]() | |||||
![]() ![]() ![]() | |||||
| |||||
Ans. Predicate represents an anonymous function that accepts one argument and produces a result. Supplier represents an anonymous function that accepts no argument and produces a result. Consumer represents an anonymous function that accepts an argument and produces no result. | |||||
![]() ![]() ![]() | |||||
![]() | |||||
![]() ![]() ![]() ![]() | |||||
![]() ![]() | |||||