Library

Course: Java Interview Preparation || 100+ Quality Questions Covered

Java Interview Preparation || 100+ Quality Questions Covered

  • Life Time Access
  • Certificate on Completion
  • Access on Android and iOS App
  • Self-Paced
About this Course

Welcome to Java Interview Preparation Course.

This course will help you to crack your next Java Interview by brushing up your Java knowledge.

You will get clarifications of Java concepts from basic to advanced such as -

  • Java Platform - JVM, JRE, JDK
  • Java 8 Interview Questions - Functional Interface, Lambda Function, Stream API, Optional
  • OOPs concepts - Inheritance, Polymorphism, Abstraction, Encapsulation
  • Exception
  • Collection
  • Design Patterns - Singleton Design Pattern, Factory Design Pattern
Basic knowledge
  • Need to have basic idea of core Java
What you will learn

You will get clarifications of Java concepts from basic to advanced such as -

  • Java Platform - JVM, JRE, JDK
  • Java 8 Interview Questions - Functional Interface, Lambda Function, Stream API, Optional
  • OOPs concepts - Inheritance, Polymorphism, Abstraction, Encapsulation
  • Exception
  • Collection
  • Design Patterns - Singleton Design Pattern, Factory Design Pattern
Curriculum
Number of Lectures: 105
Total Duration: 02:12:44
Introduction
  • Introduction  
  • Practice Code  

    In every session, inside last lecture you will get source code that is used during lectures for a session.

Java Basics
  • What is JVM, JRE and JDK ?  
  • Difference between Path and Classpath  
  • Is Java platform independent ? Why ?  
  • Difference between Java and C++  
  • What if I write static public void instead of public static void ?  

    The program compiles and runs correctly.

  • Explain Access Modifiers in Java.  
    • default - Its visible for same class and same package. It is NOT visible to sub classes in different packages.
    • public - Its is accessible from anywhere.
    • private - Its visible to only within class.
    • protected - Its visible in same class, same package and sub classes in different packages.


OOPs Concepts
  • Explain OOPs Concepts With Real Time Examples  
  • How to prevent inheritance and method overriding?  
  • Can we declare main method as final ?  
  • Is Multiple inheritance supported in Java ? Why ?  
  • Execution sequence for static block, block, constructor and method.  
  • Can we run abstract class which has main method ?  
  • What is Marker Interface ?  
  • Difference between an Interface and Abstract Class  
    • Interface can have only method signatures while abstract class can have abstract methods and concrete methods as well.
    • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
    • A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
    • Variables in interface are public static final where as abstract class can have non static variables.


  • Can we override a static method ?  

    No, we cannot override a static method in Java.


  • Can we make constructors static ?  
    • No.
    • As we know that the static context (method, block, or variable) belongs to the class, not the object.
    • Since Constructors are invoked only when the object is created, there is no sense to make the constructors static.
    • However, if you try to do so, the compiler will show the compiler error.


  • Can we override the overloaded method ?  

    Yes. We can override the overloaded method in Java.


  • Difference between Constructor and Method ?  
    • The constructor name must be same as the class name. While the method name may or may not be same as class name.
    • Constructor does not have any return type. While method has.
    • Java compiler provides default constructor if there is no constructor. While this is not the case for method.
  • Can we execute a program without main() method ?  
    • Yes. Using static block we can do this.


  • Can you use abstract and final both with a method ?  
    • No, We can not.
    • Abstract method is meant to be overridden so we can not mark it as final.
  • Can we declare an interface as final ?  
    • No we can not declare Interface as final.
    • The main purpose of Interface is being inherited. If we declare interface as final then we can not implement/inherit an interface.
    • If you try to declare interface as final then it will compilation error
  • Distinguish between static loading and dynamic class loading ?  
    • When we create an object of class using new then its static class loading.
    • When we use Class.forName() to get class and to create an object then its dynamic class loading.


  • Can we override the private methods ?  
    • No
    • We cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.
  • Can we declare a constructor as final ?  
    • No we can not declare constructor as final.
    • Constructor is not being inherited and so it can not be overridden and hence we can not declare constructor as final.
Exception
  • Difference between Checked and Unchecked Exceptions  
  • How to create Custom Exception Class ?  
  • Is there any case when finally will not be executed ?  
  • Which is the base class of all exception classes ?  
    • It is Java.lang.Throwable


  • Explain about Exception Propagation  
    • Exception is first thrown from the method which is at the top of the stack.

    • If it doesn’t catch, then it pops up the method and moves to the previous method and so on until they are caught.


  • Difference between throw and throws.  
    • Throw is used to throw an exception where as throws is used to declare an exception.
    • When there is checked exception then we need to handle it with throws while for unchecked exceptions we can have exception propagation with throw.


  • Difference between Error and Exception.  
    • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch while we can catch exceptions at runtime using try, catch and finally.
    • Example of Error : OutOfMemoryError - We can not do much as our program can no longer run.
    • Example of Exception : NullPointerException - Tried to access resource which has null value.


