JAVA Interview Questions
What is OOPs?
OOPs (Object-Oriented Programming) is a type of programming which is based on objects rather than just functions and procedures.
Why use OOPs?
OOPs allows clarity in programming.
Code can be reused through inheritance
Data and code are bound together by encapsulation
OOPs allows data hiding, therefore, private data is kept confidential
Problems can be divided into different parts making it simple to solve
The concept of polymorphism gives flexibility to the program by allowing the entities to have multiple forms
What are the main features of OOPs?
Inheritance
Encapsulation
Polymorphism
Data Abstraction
Inheritance is a feature of OOPs which allows classes inherit common properties from other classes.
Polymorphism refers to the ability to exist in multiple forms. Multiple definitions can be given to a single interface.
Method overloading is a feature of OOPs which makes it possible to give the same name to more than one methods within a class if the arguments passed differ.
Method overriding is a feature of OOPs by which the child class or the subclass can redefine methods present in the base class or parent class.
Overloading: Two or more methods having the same name but different parameters or signature. Resolved during compile-time
Overriding: Child class redefining methods present in the base class with the same parameters/Signature. Resolved during runtime
Encapsulation refers to binding the data and the code that works on that together in a single unit.
Data abstraction is a very important feature of OOPs that allows displaying only the important information and hiding the implementation details.
Can you create an instance of an abstract class? No.
Data abstraction: Solves the problem at the design level. Allows showing important aspects while hiding implementation details
Encapsulation: Solves the problem at the implementation level. Binds code and data together into a single unit and hides it from the world
How you will design a class to be used as key?
The contract between hashCode() and equals()
The very basic need for designing a good key is that “we should be able to retrieve the value object back from the map without failure“,
Make HashMap key object immutable.
How to Synchronize HashMap in Java?
1) Synchronize HashMap – ConcurrentHashMap
2) Synchronize HashMap – Collections.synchronizedMap()
Difference between Synchronized HashMap and ConcurrentHashMap
1) Multiple threads can add/remove key-value pairs from ConcurrentHashMap, while only one thread is allowed to make change in case of SynchronizedHashMap. This results higher degree of concurrency in ConcurrentHashMap.
2) A lock is required for read operation too in SynchronizedHashMap.No need to lock the map to read a value in ConcurrentHashMap
3) ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it
what is ConcurrentModificationException?
Java Collection classes are fail-fast, which means if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException.
How To Avoid ConcurrentModificationException in multi-threaded environment?
You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.
You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.
If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. This is the recommended approach to avoid concurrent modification exception.
Java 8 features?
Java 8 Features
Some of the important Java 8 features are;
forEach() method in Iterable interface
default and static methods in Interfaces
Functional Interfaces and Lambda Expressions
Java Stream API for Bulk Data Operations on Collections
Java Time API
Collection API improvements
Concurrency API improvements
Java IO improvements
Miscellaneous Core API improvements
What is Lambda Expression?
functional programming in the java object oriented world.
1. Reduced Lines of Code
2. Sequential and Parallel Execution Support
3. Passing Behaviors into methods
4. Higher Efficiency with Laziness
Java String?
create String Using string literal or Using new keyword.
String Immutability Benefits:a) String Constant Pool, hence saves memory.b) Security as it’s can’t be changed.
c)Thread safe d)Class Loading security
How to make class immutable?
1)The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
2)The class is final so we cannot create the subclass.
3)There is no setter methods i.e. we have no option to change the value of the instance variable.
Difference between StringBuffer and StringBuilder?
StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
What is enum?
Enum was introduced in Java 1.5 as a new type whose fields consists of a fixed set of constants.
Diff between Java Enum vs Constants?
1)We can pass any int constant to the simpleConstantsExample method but we can pass only fixed values to simpleEnumExample, so it provides type safety.
2)We can change the int constants value in ThreadStatesConstant class but the above program will not throw any exception. Our program might not work as expected but if we change the enum constants, we will get compile time error that removes any possibility of runtime issues.
Java Enum Important Points
Below are some of the important points for Enums in Java.
All java enum implicitly extends java.lang.Enum class that extends Object class and implements Serializable and Comparable interfaces. So we can’t extend any class in enum.
Since enum is a keyword, we can’t end package name with it, for example com.journaldev.enum is not a valid package name.
Enum can implement interfaces. As in above enum example, it’s implementing Closeable interface.
Enum constructors are always private.
We can’t create instance of enum using new operator.
We can declare abstract methods in java enum, then all the enum fields must implement the abstract method. In above example getDetail() is the abstract method and all the enum fields have implemented it.
We can define a method in enum and enum fields can override them too. For example, toString() method is defined in enum and enum field START has overridden it.
Java enum fields has namespace, we can use enum field only with class name like ThreadStates.START
Enums can be used in switch statement, we will see it in action in the later part of this tutorial.
We can extend existing enum without breaking any existing functionality. For example, we can add a new field NEW in ThreadStates enum without impacting any existing functionality.
Since enum fields are constants, java best practice is to write them in block letters and underscore for spaces. For example EAST, WEST, EAST_DIRECTION etc.
Enum constants are implicitly static and final
Enum constants are final but it’s variable can still be changed. For example, we can use setPriority() method to change the priority of enum constants. We will see it in usage in below example.
Since enum constants are final, we can safely compare them using “==” and equals() methods. Both will have the same result.
Exception handling in java?
Exception is an error event that can happen during the execution of a program and disrupts its normal flow.
Java being an object oriented programming language, whenever an error occurs while executing a statement, creates an exception object and then the normal flow of the program halts and JRE tries to find someone that can handle the raised exception.
Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.
Error: Errors are exceptional scenarios that are out of scope of applicationfor example hardware failure, JVM crash or out of memory error. OutOfMemoryError, StackOverflowError
Checked-Excption:We should catch this exception and provide useful message. FileNotFoundException
unchecked-Exception:Runtime Exceptions are cause by bad programming. ArrayIndexOutOfBoundException
* Java 7 Automatic Resource Management and Catch block improvements
Steps to write custom exceptions?
1. Create a new class whose name should end with Exception like ClassNameException
2. Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class.
3. Create a constructor with a String parameter which is the detail message of the exception.
What is Java collection?
A collection is an in-memory data structure to hold values.
Java Stream is a data structure that is computed on-demand.
We can use Java Stream API to implement internal iteration.
1. Java Stream doesn’t store data, it operates on the source data structure (collection and array) and produce pipelined data that we can use and perform specific operations.
2. Java Stream operations use functional interfaces, that makes it a very good fit for functional programming using lambda expression
3. Java 8 Stream internal iteration principle helps in achieving lazy-seeking in some of the stream operations.
4. Java Streams are consumable, so there is no way to create a reference to stream for future usage.
5. Java 8 Stream support sequential as well as parallel processing, parallel processing can be very helpful in achieving high performance for large collections.
6. All the Java Stream API interfaces and classes are in the java.util.stream package.
Internal iteration provides several features such as sequential and parallel execution, filtering based on the given criteria, mapping etc.
Most of the Java 8 Stream API method arguments are functional interfaces, so lambda expressions work very well with them.
Functional Interfaces in Java8?
1. Function and BiFunction: Function represents a function that takes one type of argument and returns another type of argument. Function<T, R> is the generic form where T is the type of the input to the function and R is the type of the result of the function. example map(),toArray(), reduce(),flatmapToInt()
2. Predicate and BiPredicate: It represents a predicate against which elements of the stream are tested. This is used to filter elements from the java stream. Just like Function, there are primitive specific interfaces for int, long and double. example anyMatch(), allMatch()
3. Consumer and BiConsumer: It represents an operation that accepts a single input argument and returns no result. It can be used to perform some action on all the elements of the java stream. example forEach()
4. Supplier: Supplier represent an operation through which we can generate new values in the stream. example collect()
Concurrency in Java:
What Is the Difference Between a Process and a Thread?
Both processes and threads are units of concurrency, but they have a fundamental difference: processes do not share a common memory, while threads do
a process is an independent piece of software that runs in its own virtual memory space, thread share memory.
Describe the Different States of a Thread and When Do the State Transitions Occur.
New Runnable Blocked waiting timed_waiting terminated.
Difference Between the Runnable and Callable Interfaces?
The Runnable interface has a single run method.The Runnable interface does not allow this method to return value or to throw unchecked exceptions.
The Callable interface has a single call method and represents a task that has a value. Callable is generally used in ExecutorService instances to start an asynchronous task and then call the returned Future instance to get its value.
What Is the Thread’s Interrupt Flag? How Can You Set and Check It? How Does It Relate to the Interruptedexception?
If a thread is currently inside one of the methods that throw InterruptedException (wait, join, sleep etc.), then this method immediately throws InterruptedException.
What Are Executor and Executorservice?
What Are the Differences Between These Interfaces?
Interfaces of java.util.concurrent framework. Executor is a very simple interface with a single execute method accepting Runnable instances for execution.
ExecutorService extends the Executor interface with multiple methods for handling and checking the lifecycle of a concurrent task execution service (termination of tasks in case of shutdown) and methods for more complex asynchronous task handling including Futures.
Available Implementations of Executorservice in the Standard Library?
The ExecutorService interface has three standard implementations:
ThreadPoolExecutor — for executing tasks using a pool of threads. Once a thread is finished executing the task, it goes back into the pool. If all threads in the pool are busy, then the task has to wait for its turn.
ScheduledThreadPoolExecutor allows to schedule task execution instead of running it immediately when a thread is available. It can also schedule tasks with fixed rate or fixed delay.
ForkJoinPool is a special ExecutorService for dealing with recursive algorithms tasks. If you use a regular ThreadPoolExecutor for a recursive algorithm, you will quickly find all your threads are busy waiting for the lower levels of recursion to finish. The ForkJoinPool implements the so-called work-stealing algorithm that allows it to use available threads more efficiently.
What Is a Volatile Field and What Guarantees Does the Jmm Hold for Such Field?
A read of a volatile variable is guaranteed to observe the last write to this variable.
Another guarantee for volatile is atomicity of writing and reading 64-bit values (long and double). Without a volatile modifier,
If Two Threads Call a Synchronized Method on Different Object Instances Simultaneously, Could One of These Threads Block? What If the Method Is Static?
No, Two threads calling the method on different instances acquire different monitors, so none of them gets blocked.
If the method is static, then the monitor is the Class object. For both threads, the monitor is the same, so one of them will probably block and wait for another to exit the synchronized method.
What Is the Purpose of the Wait, Notify and Notifyall Methods of the Object Class?
A thread that owns the object's monitor (for instance, a thread that has entered a synchronized section guarded by the object) may call object.wait() to temporarily release the monitor and give other threads a chance to acquire the monitor.
Spring interview QA: https://www.edureka.co/blog/interview-questions/spring-interview-questions/
Springboot: https://www.edureka.co/blog/interview-questions/spring-boot-interview-questions/
Spring cloud: https://www.javainuse.com/spring/spring-cloud-interview-questions
Comments
Post a Comment