java realtime interview - TopicsExpress



          

java realtime interview questions ................................ 1.What is Annotation and Why to use @Override Annotation in Java. ................................................................... answer1: @override annotation is very useful when you use multilevel inheritance in your project. For example If we have class A implementing some methods and class B override its some of the methods. If you dont use override annotation and someone modifies method prototype which is present in parent class than you wont get any compile time error and Your overridden method wont be overridden anymore it will be treated like new method but if you use override annotation and someone modifies parent method prototype than you will get compile time error. This case happens when your team size is more and they work on the same project. answer2: Annotation is some additional info for compiler or for JVM. The @Override annotation means that you intended to override the method of the suppercclass and it is strongly recommended to use it. Suppose you implement some class: class MyClass { String name; public boolean equals(MyClass other) { return name != null && name.equals(other.name); } } Somewhere in the code you do the following: final Set set = new HashSet(); set.add(new MyClass(name)); set.add(new MyClass(name)); } And you expect to have 1 instance of MyClass in the set. But there are two of them! That is because you didnt override the equals of the Object, since it has different notation. If you add the @Override annotation to the class, you get the compilation error with the message like the method doesnt ovveride the method of the superclass - and you will fix the error at once. 2.If there are 10 servlets and one of the servlet has an error, how to stop that one servlet. In short how to manually stop a servlet? Is... .............................................................................................................................. answer:1 You can stop an application, edit the web.xml file, and then restart the application. I dont know if that would satisfy your requirements. It appears that Servlet 3.0 ServletContext ( docs.oracle/javaee/7/api/javax/servlet/ServletContext.html ) might allow you to do this. You could add a filter that would divert any requests that were to go to the malfunctioning servlet. This isnt quite the same as stopping the servlet, but it would eliminate requests for it. I should add that I dont like this idea. 3.Does method overloading fall under polymorphism? ..................................................... Is polymorphism only related to inheritance and hence method overriding? If yes, then what is the difference between static and dynamic polymorphism? Polymorphism refers to the ability of an object to behave differently to the same message. Polymorphism is of two types. static or dynamic. The binding which can be resolved at compile time by compiler is known as static or early binding. In static binding method call occur based on the reference type at compile time. All the static, private and final methods have always been bonded at compile-time. Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static. When compiler is not able to resolve the call/binding at compile time, such binding is known as Dynamic or late Binding. Overriding is a perfect example of dynamic binding as in overriding both parent and child classes have same method. Thus while calling the overridden method, the compiler gets confused between parent and child class method(since both the methods have same name) and the method call occurs based on the object (instance) type at Run time. answer2: Yes, method overloading falls under polymorphism which is static polymorphism. Difference between static and dynamic polymorphism is as follows. Static polymorphism is polymorphism at compile time i.e., method call is decided basing on the no of parameters, type of parameters etc during compile time. Dynamic polymorphism is polymorphism at run time i.e., method call is decided during run time basing on the actual object which calls it i.e., whether it is parent object or child object. 3.what is difference between spring singlton and java singleton? ................................................................... answer:Java Singleton: One and only one object will be create for singleton class per class loader. Spring Singleton: For every spring context(spring container) only one bean object will be create. 4.What are checked and unchecked exceptions in Java? ......................................................... answer: Checked exceptions by design are exceptions that have to handled in try/catch block or declared to be thrown by the method. They extend java.lang.Exception. Unchecked exceptions dont have to be handled by try/catch block nor have to be declared in the method declaration. They extend java.lang.RuntimeException. Generally with new languages based on JVM you dont see much support for checked exceptions, because they tend to make code more verbose, they shift to unchecked exceptions. 5.Do we nee to implement cloneanle interface for singleton class please explain? .................................................................................... Answer:No. You dont need to implements Cloneable in the singleton pattern. SIngleton means that you need only one object for that class. So it is incorrect to have a second instance and clone a class is a method to have another instance.. A singleton class need not implement Cloneable interface. If it implements, it breaks the singleton property. 5.What is the limitation of method overriding ? ................................................ answer:Overridden methods must have the same name, argument list, and return type (i.e., they must have the exact signature of the method we are going to override, including return type.) The overriding method cannot be less visible than the method it overrides (i.e., a public method cannot be override to private). The overriding method may not throw any exceptions that may not be thrown by the overridden method. Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass. limitations of overriding of methods: 1. we can not override static methods. 2. we can not override constructor. 3.if the methods are not inherited then we cant override it. 6.Volatile Vs Atomic ......................... Volatile is not useful when you perform compound operations read-update-write, because it doesnt guarantee atomicty. For instance if you have an volatile int variable and you do something like: volatile int counter = 0; if (counter++ == 0) { System.out.println(execute only once); } This piece of code is not thread safe, because volatile is only giving you guarantee that on the check if counter is equal 0 counter will have most recent value from the main memory, not local thread cache. The check will be performed in following steps: read most recent value from memory, check if its equal 0, increase the value and store it in the main memory. But after the first step this thread can be suspended and other thread will also check if counter is equal 0 and again it will be true and in the end the message will be executed twice. AtomicInteger counter = new AtomicInteger(0); if (counter.getAndIncrement()) { System.out.println(execute only once); } Atomic objects are using atomic operations, so those four steps that I described in the previous step are performed in a single one, so theres no chance, that the first thread will be suspended in the middle of the update. Either the update will be performed with a single processor instruction or the counter object will be locked for other threads. 7.what is the difference between primitive type (int,float,long,...) and their respective classes(Integer, Float and Long)..? ............................................................................................................................... answer:can include wrapper classes in Collection where primitive not. * NULL value is possible with wrapper classes. * can be handy to initialise Object with null or send null parameters to a method or constructor to indicate state or function. This cant be possible with primitives. * can treat wrapper classes generically / polymorphically as an object along with other objects but not primitivies * get type safety we use generics and generics need objects not primitives 8. is singleton thread safe...? ....................................... answer:It can be thread safe. Why not? Something like that: public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchroniced (Singleton.class) { if (instance == null) instance = new Singleton(); } } } 9.why do we pass String argument in main method? can we pass Integer or Float in main method as args? ..................................................................................................... answer:This is a JVM architectural decision, that an entry point class to your program execution must have a method with a following definition: public static void main(String[] args) { } If the class that you specify in your execution command doesnt have this method definition, the error is thrown. If the array should represent different type you have to do parsing manually. 10.what is main difference between filter and interceptor with example ......................................................................... answer: Filter is a class which use to check server side validation....means if u are requesting any thing from the server the ...fillter will check ur request on ur server ....if requested data valid then...fillter will put on the server...otherwise it will give u error.... ...Interceptor is very important part of the struts framework...which process the request step by step...on the controller...there are many interceptor working in the form of queue... 11.What is hashmap ? How hashmap work ? ...................................... answer1: Hashmap is a class which implements map interface.It works on the principle of hashing.For putting the objects in a map, we have put(key, value) method and for getting the object value, we have get(key) method.when we pass key and value to put method, hashmap calls hashcode method and whatever hashcode is returned by this method, this code is applied to its own hashing function to store and retrieve the object.HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic. answer2:HashMap is an object container that lets you store the objects inside by custom key object. You are not limited with number indexing like in case of lists. Internal implementation of HashMap in java is made of array of linked lists. First you call a hashCode of your object to specify the index in array and then you check the linked list under the index to perform your desired action. With a good hashing algorithm hash map gives you constant access time which is why hash map is used in most cases. To find an object in a LinkedList you have to iterate through all elements which gives you O(n) access time. With ArrayList you dont have that for get operations, because its backed by the array, but for updating, adding and deleting you still have O(n) because you have to potentially move all elements in an backing array. The drawback of using HashMap is that it uses slightly more space than lists and it doesnt preserve any ordering. With a bad hashing ( bad implementation of hashCode method in your objects) you will actually end up with a linkedlist which will degrade the operations time to O(n). 12.In HashMap, if two objects have same hashcode How object is stored (reg collision) and how it is retrieved ? What is the internal data... ....................................................................................................................... answer1: HashMap calculates the hashcode of the key to store the value which you want to store. This hashcode is used to assign a bucket(an Linkedlist which stores the Entry Object which contains the key and value). In case, two unequal objects have the same hashcode, so both objects will be stored inside one bucket only. Now to retrieve the objects, HashMap checks for == and .equals() and the desired object will be retrieved. answer2: Hash map internally use LinkedList not an arraylist. Entry object stores in the bucket like this (hash,key,value,bucketindex) .The bucket is the linked list effectively . Its not a LinkedList as in a java.util.LinkedList - Its a separate (simpler) implementation just for the map . So we traverse through linked list , comparing keys in each entries using keys.equals() until it return true. Then the corresponding entry object Value is returned . 13.What is the use of clone() method ? clone() is method of object class then why we need to implement cloneable interface ? if we have not implement cloneable interface what happen ? ............................................................................................................................... answer: What is the use of clone() method? clone() is a method for object duplication. In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality. clone() is method of object class then why we need to implement cloneable interface ? Classes dont usually inherit a public clone() method because Object doesnt have a public clone() method, so it is usually unnecessary to explicitly implement a non-functional clone() method. If we have not implement cloneable interface what happen ? This is simple, you will get CloneNotSupportedException 14:Why in Java it is not recommended to specify or throw Unchecked Exceptions or create a subclass of RuntimeException ? ....................................................................................................................... answer: Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a programs clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can). One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null. If an argument is null, the method might throw a NullPointerException, which is an unchecked exception. Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you dont want to be bothered with specifying the exceptions your methods can throw. Bottom line : If you want to force the users of your custom exception to handle the exception, then you can extend your exception class from the Exception class, which will make your custom exception a checked exception. If you want to give flexibility to the users of your custom exception, and leave it to the users of your exception to decide if they want to handle the exception or not, you can derive your exception from the RuntimeException class. 15:Why StringBuffer and StringBuilder doesnt override equals() and hashcode() method ? ........................................................................................... aswer: First of all : StringBuilder/StringBuffer is not based on Builder pattern. Now Why hashcode() is not overridden for them? It is because, hashcode is used by the data structures that uses hashing algorithm to store the objects. Examples are : HashMap, HashTable, ConcurrentHashMap, HashSet.... e.t.c . Mostly such objects are used as key which are not meant to be changed throughout the program. Since StringBuilder/StringBuffer are expected to be mutated so, they are poor choices for such kind of roles... Now, Why equals() is not overridden for them? Well going by equals and hashCode contract in Java : If two objects are equal by equals method then there hashcode must be same. Now, had the equals method for StringBuilder/StringBuffer overridden , there corresponding hashcode method would also need to be overridden to follow that rule. But as explained earlier , these classes dont need to have there own hashcode implementation and hence same is with there equals method. 16.Why HashTable class does not allow null key and null values? ................................................................
Posted on: Wed, 22 Oct 2014 06:36:46 +0000

Trending Topics



Recently Viewed Topics




© 2015