JAVA OOPs
JAVA OOPs
JAVA OOPs
Object Any entity which has state and behavior is known as an object. An object is defined as an
instance of a class.
Class Collection of objects is called class. It is a logical entity. A class can be defined as a blueprint
from which we can create a new object.
Inheritance When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. Code reusability. It is used to achieve runtime polymorphism.
Polymorphism If one task is performed in different ways. We use method overloading and
method overriding. One Interface, many implementations
Method overloading multiple methods having the same name but with different parameters –
Compile time Polymorphism
Method overriding declaring a method in child class which is already present in parent class –
Runtime Polymorphism
Abstraction Hiding internal details and showing functionality is known as abstraction. We use
abstract class and interface to achieve abstraction
The List, Set and Map interfaces are very important members of the Java Collections Framework. In
this post, we will point out major differences between them
1. Ordering
List represents an ordered sequence in Java whose elements are accessible by index.
Set represents a distinct collection of elements in Java which can be either ordered or unordered,
depending on the implementation. For example, HashSet implementation is unordered,
LinkedHashSet implementation is ordered, and TreeSet implementation is ordered by natural order
or by provided comparator.
Map represents mapping of key to values in Java. The ordering in Map is also implementation
specific. For example, TreeMap class is ordered while HashMap class is not.
2. Duplicates
Another notable difference between List, Set and Map interface is that a List can have duplicate
elements, a Set contains only distinct elements, and a Map doesn’t permit duplicate keys i.e. each
key can map to at most one value.
3. Null values
List allows any number of null values while a Set contains at most one null element. A Map typically
allows null as a key and value but some implementations prohibit null keys and values.
4. Implementing classes
Few of the most popular implementing classes of the List interface are ArrayList and LinkedList while
that of Set interface includes HashSet, TreeSet and LinkedHashSet. Map interface offers HashMap,
TreeMap, and LinkedHashMap classes.
A List can be used when insertion order of elements needs to maintained. A Set can be used if we
need to maintain a collection that contains no duplicates. And Map when data is key-value pairs and
need fast retrieval of value based on some key.
REST based architecture.
GET − Provides a read only access to a resource.
POST − Used to create a new resource.
DELETE − Used to remove a resource.
PUT − Used to update a existing resource or create a new resource.
What is Spring? Spring framework as “an application framework and inversion of control
container for the Java platform. This can be used for developing enterprise applications in java.
Bean in Spring Beans are objects that form the backbone of a Spring application. They are
managed by the Spring IoC container. In other words, a bean is an object that is instantiated,
assembled, and managed by a Spring IoC container.
DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring
bean configuration file and initializes all the beans that have been configured.
ContextLoaderListener, on the other hand, is the listener to start up and shut down the
WebApplicationContext in Spring root.
What is autowiring in Spring? Autowiring enables the programmer to inject the bean
automatically. We don’t need to write explicit injection logic. The code to inject bean using
dependency injection.
Controller Based: We can define exception handler methods in our controller classes. All we need is
to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler: Exception Handling is a cross-cutting concern and Spring provides
@ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation: For generic exceptions, most of the times we serve
static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement
to create global exception handler. The reason behind this additional way to define global exception
handler is that Spring framework also provides default implementation classes that we can define in
our spring bean configuration file to get spring framework exception handling benefits.
What are some of the important Spring annotations which you have used?
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very
important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as
response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type
is present.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around,
@Pointcut, etc.
Programmatic transaction management: In this, the transaction is managed with the help of
programming. It provides you extreme flexibility, but it is very difficult to maintain.
What is hibernate? Hibernate is Java-based ORM tool that provides a framework for mapping
application domain objects to the relational database tables and vice versa.
What are “class access modifiers”? restrict the scope of a class. Four types – default, public,
private, protected
Give me any three differences between “Truncate” and “Delete”.
Basic It is used to delete specific data It is used to delete the entire data of the table
Where clause We can use with where clause It can’t be used with where clause
Locking It locks the table row before deleting the row It locks the entire table
What do you understand by “access specifiers”? we use this in specifying the visibility of class,
fields, methods or how to give access
What is an abstract class and when do you use it? Abstract class: is a restricted class that cannot
be used to create objects (to access it, it must be inherited from another class). Java Abstract class is
used to provide common method implementation to all the subclasses or to provide default
implementation.
Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
What is the difference between UNIQUE and DISTINCT keywords in DBMS? Unique ensures that
all values in columns are different, Distinct helps to remove all duplicate records while retrieving the
records from table
How would you use Bubble Sort to sort the number of elements?
Exception handling
Try/Catch/Finally:
Throwable class is the root class which is extended by Exception & Error.
Throwable has a copy of execution stack.
The throwable has a list of methods which we can use while handling exception.
New − A new thread begins its life cycle in the new state.
Runnable − After a newly born thread is started, the thread becomes
runnable.
Waiting − Sometimes, when the thread waits for another thread to
perform a task, it enters waiting state.
Timed Waiting – A thread can enter the timed waiting state for a
specified time.
(Dead) − A runnable thread enters the terminated state when it completes
its task.
Thread Priorities
Creating a Thread
Thread Methods
start() isAlive()
run() join()
setName()
setPriority()
Static Method:
yield() - running thread will yield to any other threads of the same
priority that are waiting to be scheduled.
public static boolean holdsLock(Object x)
public static Thread currentThread()
public static void dumpStack()
Thread Synchronization
Interthread Communication
public void wait()
public void notify()
public void notifyAll()
Thread Deadlock
two or more threads are blocked forever, waiting for each other
Situation where threads need the same locks but obtain them in different
order.
because the synchronized keyword causes the executing thread to block
while waiting for the lock
With Runnable
With Callable:
The Callable interface is a generic interface containing a single call ()
method – which returns a generic value V:
The result of call () method is returned within a Future object:
- Generics
object whose internal state remains constant after it has been entirely
created. This means that once the object has been assigned to a variable,
we can neither update the reference nor mutate the internal state by any
means.
A mutable object can be changed after it's created, and an immutable
object can't.
In Java, everything (except for strings) is mutable by default:
There's no way to make existing objects immutable. Even if an object is
declared final, its fields can still be changed:
That said, if you're defining your own class, you can make its objects
immutable by making all fields final and private.
Strings are immutable in Java.
Any time you change a string, you're actually creating a new and separate
copy.
The key benefits of keeping this class as immutable are caching, security,
synchronization, and performance.
the JVM optimizes the amount of memory allocated for them by storing
only one copy of each literal String in the pool.
String Buffer:
StringBuffer in java is used to create modifiable String objects.
This means that we can use StringBuffer to append, reverse, replace,
concatenate and manipulate Strings
StringBuffer is much alike the String class, but with mutability features.
String Builder:
- Java 8 Features
Lambda expressions:
Method References:
forEach:
StringJoiner:
Collectors:
Stream API:
Stream Filter:
Data Structures:
List:
A List is an ordered Collection
Lists may contain duplicate elements.
Elements can be inserted or accessed by their position in the list, using a
zero-based index.
Arraylist:
it is based on an Array data structure
ArrayList is a resizable-array
permits all elements, including null.
ArrayList can dynamically grow and shrink
Why ArrayList is better than Array?
The limitation with array is that it has a fixed length so if it is full you
cannot add any more elements
likewise if there are number of elements gets removed from it the
memory consumption would be the same as it doesn’t shrink.
ArrayList can dynamically grow and shrink after addition and removal of
elements
LinkedList representation:
Each element in the LinkedList is called the Node. Each Node of the
LinkedList contains two items:
1) Content of the element
2) Pointer/Address/Reference to the Next Node in the LinkedList
Head of the LinkedList only contains the Address of the First element of
the List.
The Last element of the LinkedList contains null in the pointer part of the
node because it is the end of the List so it doesn’t point to anything
HashSet:
The underlying data structure for HashSet is Hash table.
HashSet stores the elements by using a mechanism called hashing.
HashSet contains unique elements only.
HashSet doesn't maintain the insertion order. Elements are inserted on the
basis of their hash code.
HashSet is the best approach for search operations.
The initial default capacity of HashSet is 16, and the load factor is 0.75.
Default initial capacity of the HashMap takes is 16 and load factor is 0.75f (i.e 75% of current map
size). The load factor represents at what level the HashMap capacity should be doubled. For example,
product of capacity and load factor as 16 * 0.75 = 12. This represents that after storing the 12th key –
value pair into the HashMap, its capacity becomes 32.
HashSet allows null value.
Before storing an Object, HashSet checks whether there is an existing
entry using hashCode() and equals() methods.
Time Complexity of HashSet Operations: The underlying data structure
for HashSet is hashtable. So amortize time complexity for add, remove
and look-up (contains method) operation of HashSet takes O(1) time.
TreeSet:
Underlying data Structure is self-balancing tree.
TreeSet implements the SortedSet interface. So, duplicate values are not
allowed.
TreeSet implements a NavigableSet interface.
The ordering of the elements is maintained by a set using their natural
ordering whether or not an explicit comparator is provided. Which means
objects in a TreeSet are stored in ascending order.
If we are depending on default natural sorting order, the objects that are
being inserted into the tree should be homogeneous and comparable.
TreeSet does not allow to insert Heterogeneous objects. It will throw a
classCastException at Runtime if we try to add heterogeneous objects.
TreeSet is basically an implementation of a self-balancing binary search
tree.
Therefore, operations like add, remove, and search take O(log(N)) time.
String class and all the Wrapper classes already implements Comparable interface but
StringBuffer class doesn’t implements Comparable interface. Hence, we get a
ClassCastException in the above example.
TreeSet serves as an excellent choice for storing large amounts of sorted information which
are supposed to be accessed quickly because of its faster access and retrieval time. The
insertion of null values into a TreeSet throws NullPointerException because while insertion of
null, it gets compared to the existing elements and null cannot be compared to any value.
Ordering
Elements in HashSet are not ordered. TreeSet maintains objects in Sorted order
defined by either Comparable or Comparator method in Java. TreeSet elements
are sorted in ascending order by default.
Null Object
HashSet allows null object. TreeSet doesn’t allow null Object and throw
NullPointerException, Because TreeSet uses compareTo() method to compare
keys and compareTo() will throw java.lang.NullPointerException.
Comparison
HashSet uses equals() method to compare two object in Set and for detecting
duplicates. TreeSet uses compareTo() method for same purpose.
If equals() and compareTo() are not consistent, i.e. for two equal object equals
should return true while compareTo() should return zero, than it will break
contract of Set interface and will allow duplicates in Set implementations like
TreeSet
LinkedHashSet:
The LinkedHashSet is an ordered version of HashSet that maintains a
doubly linked List across all elements.
When the iteration order is needed to be maintained this class is used.
When iterating through a HashSet the order is unpredictable, while a
LinkedHashSet lets us iterate through the elements in the order in which
they were inserted.
Contains unique elements only like HashSet. It extends the HashSet class
and implements the Set interface. Maintains insertion order.
Spring Bean:
A bean is an object that is instantiated, assembled, and otherwise managed by a
Spring IoC container.
Inversion of Control:
Inversion of Control is a principle in software engineering which transfers
the control of to a container or framework.
IoC enables a framework to take control of the flow of a program and
make calls to our custom code.
is a process in which an object defines its dependencies without creating
them
This object delegates the job of constructing dependencies to an IoC
container.
All we need to do is to provide the container with appropriate
configuration metadata.
Dependency Injection:
Dependency injection is a pattern we can use to implement IoC, where
the control being inverted is setting an object's dependencies.
injecting” objects into other objects, is done by an assembler
Cloud
- PCF / AWS / Azure / GCP / Private Cloud - Experienced? Services Offered by these platforms?
- API Gateway
- Actuators
- Sleuth
DB Handling
- Lazy Loading?
- Transactions
Quality / DevOps
- Code Coverage
- Security Scanning
- Automation Testing
Javascript Basics
- Functional Programming
- Asynchronous Programming
Angular:
Event Handling:
target event name = emplate statement to the right
<button (click)="onSave()">Save</button>
Custom events with EventEmitter:
ItemDetailComponent that presents item information
ItemDetailComponent has a delete button it doesn't contain the
functionality to delete the hero
It can only raise an event
// This component makes a request, but it can't actually delete a hero.
@Output() deleteRequest = new EventEmitter<Item>();
delete() {
this.deleteRequest.emit(this.item);
}
The hosting parent component binds to the deleteRequest
<app-item-detail(deleteRequest)="deleteItem($event)"
[item]="currentItem"></app-item-detail>
HTTP Requests:
the HttpClient service class in @angular/common/http
Use the HttpClient.get() method to fetch data from a server
The asynchronous method sends an HTTP request, and returns an
Observable that emits the requested data when the response is received
@OneToMany(fetch = FetchType.EAGER)
private List<Student> students;
}
one-to-many relationship:
@ComponentScan
@ComponentScan is used with the @Configuration annotation to allow
Spring to know the packages to scan for annotated components.
@ComponentScan is also used to specify base packages using
basePackageClasses or basePackage attributes to scan. If specific
packages are not defined, scanning will occur from the package of the
class that declares this annotation.
@Autowired
@Autowired is used to mark a dependency which Spring is going to
resolve and inject automatically. We can use this annotation with a
constructor, setter, or field injection.
@Component
@Component is used on classes to indicate a Spring component. The
@Component annotation marks the Java class as a bean or component so
that the component-scanning mechanism of Spring can add it into the
application context.
@Bean
@Bean is a method-level annotation and a direct analog of the XML
element. @Bean marks a factory method which instantiates a Spring bean.
Spring calls these methods when a new instance of the return type is
required.
@Qualifier
@Qualifier helps fine-tune annotation-based autowiring. There may be
scenarios when we create more than one bean of the same type and want
to wire only one of them with a property. This can be controlled using
@Qualifier annotation along with the @Autowired annotation.
We use @Qualifier along with @Autowired to provide the bean ID or bean
name we want to use in ambiguous situations.
@Primary
We use @Primary to give higher preference to a bean when there are
multiple beans of the same type. When a bean is not marked with
@Qualifier, a bean marked with @Primary will be served in case on
ambiquity.
@Required
The @Required annotation is method-level annotation, and shows that the
setter method must be configured to be dependency-injected with a value
at configuration time.
@Required on setter methods to mark dependencies we want to populate
through XML; Otherwise, BeanInitializationException will be thrown.
@Value
Spring @Value annotation is used to assign default values to variables and
method arguments. We can read spring environment variables as well as
system variables using @Value annotation.
We can use @Value for injecting property values into beans. It’s
compatible with the constructor, setter, and field injection.
@DependsOn
@DependsOn makes Spring initialize other beans before the annotated
one. Usually, this behavior is automatic, based on the explicit
dependencies between beans.
The @DependsOn annotation may be used on any class directly or
indirectly annotated with @Component or on methods annotated with
@Bean.
@Lazy
@Lazy makes beans to initialize lazily. By default, the Spring IoC container
creates and initializes all singleton beans at the time of application startup.
@Lazy annotation may be used on any class directly or indirectly
annotated with @Component or on methods annotated with @Bean.
@Lookup
A method annotated with @Lookup tells Spring to return an instance of the
method’s return type when we invoke it.
@Scope
@Scope is used to define the scope of a @Component class or a @Bean
definition. It can be either singleton, prototype, request, session,
globalSession or some custom scope.
@Profile
Beans marked with @Profile will be initialized in the container by Spring
only when that profile is active. By Default, all beans has “default” value as
Profile. We can configure the name of the profile with the value argument
of the annotation.
@Import
@Import allows to use specific @Configuration classes without component
scanning. We can provide those classes with @Import‘s value argument.
@ImportResource
@ImportResource allows to import XML configurations with this annotation.
We can specify the XML file locations with the locations argument, or with
its alias, the value argument.
@PropertySource
@PropertySource annotation provides a convenient and declarative
mechanism for adding a PropertySource to Spring’s Environment. To be
used in conjunction with @Configuration classes.
@Service
@Service marks a Java class that performs some service, such as
executing business logic, performing calculations, and calling external
APIs. This annotation is a specialized form of the @Component annotation
intended to be used in the service layer.
@Repository
This annotation is used on Java classes that directly access the database.
The @Repository annotation works as a marker for any class that fulfills
the role of repository or Data Access Object. This annotation has an
automatic translation feature. For example, when an exception occurs in
the @Repository, there is a handler for that exception and there is no need
to add a try-catch block.
@RequestMapping
@RequestMapping marks request handler methods inside @Controller
classes. It accepts below options:
path/name/value: which URL the method is mapped to.
method: compatible HTTP methods.
params: filters requests based on presence, absence, or value of HTTP
parameters.
headers: filters requests based on presence, absence, or value of HTTP
headers.
consumes: which media types the method can consume in the HTTP
request body.
produces: which media types the method can produce in the HTTP
response body.
@RequestBody
@RequestBody indicates a method parameter should be bound to the
body of the web request. It maps the body of the HTTP request to an
object. The body of the request is passed through an
HttpMessageConverter to resolve the method argument depending on the
content type of the request. The deserialization is automatic and depends
on the content type of the request.
@GetMapping
@GetMapping is used for mapping HTTP GET requests onto specific
handler methods.
Specifically, @GetMapping is a composed annotation that acts as a
shortcut for @RequestMapping(method = RequestMethod.GET).
@PostMapping
@PostMapping is used for mapping HTTP POST requests onto specific
handler methods.
Specifically, @PostMapping is a composed annotation that acts as a
shortcut for @RequestMapping(method = RequestMethod.POST).
@PutMapping
@PutMapping is used for mapping HTTP PUT requests onto specific
handler methods.
Specifically, @PutMapping is a composed annotation that acts as a
shortcut for @RequestMapping(method = RequestMethod.PUT).
@DeleteMapping
@DeleteMapping is used for mapping HTTP DELETE requests onto
specific handler methods.
Specifically, @DeleteMapping is a composed annotation that acts as a
shortcut for @RequestMapping(method = RequestMethod.DELETE).
@PatchMapping
@PatchMapping is used for mapping HTTP PATCH requests onto specific
handler methods.
Specifically, @PatchMapping is a composed annotation that acts as a
shortcut for @RequestMapping(method = RequestMethod.PATCH).
@ControllerAdvice
@ControllerAdvice is applied at the class level. For each controller, you
can use @ExceptionHandler on a method that will be called when a given
exception occurs. But this handles only those exceptions that occur within
the controller in which it is defined. To overcome this problem, you can
now use the @ControllerAdvice annotation. This annotation is used to
define @ExceptionHandler, @InitBinder, and @ModelAttribute methods
that apply to all @RequestMapping methods. Thus, if you define the
@ExceptionHandler annotation on a method in a @ControllerAdvice class,
it will be applied to all the controllers.
@ResponseBody
@ResponseBody on a request handler method tells Spring to converts the
return value and writes it to the HTTP response automatically. It tells
Spring to treat the result of the method as the response itself.
The @ResponseBody annotation tells a controller that the object returned
is automatically serialized into JSON and passed back into the
HttpResponse object. If we annotate a @Controller class with this
annotation, all request handler methods will use it.
@ExceptionHandler
@ExceptionHandler is used to declare a custom error handler method.
Spring calls this method when a request handler method throws any of the
specified exceptions.
The caught exception can be passed to the method as an argument.
@ResponseStatus
@ResponseStatus is used to specify the desired HTTP status of the
response if we annotate a request handler method with this annotation. We
can declare the status code with the code argument, or its alias, the value
argument.
@PathVariable
@PathVariable is used to indicates that a method argument is bound to a
URI template variable. We can specify the URI template with the
@RequestMapping annotation and bind a method argument to one of the
template parts with @PathVariable.
@RequestParam
@RequestParam indicates that a method parameter should be bound to a
web request parameter. We use @RequestParam for accessing HTTP
request parameters. With @RequestParam we can specify an injected
value when Spring finds no or empty value in the request. To achieve this,
we have to set the defaultValue argument.
@RestController
@RestController combines @Controller and @ResponseBody. By
annotating the controller class with @RestController annotation, we no
longer need to add @ResponseBody to all the request mapping methods.
@ModelAttribute
@ModelAttribute is used to access elements that are already in the model
of an MVC @Controller, by providing the model key.
@CrossOrigin
@CrossOrigin enables cross-domain communication for the annotated
request handler methods. If we mark a class with it, it applies to all request
handler methods in it. We can fine-tune CORS behavior with this
annotation’s arguments.
@InitBinder
@InitBinder is a method-level annotation that plays the role of identifying
the methods that initialize the WebDataBinder — a DataBinder that binds
the request parameter to Java Bean objects. To customize request
parameter data binding, you can use @InitBinder annotated methods
within our controller. The methods annotated with @InitBinder include all
argument types that handler methods support.
The @InitBinder annotated methods will get called for each HTTP request
if we don’t specify the value element of this annotation. The value element
can be a single or multiple form names or request parameters that the init
binder method is applied to.
@EnableAutoConfiguration
@EnableAutoConfiguration tells Spring Boot to look for auto-configuration
beans on its classpath and automatically applies them. It tells Spring Boot
to “guess” how you want to configure Spring based on the jar
dependencies that you have added.
Since spring-boot-starter-web dependency added to classpath leads to
configure Tomcat and Spring MVC, the auto-configuration assumes that
you are developing a web application and sets up Spring accordingly. This
annotation is used with @Configuration.
@ConditionalOnProperty
@ConditionalOnProperty annotation lets configuration be included based
on a Spring Environment property i.e. make conditions on the values of
properties.
@ConditionalOnResource
@ConditionalOnResource annotation lets configuration be included only
when a specific resource is present.
@ConditionalOnWebApplication and
@ConditionalOnNotWebApplication
@ConditionalOnWebApplication and @ConditionalOnNotWebApplication
annotations let configuration be included depending on whether the
application is a “web application”. A web application is an application that
uses a spring WebApplicationContext, defines a session scope, or has a
StandardServletEnvironment.
@ConditionalExpression
@ConditionalExpression is used in more complex situations. Spring will
use the marked definition when the SpEL expression is evaluated to true.
@Conditional
@Conditional is used in complex conditions, we can create a class
evaluating the custom condition.