Core Java What are the principle concept of OOPS? Oops has 4 principle concept. 1. 2. 3. 4. Abstraction Polymorphism Inheritence Encapsulation What are Encapsulation, Inheritance and Polymorphism? Encapsulation: Mechanism of binding together code and data and keeping it safe from interference from both outside and inside. Inheritance: Process of acquiring the property of one Object by another Object. Polymorphism: Feature which allows one interface to be used for general class actions. What is the difference between abstraction and encapsulation? Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented. Abstraction solves the problem in the design side while Encapsulation is the Implementation. Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs. How Java implement polymorphism? Inheritance, Overloading and Overriding are used to achieve Polymorphism in java. Overloading of Method Overriding of Method Explain different form of Polymorphism. Two type of polymorphism is there 1. Compile time polymorphism 2. Runtime polymorphism IT can be divided in 2 parts again 1- Method Overloading 2- Method Overriding What is Overloading? Look Here for better understanding of Overloading What is Overriding? Look Here for better understanding of Overriding Can we Overload Overriden method? Yes, Derived class can Overload, overridden method. Can we Override Main method? No, Main method is static method and static method can’t be Overriden. It will be hidden in derieved class. For Rules of Overriding look here How can we invoke super class version of Overriden method? Super keyword can be used for this purpose. super keyword will invoke the overriden method from super class. Syntax: super.methodName() What is Super? Super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. Note*:super or this needs to be first statement in method declaration. Hence both can not be used at the same time. Is there any way we can prevent method from being overriden? We can avoid method overriding by using final keyword. Syntax: public void final methodName(){} What is an Interface? Contract class needs to follow when it is inherting it. For Complete functionaing of Interface look here Can we instantiate Interface? No Does Interface have member variable Yes they have but these variable will be public , static and final implicitly Modifiers Allowed for method inside Interface? Only Public & abstract modifier is allowed. Can there be an abstract class with no abstract methods in it? Yes, there can be an abstract class without abstract methods. What is Class Class is a template for multiple objects with similar features(State & Behavior) and it is a blue print for objects What is Constructor Special kind of method that determines how an object is initialized when created. What is the difference between Constructor & Method? Constructor needs to have the name of Class. Method can have any name even the Class name. Constructor can not return any value like Method. Constructor will be invoked implicitly when object of Class is created. While method needs to be invoked. Can constructor be inherited? No, constructor cannot be inherited, though a derived class can call the base class constructor. What is Casting? Process of converting the value of One type to another type. What is the difference between an argument and a parameter? While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments. What are different types of access modifiers? Three type of access modifiers are there 1. Public 2. Private 3. Protected For more detail refer: Java Beginners Tutorial What is Finally & Finalize? Finally: Key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will get execute whether or not an exception is thrown. There will be only one case when finally block will not get executed & that would be system.exit(). finalize: finalize method will be called just before garbage collection of Object What is Garbage Collection ? How to call garbage collection explicitly? When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly. Note*: It is just request to garbage collection. It doesn’t force JVM to garbage collect. What are Transient and Volatile Modifiers? Transient: Transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program. Why wait and Notify is in Object Class and not in Thread In Multi Threaded model Java uses locks to implement exclusive access to object & lock is related to object and not Thread. These methods work on the locks of the object i.e. the reason why these methods are in Object class and not in Thread. How(Steps) to Create Immutable Class? Some Rules needs to be followed in order to create Immutable class. 1- Make constructor private 2- Provide static method to get instance to class. 3- Throw CloneNotSupported exception. 4- Make class Final. Difference between notify and notifyall? notifyall() method causes all the waiting threads (on the same lock) to wake up(runnable state) , As only thread can access lock at a time so one thread will start running while all other thread that wakeup with notifyall() will not run immediately, but they will run eventually as each in turn acquire and eventually free the lock. notify() method wakes up only one thread it acquires and free the lock after completion But other threads will not be unblocked even when lock is free to take. What is the DIfference between abstract class and Interface? An abstract class is a class which may have the usual flavors of class members (private, protected, etc.) with some abstract methods. An abstract class can have instance methods with default behavior. A class can extend only one abstract class. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. Methods are implicitly public and variables are implictly public static Final. Which one to choose depends on the design requirement. Difference between hashMap and hashTable? HashMap is unsynchronised while HashTable is synchronised but we can synchronise the HashMap with use of Collections.synchronizedMap(new HashMap()); HashMap permits null values in it, while Hashtable doesn’t. HashTable has method which Returns an enumeration of the values in hashtable which is not fail safe. But there is no such method in HashMap. What is Checked and Unchecked Exception? Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller. Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are Unchecked exceptions, compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be. What is the use of Final keyword? Final is a modifier which can be applied on Class / Method / Variable. 1. Final class can not be extended. 2. Final method can not be overridden. 3. Final variables value can’t be changed once assigned. Can we have several main method in the same class? Yes a class can have several main() method. But main method from the public class in the same file will be accessed while running the app. Different type of Inner Class? 1- Static 2- Method Local 3- Anonymous 4- Other then above these normal inner class What are wrapper classes and what is use of it? In Java everything except primitives are object. These primitives don’t get the benifit of being object. Wrapper classes are created to provide the same to primitives. Integer class is wrapper for int primitive. Different state of Threads? 1- Instantiated 2- Runnable 3- Running 4- Wait/blocked/Sleep 5- Completed How to implement Singleton pattern? Single instance per JVM 4 thing needs to followed in order to achieve it. 1- Make constructor private. 2- Provide Static method to get singleton object 3- Make a private referrence variable 4- Check for ref type in static method if it is null then make a reference and assign it and return else just return. 5- make the static method as synchronized.(when 2 thread access the same time they will see ref as null and end up in creating two reference so avoid that situation need to make static method as synchronized) 6- Provide the implementation for Clone() method and throw CloneNotSupportedException exception from method (If singleton class extend some other class which is supporting the Clone method in that case we need to do this otherwise Clone method will create another instancce) What is the difference between Integer and Int? Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Integer is wrapper class for Int. Integer is an Object while Int is not Can we have an inner class inside method? Yes, More details can be found here What is the difference between String and String Buffer? String is immutable, value assigned once to String can not be changed while StringBuffer is mutable. What is the difference between Array and vector? Array is a set of related data type and static whereas vector is a growable array of objects and dynamic. What are different states of Thread in Java? States are : 1. 2. 3. 4. 5. New Ready Running Wait / Blocked Dead For more details look here What is synchronization? Synchronization is a mechanism that ensures that only one thread accessed a particular resources at a time. What is deadlock? When two threads are waiting each other and can’t precede the program is said to be deadlock. Collection FAQ What is an Iterator ? The Iterator interface is used to step through the elements of a Collection. Iterators let you process each element of a Collection. Iterators are a generic way to go through all the elements of a Collection no matter how it is organized. Iterator is an Interface implemented a different way for every Collection. How do you traverse through a collection using its Iterator? To use an iterator to traverse through the contents of a collection, follow these steps: Obtain an iterator to the start of the collection by calling the collection’s iterator()method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext()returns true. Within the loop, obtain each element by calling next(). How do you remove elements during Iteration? Iterator also has a method remove() when remove is called, the current element in the iteration is deleted. What is ListIterator? ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element What is the List interface? The List interface provides support for ordered collections of objects. Lists may contain duplicate elements. What are the main implementations of the List interface ? The main implementations of the List interface are as follows : ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface. Vector : Synchronized resizable-array implementation of the List interface with additional “legacy methods.” LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques). What are the advantages of ArrayList over arrays ? It can grow dynamically It provides more powerful insertion and search mechanisms than arrays. Why insertion and deletion in ArrayList is slow compared to LinkedList ? ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node. Why are Iterators returned by ArrayList called Fail Fast ? Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. How do you decide when to use ArrayList and When to use LinkedList? If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation. Thread FAQ Different state of Thread? States are 1. 2. 3. 4. 5. 6. New Ready Runnable Running waiting/blocked Dead Basic java interview questions - contributed bu Rohit Srivastava What is reflection? What is JVM? Explain different layout manager in Java. What is difference between Stream classes and Reader writer classes? Explain the use of RandomAccessFile classes. What is object Serialization? Explain the use of Persisting object. What is the difference between procedural and object-oriented programs? What are inner class and anonymous class? What is multithreading and what is the class in which these methods are defined? What is the difference between applications and applets? What is adapter class? What is JavaDoc utility? What are the advantages of Java layout managers? Explain Marker Interface. What is the difference between Process and Thread? How do you declare a class as private? What is the drawback of inheritance? What is the difference between notify() and notifyAll()? Why are there no global variables in Java? What is reflection? Reflection: is property by which program can analyze itself. It is given by the java.lang.reflect package. This enables us to evaluate the software components and detailed knowledge of its capabilities dynamically. We can use this reflection to access the public methods of a class. Member which is present in the java.lang.reflect package is used to extract information regarding the fields, constructor and method of a class. What is JVM? Java Virtual Machine (JVM): is an interpreter for bytecode. JVM is a platform independent and converts Java byte code into machine language and executes it. Program calls compiler to translate the program code into executable code that computer can understand and execute. The executable code depends upon the computer operating system that we use to execute our program. It is machine dependent. Explain different layout manager in Java. Some of the components like Button, Checkbox, Lists, Scrollbars, Text Fields, and text area are positioned by the default layout manager. There are following types of layouts are used to organize or to arrange objects: Border Layout: Five areas for holding components: north, east, west, south and center. Flow Layout: Default layout manager, lays out the components from left to right Card Layout: Different components at different times are laid out, Controlled by a combo box. Grid Layout: Group of components are laid out I equal size and displays them in certain rows and columns. Grid Bag Layout: Flexible layout for placing components within a grid of cells. What is difference between Stream classes and Reader writer classes? Stream Classes: Hierarchy is byte oriented Unicode characters are not supported 8-bit streams are supported. The streams supports filtering data into primitive types using DataOutputStream and DataInputStream Object serialization supports byte oriented stream Data over network passes a stream of bytes Available since JDK 1.0 Reader and Writer Classes: hierarchy is character oriented The never support byte streams Supports 16-bit Unicode characters. Supports to read a group of characters at once Available since JDK 1.1 Explain the use of RandomAccessFile classes. RandomAccessFile enables us to perform read and write operations on file. In this we use the file pointer to points the positions from where the reading or writing operation is performed. It defines operation modes (read / write). r mode- Open for reading only. rw mode- Open for reading and writing. seek(file.length()) method- It jumps the file pointer at the specified location. rand.close() method- It closes the random access file stream. writeBytes( ) method- It simply writes the content into the file. readByte() method- It reads a single byte from the file. readLine() method- It reads the line from the file. What is object Serialization? Explain the use of Persisting object. Serialization is the process of saving the state of object to a byte stream. This enables us to save the state of object. So that we can use this value to again restart our program using Deserialization Process. This value can be stored in file. Serialization allows the objects to move from one computer to another by maintaining their state. It implements java.io.Serialization interface with few lines of code. The following is the class declaration to serialize an object Public class UserData implements java.io.Serializable When an application uses objects, it cannot use all objects at once. The required objects can be desterilized and then it handles. Later another object is handled, allowing the memory to conserved space for better performance. What is the difference between procedural and object-oriented programs? The difference between procedural and object oriented programming are: Procedural programming creates a step by step program that guides the application through a sequence of instructions where as object oriented programming is analogous to human brain, multiple programming at a time. In procedural each instruction is executed in order whereas in object oriented programming each program is made up of many entities called objects. Procedural programming also focuses that all algorithms are executed with functions and data that the programmer has access to and is able to change bit in object oriented, Objects become the fundamental units and have behavior. In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible within the object and which in turn assures the security of the code. What are inner class and anonymous class? Inner class: classes that are defined within other classes. The nesting is a relationship performed between two different classes. An inner class can access private members and data. Inner classes have clearly two benefits: o Name control o Access control. Anonymous class: Anonymous class is a class defined inside a method without a name. It is instantiated and declared in the same method. It does not have explicit constructors. What is multithreading and what is the class in which these methods are defined? Multithreading is the mechanism which allows us to do many things simultaneously. A multithreaded enable us to executed two or more program at same time which are totally independent of each other. Each part of such a program is called a thread. Each thread defines a separate path of execution inside the program. To communicated between two threads we use methods like wait (), notify () and notifyAll() and these methods are in Object class.wait(). What is the difference between applications and applets? The differences between an Applet and an application are as follows: Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading. Application starts execution with its main method whereas applet starts execution with its init method. Application must be run on local machine whereas applet needs no explicit installation on local machines. Application must be run explicitly within a java-compatible virtual machines whereas applet loads and runs itself automatically in a java-enabled browser. Application can run with or without graphical user interface whereas applet must run within a graphical user interface. What is adapter class? An adapter class is a class that enables a dummy or empty implementation for an interface. We can use the adapter class when we don’t know how to implement interface. After getting the interface we can override those methods which are required in our programming. It is useful when we want to receive and process only some of the events that are handled by a particular event listener interface. We can create a new class which can act as a listener by extending the adapter classes and implementing only those events which is required. What is JavaDoc utility? Javadoc is java tool, used to parse the declaration comments and documentation comments available in a set of java source files. Javadoc produces a group of HTML pages with information about classes, interfaces, constructors, methods and fields. Syntax: javadoc [options] [packagenames] [sourcefiles] [@files] Arguments can be in any order. Options: Command-line options that is doc title, window title, header, bottom etc Packagenames: A series of names of packages, separated by spaces. You must separately specify each package we want to document. Sourcefiles: A series of source file names, separated by spaces, each of which can begin with a path and contain a wildcard such as asterisk (*). @files: One or more files that contain PackageNames and Sourcefiles in any order, one name per line. What are the advantages of Java layout managers? In Java Button, Checkbox, Lists, Scrollbars, Text Fields, and Text Area etc positioned by the default layout manager. Using algorithm layout manager automatically arranges the controls within a window. In Windows environment, we can control layout manually. But we do not do it manual because of following two reasons: It is very tedious to manually lay out a large number of components. Sometimes the width and height information is not available when you need to arrange some control, because the native toolkit components have not been realized. This is a chicken-and-egg situation. Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Explain Marker Interface. Marker interface in Java is interfaces with no field or methods. Features of Mark Interfaces are following: We use Marker interface to tell java complier to add special behavior to the class implementing it. Java marker interface has no members in it. It is implemented by classes in get some functionality. Example: when we want to save the state of an object then we implement Serializable interface. What is the difference between Process and Thread? The major difference between threads and processes is: Threads share the address space of the process that created it whereas processes have their own address. Threads can directly access to the data segment of its process whereas processes have their own copy of the data segment of the parent process. Threads communicate directly with other threads of its process whereas processes use interprocess communication to communicate with child processes. Threads have almost no overhead whereas processes have considerable overhead. New threads are easily created whereas new processes require duplication of the parent process. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes. Changes to the main thread affect the behavior of the other threads of the process whereas changes to the parent process do not affect child processes. How do you declare a class as private? We can declare a private class as an inner class. For example, class MyPrivateClass { private static class MyKey { String key = "91234"; } public static void main(String[] args) { System.out.println(new MyKey().key);//prints 91234 } } What is the drawback of inheritance? Main disadvantage of using inheritance are: Coupling: two classes (base and inherited class) get tightly coupled. Maintenance: Adding new features, involves both base and inherited derived classes are required to be changed. Time and Effort: It takes more time and effort to perform change in any of the class. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of using that method. Understanding of code: It make programming code more complex which makes it difficult to understand the code. What is the difference between notify() and notifyAll()? The notify() method wakes up a single thread waiting on the object and passes the control of the monitor to it. . If the wait set of the object is non-empty then a thread from the set is arbitrarily chosen, removed and is re-enabled for thread scheduling. The notifyAll() says that it will wake up all the threads waiting on the object and will select a thread to pass control to it. Using notify() is preferable when only one blocked thread can benefit from the change. notifyAll() is necessary if multiple threads should resume. Why are there no global variables in Java? Global variables are globally accessible. Java does not support globally accessible variables because the global variable breaks the referential transparency and also a global variable creates collisions in namespace. As JAVA is pure object oriented language so there are no global variables because each variable is to be declared in a class and object of a class must be initialized to use its variables and functions when we add one variable. We limit the use of your program to one instance. What we thought was global. Someone else might think of as local, they may want to run two copies of program at once. What is an interface and how will you go about implementing an interface? Explain the difference between Static and Non-Static fields of a class. What are Class loaders? Explain the types of class loader, i.e. Bootstrap Class loader, Extension Class loader and System Class loader Can you explain how can we practically do dynamic loading? Explain how to implement Shallow Cloning. Explain how to implement Deep Cloning. Can you explain how Scheduling and Priority works in threads? Explain how to implement single threaded model in servlets. Can you explain how Java interacts with database? Explain the different section of JDBC and their usage. Can you explain SQLException class? What is SQL State in SQL Exception Can you explain CallableStatement interface in details? Explain how to do batch updates using CallableStatement interface. Explain the architecture of a Servet package. Explain different Authentication Options available in Servets. Can you explain JDBCRealm? More basic Java interview questions - frequently asked Java interview Explain in brief transient modifiers and volatile modifiers. When serializable interface is declared, the compiler knows that the object has to be handled so as so be able to serialize it. However, if you declare a variable in an object as transient, then it doesn’t get serialized. Volatile - Specifying a variable as volatile tells the JVM that any threads using that variable are not allowed to cache that value at all. Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program. Define daemon threads and explain its purposes. Threads that work in the background to support the runtime environment are called daemon threads. Eg garbage collector threads. When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service. You cannot create a daemon method but you can use public final void setDaemon(boolean isDaemon) method to turn it into one. Can you explain JAVAdoc utility. Javadoc utility enables you to keep the code and the documentation in sync easily. The javadoc utility lets you put your comments right next to your code, inside your ".java" source files. All you need to do after completing your code is to run the Javadoc utility to create your HTML documentation automatically. StringBuilder class vs. StringBuffer class. StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer. Can you explain semaphore and monitors in java threading? A semaphore is a flag variable used to check whether a resource is currently being used by another thread or process. The drawback of semaphores is that there is no control or guarantee of proper usage. A Monitor defines a lock and condition variables for managing concurrent access to shared data. The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time. A semaphore is a generalization of a monitor. A monitor allows only one thread to lock an object at once. Describe synchronization in respect to multithreading. Multithreading occurs asynchronously, meaning one thread executes independently of the other threads. In this way, threads don’t depend on each other’s execution. In contrast, processes that run synchronously depend on each other. That is, one process waits until the other process terminates before it can execute What are Checked and UnChecked Exception? The java.lang.Throwable class has two subclasses Error and Exception. There are two types of exceptions non runtime exceptions and runtime exceptions. Non runtime exceptions are called checked exceptions and the unchecked exceptions are runtime exceptions. Runtime Exceptions occur when the code is not robust and non runtime exceptions occur due to the problems is environment, settings, etc. In which scenario LazyInitilizationException will occur in Hibernate ? how to over come it? when we are loading the data from the data base use load() method of Session. And we are getting the data from bean after session has been closed . In such scenerio LazyInitilizationException will occur. i.e for Example Session sess=factory.openSession(); Transaction trans=sess.beginTransaction(); SampleEntity se=(SampleEntity)sess.load(SampleEntity.class,11); trans.commit(); sess,close(); System.out.println(se.getName()); To overcome this problem use initialize() of Hibernate i.e Session sess=factory.openSession(); Transaction trans=sess.beginTransaction(); SampleEntity se=(SampleEntity)sess.load(SampleEntity.class,11); Hibernate.initialize(se); trans.commit(); sess,close(); System.out.println(se.getName()); Is it recommended to handle NumberFormatException? NumberFormatException is Unchecked Exception. It is not recommended to handle Unchecked exception. So, we have to prevent it with out raising that Exception. we can prevent it by using regular expression i.e public boolean isInteger(String str) { return str.matches(“^-?[0-9]+(\\/[0-9]+)?$”); } What is Singleton pattern? How can we implements this pattern in Java and Spring? Singleton pattern allows us to create only one instantiation of a class to one object. We can achieve this in Java by using private class Constructor i.e Public Class Singleton{ private static Singleton sing; private Singleton(){} public static Singleton getObject() { sign=new Singleton(); } } In spring by default all beans are Singleton . To change we have to define a tag called scope for latest version and for old version we have to use tag called singleton New Version:<bean id='sampleid” class=”example.sample” scope=”singleton”> Old Version:<bean id='sampleid” class=”example.sample” singleton=”true”>