Collection
  • Difference between List and Set  
  • Unmodifiable Collection  
  • What is UnSupportedOperationException ?  
  • Difference between peek(),poll() and remove() method of the Queue interface  
  • How HashMap internally works ?  
    • HashMap works on hashing.
    • Its Key-Value pair.
    • Hashing is a process of converting an object into integer form by using the method hashCode().
    • Key is stored as hash value in bucket.
    • It may happen that two different keys can have same hash value. In that case it uses equals() method to compare two keys and in bucket linked list structure is used. While retrieving elements it two values are there in bucket then it uses equals() method.


  • How HashSet works internally ?  
    • HashSet allows only unique values.
    • HashSet's add() method uses HashMap internally to check uniqueness of value as HashMap has unique key.


  • Difference between ArrayList and Vector  
    • Array list is not thread safe while vector is thread safe.
    • Vector is slow in performance as it is thread safe while Arraylist is fast as it is not thread safe.
    • Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%. By default ArrayList size is 10 . It checks whether it reaches the last element then it will create the new array ,copy the new data of last array to new array ,then old array is garbage collected by the Java Virtual Machine (JVM) .
    • Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator .While ArrayList can only use Iterator for traversing an ArrayList .


  • Difference between HashMap and HashTable  
    • HashMap is not thread safe while HashTable is thread safe.
    • HashMap has good performance as it is not synchronized while HashTable is slow in performance as it is synchronized.
    • HashMap allows one null key and any number of null values in it while HashTabe does not allow any null keys and values in it.
    • HashMap values are iterated by iterator while HashTable values are iterated by iterator and enumeration.


  • Difference Between Iterator And Enumeration  
    • Iterator has three methods – hashNext(), next() and remove().
    • Enumeration has two methods – hashMoreElements() and nextElement().
    • Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. We cannot remove elements from a collection when using enumerator.


  • Difference between Iterator and ListIterator  
    • Using Iterator we can traverse the list of objects in forward direction . But ListIterator can traverse the collection in both directions that is forward as well as backward.
    • Iterator can be used for traversing Set, List and Map. ListIterator can only be used for traversing a List.


  • Difference between Fail Fast iterator and Fail Safe iterator  
    • Fail fast iterator while iterating through the collection then instantly throws Concurrent Modification Exception if there is structural modification of the collection.
    • Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.
    • So original data structure remains structurally unchanged .Hence no ConcurrentModificationException throws by the fail safe iterator.


  • How Fail Fast Iterator come to know that the internal structure is modified ?  
    • Iterator read internal data structure (object array) directly .
    • The internal data structure(i.e object array) should not be modified while iterating through the collection.
    • To ensure this it maintains an internal flag "mods".
    • Iterator checks the "mods" flag whenever it gets the next value (using hasNext() method and next() method).
    • Value of mods flag changes whenever there is an structural modification.
    • Thus indicating iterator to throw ConcurrentModificationException.


  • Difference between HashSet and TreeSet  
    • HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order.
    • HashSet can store null object while TreeSet can not store null object.
  • Difference between HashMap and ConcurrentHashMap  
    • HashMap is not synchronized while ConcurrentHashMap is synchronized.
    • HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .
  • Difference between ArrayList and LinkedList  
    • ArrayList is the resizable array implementation of list interface , while LinkedList is the Doubly-linked list implementation of the list interface.
    • LinkedList can be iterated in reverse direction using descendingIterator() while there is no descendingIterator() in ArrayList , so we need to write our own code to iterate over the ArrayList in reverse direction.
    • LinkedList is preferred for add and update operations while ArrayList is a good choice for search operations.
  • Why Map interface does not extend the Collection interface ?  
    • Map interface is not compatible with the Collection interface.
    • Since Map requires key as well as value , for example , if we want to add key-value pair then we will use put(Object key , Object value) . So there are two parameters required to add element to the HashMap object . In Collection interface add(Object o) has only one parameter.
    • Hence Map interface does extend the Collection interface in Java.
  • What is hash-collision ? How it is handled in Java ?  
    • If two different keys have the same hash value then it lead to hash -collision.
    • A bucket of type linkedlist used to hold the different keys of same hash value.
  • How do you convert a given Collection to SynchronizedCollection ?  
    • Below is the way for synchronized collection in Java.
    • Collections.synchronizedCollection(Collection collectionObj)
  • Why ArrayList is better than Arrays ?  
    • Array can hold fixed number of elements. ArrayList can grow dynamically.
  • For addition and deletion. Which one is most preferred ArrayList or LinkedList ?  
    • LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.
  • For searches. Which one is most preferred: ArrayList or LinkedList ?  
    • ArrayList. Searching an element is faster in ArrayList compared to LinkedList.
  • Difference between Array and ArrayList.  
    • For Array we need to provide size while creating it while for ArrayList size is dynamic.
    • For Array to add an element we need to provide while for ArrayList index is NOT required for adding an element in ArrayList.
  • Explain TreeMap.  
    • The class implements Map interfaces including NavigableMap, SortedMap and extends AbstractMap.
    • TreeMap always keeps the elements in a sorted(increasing) order
    • TreeMap in Java does not allow null keys.
    • TreeMap is not synchronized and thus is not thread-safe.
  • Difference between HashMap and TreeMap  
    • HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted Map interface is a child of Map.
    • HashMap implements Hashing, while TreeMap implements Red-Black Tree(a Self Balancing Binary Search Tree).
    • There is no order in HashMap while TreeMap maintains an order for elements.
  • What is the difference between Collection and Collections ?  
    • Collection is an interfaces while Collections is a class.
    • The Collection interface provides the methods which are used for data structure while Collections class provides the static methods which can be used for various operation on a collection.
