There are four principle concepts upon which object oriented design and programming rest. They are:
1. Abstraction
2. Polymorphism
3. Inheritance
4. Encapsulation
Abstraction refers to the act of representing essential features without including the background details or explanations.
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It helps to modify your code without breaking the client code.
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) 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.
Inheritance is the process by which objects of one class acquire the properties of objects of another class. The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
1. Overloaded methods MUST change the argument list
2. Overloaded methods CAN change the return type
3. Overloaded methods CAN change the access modifier
4. Overloaded methods CAN declare new or broader checked exceptions
5. A method can be overloaded in the same class or in a subclass
Yes, we can have multiple methods with name “main” in a single class. However if we run the class, java runtime environment will look for main method with syntax as public static void main(String args[]).
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
1. The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
2. You cannot override a method marked final
3. You cannot override a method marked static
You can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding.
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not be binding the method calls since it is overloaded, because it might be overridden now or in the future.
No, because main is a static method. A static method can't be overridden in Java.
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:
1. You can only go back one level.
2. In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.
static keyword can be used with class level variables to make it global i.e all the objects will share the same variable.
static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.
PATH is an environment variable used by operating system to locate the executables. That’s why when we install Java or want any executable to be found by OS, we need to add the directory location in the PATH variable.
Classpath is specific to java and used by java executables to locate class files. We can provide the classpath location while running java application and it can be a directory, ZIP files, JAR files etc.
final keyword is used with Class to make sure no other class can extend it, for example String class is final and we can’t extend it.
We can use final keyword with methods to make sure child classes can’t override it.
final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example we can assign a final variable to an object only once but the object variables can change later on.
Java interface variables are by default final and static.
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.
The classloader is a subsystem of JVM that is used to load classes and interfaces. Following are the class loaders which executes in below mentioned order.
1. Bootstrap classloader (loads class file from rt.jar)
2.Extension classloader (loads class file from ext folder under JDK installlation directory)
3.System classloader (loads class file from classpath )
It is empty. But not null.
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.
Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).
final: final is a keyword, final can be variable, method or class.You, can't change the value of final variable, can't override final method, can't inherit final class.
finally: finally block is used in exception handling. finally block is always executed.
finalize(): finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected.The finalize() method can be used to perform any cleanup processing.
We can use break statement to terminate for, while, or do-while loop. We can use break statement in switch statement to exit the switch case.
The continue statement skips the current iteration of a for, while or do-while loop. We can use continue statement with label to skip the current iteration of outermost loop.
An interface is a description of a set of methods that conforming implementing classes must have. Note:
You can’t mark an interface as final.
Interface variables must be static.
An Interface cannot extend anything but another interfaces.
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.
Only public and abstract modifiers are allowed for methods in interfaces.
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
A local inner class without name is known as anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.
Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Note:
If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
You can’t mark a class as both abstract and final.
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
Use Interfaces when…
You see that something in your design will change frequently.
If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for non-leaf classes in class hierarchies.
Yes, other nonabstract methods can access a method that you declare as abstract.
A constructor is a special method whose task is to initialize the object of its class.
It is special because its name is the same as the class name.
They do not have return types, not even void and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
Constructor is invoked whenever an object of its associated class is created.
Constructors use this to refer to another constructor in the same class with a different parameter list.
Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
Java offers four access specifiers, listed below in decreasing accessibility:
Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the methods and fields belong.
Private methods and fields are not visible within subclasses and are not inherited by subclasses.
Classes can have only public or default access.
A class with default access can be seen only by classes within the same package.
A class with public access can be seen by all classes from all packages.
It provides concrete implementations for the interface's methods.
It must follow all legal override rules for the methods it implements.
It must not declare any new checked exceptions for an implementation method.
It must not declare any checked exceptions that are broader than the exceptions declared in the interface method.
It may declare runtime exceptions on any interface method implementation regardless of the interface declaration.
It must maintain the exact signature (allowing for covariant returns) and return type of the methods it implements (but does not have to declare the exceptions of the interface).
Instance variables can't be abstract, synchronized, native, or strictfp.
Checked exceptions include all subtypes of Exception, excluding classes that extend RuntimeException.
Checked exceptions are subject to the handle or declare rule; any method that might throw a checked exception (including methods that invoke methods that can throw a checked exception) must either declare the exception using throws, or handle the exception with an appropriate try/catch.
Subtypes of Error or RuntimeException are unchecked, so the compiler doesn't enforce the handle or declare rule. You're free to handle them, or to declare them, but the compiler doesn't care one way or the other.
You can create your own exceptions, normally by extending Exception or one of its subtypes. Your exception will then be considered a checked exception, and the compiler will enforce the handle or declare rule for that exception.
One of the Java 7 features is try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished.
Finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.
Immutable classes are Java classes whose objects can not be modified or changed once created. Any modification in Immutable object result in new object or exception. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Also it is required not have any setter methods in the class.
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
String s = new String("Test");
does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
Externalizable interface is used to write the state of an object into a byte stream in compressed format.It is not a marker interface.
Serializable is a marker interface but Externalizable is not a marker interface.When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.
You can supplement a class's automatic serialization process by implementing the writeObject() and readObject() methods. If you do this, embedding calls to defaultWriteObject() and defaultReadObject(), respectively, will handle the part of serialization that happens normally.
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.
The fundamental difference is wait() is from Object and sleep() is static method of Thread . The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.
Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.
We can ensure it by acquiring resources in a particular order and releasing resources in reverse order we can prevent deadlock.
No.The synchronized modifier applies only to methods and code blocks and synchronized methods can have any access control and can also be marked final.
You can call start() on a Thread object only once. If start() is called more than once on a Thread object, it will throw a RuntimeException
Java doesn’t support multiple inheritance in classes because of Diamond Problem. However multiple inheritance is supported in interfaces. An interface can extend multiple interfaces because they just declare the methods and implementation will be present in the implementing class. So there is no issue of diamond problem with interfaces.
With respect to the method it overrides, the overriding method must have the same argument list.
Must have the same return type, except that as of Java 5, the return type can be a subclass—this is known as a covariant return.
Must not have a more restrictive access modifier.
May have a less restrictive access modifier.
Must not throw new or broader checked exceptions.
May throw fewer or narrower checked exceptions, or any unchecked exception.
final methods cannot be overridden.
Only inherited methods may be overridden, and remember that private methods are not inherited.
A subclass uses super.overriddenMethodName() to call the superclass version of an overridden method.
Overloaded methods:
Must have different argument lists
May have different return types, if argument lists are also different
May have different access modifiers
May throw different exceptions
Methods from a superclass can be overloaded in a subclass.
Polymorphism applies to overriding, not to overloading.
Every class, even an abstract class, has at least one constructor.
Typical constructor execution occurs as follows:
The constructor calls its superclass constructor, which calls its superclass constructor, and so on all the way up to the object constructor.
The Object constructor executes and then returns to the calling constructor, which runs to completion and then returns to its calling constructor, and so on back down to the completion of the constructor of the actual instance being created.
The compiler will create a default constructor if you don't create any constructors in your class.
Three meanings for "collection":
collection Represents the data structure in which objects are stored
Collection java.util interface from which Set and List extend
Collections A class that holds static collection utility methods
ArrayList: Fast iteration and fast random access.
Vector: It's like a slower ArrayList, but it has synchronized methods.
LinkedList: Good for adding elements to the ends, i.e., stacks and queues.
HashSet: Fast access, assures no duplicates, provides no ordering.
LinkedHashSet: No duplicates; iterates by insertion order.
TreeSet: No duplicates; iterates in sorted order.
HashMap: Fastest updates (key/values); allows one null key, many null values.
Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.
LinkedHashMap: Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.
TreeMap: A sorted map.
PriorityQueue: A to-do list ordered by the elements' priority.
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.
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.
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).
Some of the advantages ArrayList has over arrays are:
It can grow dynamically
It provides more powerful insertion and search mechanisms than arrays.
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.
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.
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.
The Set interface provides methods for accessing the elements of a finite mathematical set.
Sets do not allow duplicate elements.
Contains no methods other than those inherited from Collection.
It adds the restriction that duplicate elements are prohibited.
Two Set objects are equal if they contain the same elements.
The main implementations of the List interface are as follows:
HashSet
TreeSet
LinkedHashSet
EnumSet
A HashSet is an unsorted, unordered Set.
It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.
A map is an object that stores associations between keys and values (key/value pairs).
Given a key, you can find its value. Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others cannot.
The main implementations of the List interface are as follows:
HashMap
HashTable
TreeMap
EnumMap
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
TreeMap actually implements the SortedMap interface which extends the Map interface.
In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time.
TreeMap is based on the Red-Black tree data structure.
Maps Provide Three Collection Views.
Key Set - allow a map's contents to be viewed as a set of keys.
Values Collection - allow a map's contents to be viewed as a set of values.
Entry Set - allow a map's contents to be viewed as a set of key-value mappings.
The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.
1. Class(Method) Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Stack
A thread should not be stopped by using the deprecated methods stop() of java.lang.Thread, as a call of this method causes the thread to unlock all monitors it has acquired. If any object protected by one of the released locks was in an inconsistent state, this state gets visible to all other threads. This can cause arbitrary behavior when other threads work this this inconsistent object.
A user thread cannot be converted into a daemon thread once it has been started. Invoking the method thread.setDaemon(true) on an already running thread instance causes a IllegalThreadStateException.
A shutdown hook is a thread that gets executed when the JVM shuts down. It can be registered by invoking addShutdownHook(Runnable) on the Runtime instance: Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { } });