Java Questions
Java Questions
The class must be declared as final (So that child classes can’t be created)
Data members in the class must be declared as private (So that direct access is not
allowed)
Data members in the class must be declared as final (So that we can’t change the
value of it after object creation)
A parametrized constructor should initialize all the fields performing a deep copy
(So that data members can’t be modified with object reference)
Deep Copy of objects should be performed in the getter methods (To return a copy
rather than returning the actual object reference)
No setters (To not have the option to change the value of the instance variable)
//fields as final
//wrapper classes and strings are immutable so it's okay if we add getter
private final Integer field1;
//only provide getters as setter can set some value and modify it
by default all the wrapper classes has overridden hash code and equals method
if we don't have then we can override them
firstly it will check the hascode if both are same then it will go to equals method
if content is same then it will return same
when we put some value in hashmap then it will generate some hashcode and it will
be store in an index by calculating hashcode & n-1
n =16 that will be put in that index
default size is 16
if we have more elements in it as soon as it reaches 13th elements then size will
be doubled 2 power n-1
if two inputs get same index then it will form a linked list
-----------------------------------------------------
singleton class
1. Enumeration
2. Iterator
3. List Iterator
iterator can traverse only in forward direction .iterator is the only method,
applies both on list and set, cannot add elements,
list iterator can travel in both the directions and works on list objects only
Multi Threading
-------------------------------------------
Thread - sub process
Thread states
new runnable running blocked/waiting terminated/dead
priority states
default -5 (1 to 10)
thread.setpriority()
executive service
excutive service is the new way of executing the thread asyncronously in the
backgroud similarly like thread pool
different ways of creating executive service
ExecutiveService e1 = Executors.newSingleThreadExecutor();
new fixedThreadPool(how many threads);
new scheduledThreadPool(how much time to delay);
with the help of executor service we can actually check whether thread is executed
or not by using Furture
runnable vs callable
runnable will return void if we want to return some value use callable and use call
method
synchronization
when there are multiple threads want to execute a method can execute it only if it
is not getting executed by oter threads
Synchnized is used on method for safe execution of method
if we have multiple treads running if we want 4th thread to run after 3rd one then
t3.start()
t3.join
t4.start
SOAP VS REST-
----------------------------------------------
SIMPLE OBJECT ACCESS protocal
REPRESENTATIVE STATE TRANSFER
spring boot has everything configured in it we don't need to add anything extra and
focus on coding part (jars and configuration is a big deal) so concept of spring
boot
it has internal tomcat server installed in the system
we can configure everything in application.properties file
Presentation Layer, Data Access Layer, Service Layer, and Integration Layer.
spring mvc
when client sends a request it will go to web.xml and then will go to dispatcher
servlet provided by spring mvc and then it send it respective controller based on
@controller annotation
dependecy injection
---------------------------------------------------
one object may depend on some other object
dependecy injection container to create objects
advantage is loose coupling why bcz we can test that particular object don't need
to depend on other object
@Autowired, @Component
comparator
comapare
equals
util pkg
customised order
Class Loader
------------------
it is used to load the .class files
there are 3 different types of class loaders
bootstrap-also known as primordial class loader, it doesn't have any parent class
extension-it delegated classes from it's parent class if its unsuccessful t will
load from specified directory.
application classloader-is used to load classes from classpath
List
------------------------
Array List
Linked List
Set
-----------------
Hash Set
Linked hash set
JAVA8-feature
----------------------------------
Lambda expression
------------------------------
lambda expressions are one of the feature implemented by java 8, it is an anonymous
method which does not have any name and uses the abstract method of FI and it
provide some of the imp methods like map, filter and foreach. So because of that
there is code optimzation and this lambda expressions can be written inside an
another method.
Method Reference
---------------------------
it is similar to the lamba and easy way of using lambda expression. it is used to
refer the method in the functional interface using the symbol (::)
Funcational Interface
---------------------------------
An interface which can have single abstract method and can have multiple static and
default methods are called FI.These are also called as simple abstact method
Interface(sam Iterface).
Streams
-----------------------------
Strems doesn't store any kind of data and it is just used to tranfer data from
particular source through a pipeline and it will not modify the source data for
example if we are filtering based on some condition it will just create a new list
rather than modifying the existing list.
default methods
------------------------------
we can create a method with default implementation using default keyword. methods
which are defined as default methods are not abstract methods. we can also override
default methods to provide more specific implementation.
In the same way we can create static methods also inside interface with some
implemention
after seeing this interface it is similar to abstract method the only difference is
for abstract class we can create a constructor.
foreach method
-----------------------------
this method is used to iterate through the elements and any collection which is
extending iterable interface can use this method and it's return type is void
optional
------------------------------------
optional is used to avoid null pointer exception. if there is any exeption in the
middle, in order to not to terminate in the middle we use optional if we don't have
any value it will not retrun any thing if we have value it wil return that value.
we can check for the element by using isPresent method then we can perform the
operation.
default and static methods both have implementations but default methods can be
overridden and can be accessed by class but static methods cannot be overridden and
can be accessed using interface name.
difference between collections and streams is collections can store the data but
streams is just to transform the data from one source to another.
Hibernate
------------------------
In order to save our data into db we use hibernate which provides Object relational
mapping(ORM) feature which will internally use JDBC api's to connect with the DB
and it provides a specification called JPA(java persistence api) which is used to
store the data into DB.
Equals() method
-------------------------------
equals method is used to compare the two object it will check whether two objects
are equal or not based on the reference if two objects are sharing the common
memory reference then it returns true
hashcode
-----------------------------------
for each object jvm creates an unique id which of 32 bits that is called hashcode.
when we overide equals method then it is important to override hashcode method also
oops concepts
------------------------------------
Abstraction --
representing the complex things in simple way
eg: switching on TV
it's not required to know how it internally works
encapsulation:
wrapping the data into a single unit
eg:capsule
inheritance:
acquiring the properties of parent class
provides code re usability and run time polymorphism
eg:property
== method compares the references of the objects and equals method checks the
content of the method
when we override equals method inside we will write == method which compares
references of objects.
so fistly we should override hashcode to return single integer if hashcodes are
same then == returns true
custome annotations
-----------------------------------
docker
---------------------------
docker is an open platform to develop and run our applications. It actually frees
us from the infrastructure dependency and make us to develop the application fast.
Using docker we can create containers,
what is a container?
In VM we need to install new OS when we have to run a application so if we have
multiple application which are having different OS then we need to install all, So
we have the concept of docker where we will be installing it then we have
containers in it which will share the same OS
containers can be created using image and we can create an image with the software
we have developed and all the jars and any other os features, with all these we
can create an image and can share it.
Imp points
-------------------
we can't declare constructor as static and final we can inherit super class
constructor and we can use super key word
we can't use super keyword inside static methods
Collections
iterable
collection
list,queue,set
access modifiers
------------------------------
public:any where
private:only in that class
protected:with in the package and in the package of sub class
default:only with in the package
if we want to create a mutable string then we can use string buffer or string
builder.
String buffer is synchronized means if two threads wants to access same method then
it can't be done becuase of that it is slow which makes it less efficient.
string builder is not synchronized and is more efficient.
if you doesn't care about any thread safety we can go for string builder.
-------------------------------------
api is just to make the contract between the information provider and information
user
rest api's are used to create restful web services and has certain constraints to
create RWS.they use simple methods like get,post,put,delete,patch.
restful web services? web services that are formed using rest architecture
why it is distribute is
kafka stands between the producer and consumer
kafka system is called kafka cluster and consists of multiple elements called
nodes.
brokers run inside nodes so it is a distrited system.
data produced from producer is ditributed among the nodes so if any of the cluster
is down it won't loose the data
why do we need kafka?
we can use kafka for fault tolerance that means it can store the data for the give
time period default 7days unlike rabbitMQ
kafka is distributed so when ever it's required we can increase the kafka cluster
just by adding server to kafka cluster.
kafka has low latency which makes it process the data fast.
zookeeper is must for kafka is used to maintain the brokers and if any of the
broker or partition is down it notifies the kafka and if any cluster is added then
also notified kafka
---------------------------------------------------------------
Exceptions?
it is an abnormal condition
exception handling is nothing but to handle run time exceptions
throwable
exception error (STACK OVERFLOW, OUT OF MEMEMORY, VM
ERROR)
IOEXCEPTION
FILE NOT FOUND
SQL Exceptions
CLASS NOT FOUND
RUN TIME Exceptions
NPE
NUMBER FORMAT
ARTHIMATIC
we can have a try block without catch and finally block after java 7, (try using
resource)only constraint is the parameter we are passing to tryblock should
implement autocloseable interface
example:
------------------------------------------------------
types of injections
1.constructor based
class sample {
private Coach coach;
public Sample(Coach coach) {
coach = coach;
}
}
2.setter based
class sample {
private Coach coach;
public sample() {
}
setCoach(Coach coach) {
coach = coach;
}
}
3.field based
class sample {
@Autowired
private Coach coach;
public sample() {
}
}
bean scope
-------------------------
<bean id = "sample" class = "fully qualified class path">
</bean>
so spring will create the object for it and store it in memory and when ever any
other container request for this bean it will share the same reference
basically it's a singleton
we can explicitly specify the bean scope by
<bean id = "sample"
class = "fully qualified class path" scope = "singleton>
</bean>
bean lifecycle
|
container start -> bean instantiated -> DI -> customer init method ->custom
utility method -> custom destroy method
@Configuration
it is annotated on a class and contains methods with are annotated with @Bean and
it tells spring IOC that there might be beans which should be configured in
applicationContext
@Bean
return the object which means it should be registered as a bean in application
context
@EnableAutoConfiguration
it tells spring container to create application context without manually creating
@Component
during @Componentscan spring will instantiate such beans and injects any beans
which are required
@RestController- @Controller+@ResponseBody
web application is the general view of HTML+css+JS where rest api returns json or
xml
microservices
--------------
service discovery
---------------------
CSD
here client will query the service registry where the location of services are
avialable then uses any available service to make request
netflix provide eureka registry where it exposes the api's to know what services
are avialble
also netflix ribbon
SSD:here when client makes a request it goes to load balacer here load balancer
calls service registry then service registry routes the request to the avaiable
service.
Threads in java
---------------------------------
multi threads
name itself suggests that multiple threads
In this case multiple threads run simultaneously by sharing common resource to make
the program execution fast, it is one of the important feature provided by java.
uses:
1.improves performance
2.uses cpu effectively and reduce cost of maintenance.
3.threads are independent so one thread will not effect other if there is any
exception.
Employee e = Employee.class.newInstance();
Constructor<Employee> c = Employee.class.getInstance();
Employee e1 = c.newInstance();
4.clone() method
@Override
protected Object clone() throws CloneNotFoundException{
return super.clone();
}
@RequestMapping
-------------------------------
It is used to map the incoming request to the specific class or method
when the application starts all the beans are stored in application context, when
the @Controller bean is intialized then it searched for request mapping and store
the mapping/ handler pair in mapping registry. When the http request comes to
dispatcherservlet it searches in application context for the beans which implement
requestmappinghandlermapping and it will internally searches in mapping registry
and solves the request.
@RequestBody
---------------------------
sample(@RequestBody Employee e)
@ResponseBody
-------------------
object sent is automatically serialized to json
serialization
----------------------
process of converting data into a byte streams
deserialization
-------------------------------
it is the process of converting back to the java object
ci: using various built in tools and pluging when the code is commited it does
build and unit testing and integration testing
cd: it is used for deploying the code into the production. the goal is the code
should always in develiverable state irrespective of the number of developers doing
the code changes.
jenkins
-----------------------
jenkins is an application used to build, test and deploy the application during the
development. it is used to achieve continuous integration.
continuos integration:
when ever small piece of code is developed and build is done and deploy to any env
to developement is fast and identify bugs at the early stage rather than waiting
for everybody to develop the code and test it once and fix errors if there are any.
jenkins pipeline
----------------------------
It is a series of tasks performed in a specific sequesce like build test deploy on
code to form a software product.
api gateway:
it is used to enroute the client requests to desired services
concurrenthashmap:
--------------------------------
in concurrentHashmap multiple threads can operate at a time. multiple threads can
read the operation and retrieval without locking but for updating it uses lock at
segment level.
kong
-------------------------------
request which is coming will come to load balancer and then it routes to kong from
kong it go to microservices
each consumer has unique name and unique key called api key and jwt for
authentication.
all this information is there in vault.
collections are not thread safe, multiple threads perform action at a time, but
concurrent collections are thread safe
we can make collections also thread safe using synchronized. but because of locking
performance wise it becomes slow.
hashmap - concurrent hashmap.
list - copyonwritearraylist
set - copyonwritearrayset