Design Pattern
  • Singleton Design Pattern  
  • Factory Design Pattern  
  • How to create Immutable Class ?  
  • Difference between Static Class and Singleton Class ?  
    • A static class can not be a top level class where a singleton class can.
    • All members of a static class are static but for a Singleton class it is not a requirement.
    • Static class get initialized when it is loaded so it can not be lazily loaded where a singleton class can be lazily loaded.
    • A static class object is stored in stack whereas Singleton class object is stored in heap memory space.
  • Which design patterns are used in JDK ?  
    • Decorator pattern is used by Wrapper classes.
    • Singleton pattern is used by Runtime, Calendar classes.
    • Factory pattern is used by Wrapper class like Integer.valueOf.
    • Observer pattern is used by event handling frameworks like swing, awt.
Java 8 Interview Questions
  • Introduction To Java 8  
  • What is Functional Interface ?  
  • What is Lambda Expression ?  
  • What is Stream API ?  
  • What is Optional ?  
  • What is StringJoiner ?  
  • Difference between Collection API and Stream API  
    • Collection API is in use since Java 1.2. Stream API is added to Java in version 8.
    • Collection API is used for storing data in different kinds of data structures. Stream API is used for computation of data on a large set of Objects.
    • With Collection API we can store a finite number of elements in a data structure. With Stream API, we can handle streams of data that can contain infinite number of elements.
    • Collection API constructs objects in an eager manner. Stream API creates objects in a lazy manner.
    • Most of the Collection APIs support iteration and consumption of elements multiple times. With Stream API we can consume or iterate elements only once.
  • What kind of variable you can access in an lambda expression ?  

    Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

  • Difference between Iterator and Spliterator  
    • Iterator was introduced in jdk 1.2 while Spliterator is introduced in jdk 1.8
    • Iterator is used for Collection API while Spliterator is used for Stream API
    • Iterator can be used for iterating the elements in Collection in sequential order while Spliterator can be used for iterating the Stream elements in parallel or sequential order.
  • Differences between Java’s OLD Date API and Java 8’s Date and Time API  
    • Earlier Date API was not thread safe while Java 8's Date and Time API is thread safe.
    • Earlier Date API was mutable while Java 8's Date and Time API is Immutable.
    • Earlier Date API defines months from 0 to 11 while Java 8's Date and Time API defines months from 1 to 12.
Serialization
  • What is Serialization ?  
  • What is Deserialization ?  
  • What is transient variable ?  
  • What is SerialVersionUID ?  
Other Questions
  • In how may ways we can create an object in Java ?  
  • What is Ternary Operator ?  
  • What is the purpose of a Volatile Variable ?  
    • Volatile variable values are always read from the main memory and not from thread’s cache memory.
    • This is used mainly during synchronization.
  • What is Externalizable ?  
    • Externalizable is an Interface that extends Serializable Interface.
    • It sends data into Streams in Compressed Format.
  • What is the difference between a static and a non-static inner class ?  
    • A non-static inner class may have object instances that are associated with instances of the class's outer class.
    • A static inner class does not have any object instances.
  • What are order of precedence and associativity, and how are they used ?  
    • Order of precedence determines the order in which operators are evaluated in expressions.
    • Associatity determines whether an expression is evaluated left-to-right or right-to-left.
  • What is the difference between inner class and nested class ?  
    • When a class is defined within a scope of another class, then it becomes inner class.
    • If the access modifier of the inner class is static, then it becomes nested class.
  • Difference between StringBuffer and StringBuilder  
    • StringBuffer is synchronized, StringBuilder is not. Hence it is faster than StringBuffer.
  • this() Vs super()  
    • this() refers to the same class where as super() refers to parent class.
    • this() is used call the methods and constructors of the same class while super() is used call methods and constructors of the parent class.
  • Can you use this() and super() both in a constructor ?  
    • No.
    • Because this() and super() must be the first statement in the class constructor so its not possible to use both in a constructor.
  • Difference between flush() and close()  
    • flush() just makes sure that any buffered data is written to destination.
    • close() flushes the data and indicates that there isn't any more data. It closes any file handles, sockets or whatever. You then can't write to the stream (or writer) any more.
  • What is anonymous inner class ?  
    • A local inner class without name is known as anonymous inner class.
    • 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.
  • What is Classloader in Java ?  
    • Java Classloader is the program that loads byte code program into memory when we want to access any class during runtime.
    • They are part of JRE.
  • Explain Annotation  
    • Java Annotation is metadata about the program embedded in the program itself.
    • It can be parsed by the annotation parsing tool or by compiler.
    • We can also specify annotation availability to either compile time only or till runtime also.
    • Before java annotations, program metadata was available through java comments or by javadoc.
    • Annotation methods can’t have parameters.
    • Meta annotations in java - @Target, @Retention, @Documented, @Inherited.
    • Built in annotations in java - @Deprecated, @SupressWarnings, @Override.
  • How many times does garbage collector calls the finalize() method for object ?  
    • The garbage collector calls the finalize() method only once for an object.
  • Can the Garbage Collection be forced by any means ?  
    • No, its not possible. you cannot force garbage collection.
    • You can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.
  • Why java is not 100% Object Oriented ?  
    • Java supports Primitive datatype such as int, byte, long etc.
    • Hence Java is NOT 100% Object Oriented.
  • Difference between a break statement and a continue statement  
    • break statement terminates the current for/while loop OR switch case.
    • continue statement to terminate the current iteration and move to next iteration.
  • Difference between equals and ==  
    • equals is method while == is an operator.
    • equals is used for content comparison while == is used to compare that two objects refers to same memory location OR not.
  • Difference between Comparable and Comparator  
    • A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
    • A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
    • Comparable provides only one sort of sequence while the Comparator provides multiple sorts of sequences.
  • What is Java instanceOf operator ?  
    • The instanceof is used to compare the instance with type.
    • It returns either true or false.
    • If we apply the instanceof operator with variable that has a null value then it returns false.
  • What is Synchronization ?  
    • Synchronization makes only one thread to access a block of code at a time. If multiple thread accesses the block of code, then there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes.
    • The synchronized keyword means that a thread needs a key in order to access the synchronized code.
    • Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the thread can get the key to the objects lock.
  • What is the disadvantage of Synchronization ?  
    • Synchronization is not recommended to implement all the methods. Because if one thread accesses the synchronized code then the next thread should have to wait.
    • So it makes slow performance on the other end.
  • Difference between Inheritance and Composition  
    • Composition is HAS A relationship while inheritance is IS A relationship.
    • Example : Car has a Engine is composition and Car is a Vehicle is inheritance.
  • Difference between aggregation and composition  
    • Aggregation represents the weak relationship whereas composition represents the strong relationship.
    • For example, the bike has an indicator (aggregation), but the bike has an engine (composition).
  • What is Producer and Consumer problem ?  
    • Problem Statement
    • There are two processes, a producer and a consumer, that share a common buffer with a limited size. The producer “produces” data and stores it in the buffer, and the consumer “consumes” the data, removing it from the buffer. Having two processes that run in parallel, we need to make sure that the producer will not put new data in the buffer when the buffer is full and the consumer won’t try to remove data from the buffer if the buffer is empty.
    • Solution
    • For solving this concurrency problem, the producer and the consumer will have to communicate with each other. If the buffer is full, the producer will go to sleep and will wait to be notified. After the consumer will remove some data from the buffer, it will notify the producer, and then, the producer will start refilling the buffer again. The same process will happen if the buffer is empty, but in this case, the consumer will wait to be notified by the producer.
    • If this communication is not done properly, it can lead to a deadlock where both processes will wait for each other.
  • Difference between Serializable and Externalizable interface  
    • Serializable and Externalizable is that Serializable is a marker interface i.e. does not contain any method but Externalizable interface contains two methods writeExternal() and readExternal().
    • You can not do much to improve performance of default serialization process except reducing number of fields to be serialized by using transient and static keyword but with Externalizable interface you have full control over Serialization process.
    • Serializable uses reflection to construct object and does not require no arg constructor. But Externalizable demands public no-arg constructor.
Thank You...
  • Thank You...  
Reviews (0)