Final Interview Questions
Final Interview Questions
com/ashokitschool/ashokit_weekend_workshops
JVM (Java Virtual Machine) Architecture
JVM (Java Virtual Machine) is an abstract machine. It is a specification that
provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).
What is JVM
It is:
JIT:
The Just-In-Time (JIT) compiler is a component of the Java™ Runtime Environment
that improves the performance of Java applications at run time. Java programs
consists of classes, which contain platform-neutral bytecodes that can be
interpreted by a JVM on many different computer architectures.
static : means direct access to JVM but with out object creation
void : means function will not return any thing (means main function will not
return anything)
main : function is the callable environment to the java program (BY using main
function we can call the user defined and predefined methods )
enum in java
In Java, Enumerations or Java Enum serve the purpose of representing a group of
named constants in a programming language
1. what is abstaction
Hide internal implementation and just highlight the set of services, is called
abstraction. By using abstract classes and interfaces we can implement abstraction.
Example :
By using ATM GUI screen bank people are highlighting the set of services what they
are offering without highlighting internal implementation.
The main advantages of Abstraction are:
1. We can achieve security as we are not highlighting our internal implementation.
(i.e., outside person doesn't aware our internal implementation.)
2. Enhancement will become very easy because without effecting end user we can able
to perform any type of changes in our internal system.
3. It provides more flexibility to the end user to use system very easily.
4. It improves maintainability of the application.
5. It improves modularity of the application.
6. It improves easyness to use our system.
By using interfaces (GUI screens) we can implement abstraction.
2. what is encapsulation
Binding of data and corresponding methods into a single unit is called
Encapsulation .
If any java class follows data hiding and abstraction such type of class is said to
be encapsulated class.
Encapsulation=Datahiding+Abstraction
Every data member should be declared as private and for every member we have to
maintain getter & Setter methods.
The main disadvantage of encapsulation is it increases length of the code and slows
down execution.
Difference between Abstraction and Encapsulation:
Abstraction:
1.Abstraction focus is on “what” should be done.
2.Abstraction provides access to specific part of data.
3.We can implement abstraction using abstract class and interfaces.
4.Abstraction is the method of hiding the unwanted information.
Encapsulation:
1.Whereas encapsulation is a method to hide the data in a single entity or unit
along with a method to protect information from outside.
2.Whereas encapsulation can be implemented using by access modifier i.e. private,
protected and public.
3.Encapsulation focus is on “How” it should be done.
4.Encapsulation hides data and the user can not access same directly (data hiding.
3. what is Inheretence
IS-A Relationship(inheritance) :
1. Also known as inheritance.
2. By using "extends" keywords we can implement IS-A relationship.
3. The main advantage of IS-A relationship is reusability.
Example:
class Parent {
public void methodOne(){ }
}
class Child extends Parent {
public void methodTwo() { }
}
Conclusion :
1. Whatever the parent has by default available to the child but whatever the child
has by default not available to the parent. Hence on the child reference we can
call both parent and child class methods. But on the parent reference we can call
only methods available in the parent class and we can't call child specific
methods.
2. Parent class reference can be used to hold child class object but by using that
reference we can call only methods available in parent class and child specific
methods we can't call.
3. Child class reference cannot be used to hold parent class object.
Example:
The common methods which are required for housing loan, vehicle loan, personal loan
and education loan we can define into a separate class in parent class loan.
So that automatically these methods are available to every child loan class.
Example:
class Loan {
//common methods which are required for any type of loan.
}
class HousingLoan extends Loan {
//Housing loan specific methods.
}
class EducationLoan extends Loan {
//Education Loan specific methods.
}
For all java classes the most commonly required functionality is define inside
object class hence object class acts as a root for all java classes.
For all java exceptions and errors the most common required functionality defines
inside Throwable class hence Throwable class acts as a root for exception
hierarchy.
--In how many ways we can implement inheretance in java?
single inheritance : one class is extending another class
multi-level Inheritance
multiple Inheritance is not supported in java (directely it is not supported but
indirectely it is supported )
--when we extend a thread class what all method we override and where the thread
starts
after extending the thread class we have to override a method called run method and
after overriding the run method we can provide them our own logic in that method
and we do not have to call directely the run method we can call the thread to start
by the dot .start() method
#################
htpp methods
#################
get
put
post ->post is something is when ever we create a new resource we use post but
lets say you are having already created a resource whether it doesn't matter its in
database or whether you are using some kind
delete
########################
--Java8 features
########################
lambda expressions
The Main Objective of λLambda Expression is to bring benefits of functional
programming into java.
Streams in java 8
Why do we use stream?
You can use stream to filter, collect, print, and convert from one data structure
to other etc. In those cases, we have apply various operations with the help of
stream.
Java StringJoiner
Java added a new final class StringJoiner in java.util package. It is used to
construct a sequence of characters separated by a delimiter. Now, you can create
string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix
and suffix to the char sequence.
Functional Interface
default and static method date time api ,stream api and other predefined functional
interfaces like predicate function and consumer
function: It takes a single parameter and returns result by calling the apply()
method.
BiFunction:While the BiFunction interface is also a pre-defined functional
interface that takes two parameters and returns a result.
spring security
---------------------------
i have implemented authencation and authorization
In authentication we are checking the credentials for the user and we are using the
access token and jwt part is used in our project which we have implemented
Comparator
1)The Comparator provides multiple sorting sequences. In other words, we can sort
the collection on the basis of multiple elements such as id, name, and price etc
2)Comparator doesn't affect the original class, i.e., the actual class is not
modified.
3)Comparator provides compare() method to sort elements.
4)A Comparator is present in the java.util package.
runtime exception and its child classes are checked exception and error and its
child classes are unchecked exception
polymorphism
method overloading and method overriding
what is interface
##############
main()
##############
1.can main method be overloaded in java
Yes, you can overload main method in Java. But the program doesn't execute the
overloaded main method when you run your program, you have to call the overloaded
main method from the actual main method.
We know that anyone can access/invoke a method having public access specifier. The
main() method is public in Java because it has to be invoked by the JVM. So, if
main() is not public in Java, the JVM won’t call it.
8.Can the main() method take an argument other than String array?
No, an argument of the main() method must be a String array. But, from the
introduction of var args, you can pass var args of string type as an argument to
the main() method. Again, var args are nothing but the arrays.
final:---
final is the modifier applicable for classes, methods and variables.
If a class declared as the final then child class creation is not possible.
If a method declared as the final then overriding of that method is not possible.
If a variable declared as the final then reassignment is not possible.
finally:---
finally is the block always associated with try-catch to maintain clean up code
which should be executed always irrespective of whether exception raised or not
raised and whether handled or not handled.
finalize():---
finalize is a method, always invoked by Garbage Collector just before destroying
an object to perform cleanup activities.
Note:
1. finally block meant for cleanup activities related to try block where as
finalize() method meant for cleanup activities related to object.
2. To maintain clean up code finally block is recommended over finalize() method
because we can't expect exact behavior of GC.
--> this() is used to invoke a constructor of the same class. super() is used to
invoke a superclass constructor
#############################
Exception Handling In REST API
#############################
Exceptions and errors both are subclasses of Throwable class. The error indicates a
problem that mainly occurs due to the lack of system resources and our application
should not catch these types of problems. Some of the examples of errors are system
crash error and out of memory error.
Errors mostly occur at runtime that's they belong to an unchecked type.
Exceptions are the problems which can occur at runtime and compile time. It mainly
occurs in the code written by the developers. Exceptions are divided into two
categories such as checked exceptions and unchecked exceptions.
-> To achieve graceful termination of the program we need to handle the exception
###########
String
###########
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance
is returned.
If the string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Note: String objects are stored in a special memory area known as the "string
constant pool".
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM
will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to
the object in a heap (non-pool).
StringBuffer is synchronized i.e. thread safe. It means two threads can't call the
methods of StringBuffer simultaneously.StringBuffer is less efficient than
StringBuilder.
Comparable:
Comparable provides a single sorting sequence. In other words, we can sort the
collection on the basis of a single element such as id, name, and price.Comparable
provides compareTo() method to sort elements.Comparable is present in java.lang
package.We can sort the list elements of Comparable type by Collections.sort(List)
method.
Comparator
The Comparator provides multiple sorting sequences. In other words, we can sort
the collection on the basis of multiple elements such as id, name, and price etc
Comparator doesn't affect the original class, i.e., the actual class is not
modified.Comparator provides compare() method to sort elements.A Comparator is
present in the java.util package.
We can sort the list elements of Comparator type by Collections.sort(List,
Comparator) method.
public class A
{
String str="hello";
public static void main(String args[])
{
A obj=new A(); //creating object using new keyword
System.out.println(obj.str);
}
}
import java.lang.reflect.Constructor;
public class NewInstanceExample1
{
String str="hello";
public static void main(String args[])
{
try
{
Constructor<NewInstanceExample1> obj =NewInstanceExample1.class.getConstructor();
NewInstanceExample1 obj1 = obj.newInstance();
System.out.println(obj1.str);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
About Multithreading
Life cycle of the thread
JPARepositor:
JPA extend crudRepository and PagingAndSorting repository,
JPA also provides some extra methods related to JPA such as delete records in batch
and flushing data directly to a database.
JPA repository also extends the PagingAndSorting repository. It provides all the
method for which are useful for implementing pagination.
JpaRepository ties your repositories to the JPA persistence technology so it should
be avoided.
Hashmap example
public class main{
public static void main(String[] args)
//creating a map
Map<Integer, String> map = new HashMap<>();
//adding key and value to the map
map.put(123, "java");
map.put(124, "javaScript");
map.put(125, "python");
map.put(126, "c/c++");
//printing a map
for(map.Enrty<Integer, String> itr : map.entrySet()){
int key = itr.getKey();
String value = itr.getValue();
System.out.println("key : "+Key+" value : "+value");
}
}
each bucket internally uses Linked list and linked list contains node
node : Internal structure of node is it contains key, value, hash and next
#################
collections
#################
Boxing :
----------
Converting a primitive data type into object is called Boxing (IN Java the
conversion is taken automatically then we can say as AutoBoxing) Reversing this
situation is Unboxing
UnBoxing:
-----------
when we are converting the object to primitive type is called Unboxing
Linked List:
Linked list is a linear data structure where data are not stored sequentially
inside the computer memory but they are link with each other by the address. The
best choice of linked list is deletion and insertion and worst choice is
retrieval . In Linked list random access is not allowed . It traverse through
iterator.
Vector:
The Vector class implements a growable array of objects. Vectors fall in legacy
classes, but now it is fully compatible with collections. It is found in java.util
package and implement the List interface
HashMap is similar to HashTable in java. The main difference between HashTable and
HashMap is that HashTable is synchronized but HashMap is not synchronized. Also, a
HashMap can have one null key and any number of null values. The insertion order is
not preserved in the HashMap.
Syntax:
Return Value: This method returns a synchronized view of the specified map.
hasNext()--> has a unique property it will check whether we have the element next
to the current element in the list are not and if there is element we will traverse
map.put()->put is used to stored the data in the form of key and value
containsKey(Key)-> contains key is used to check whether the key is already present
or not if key is already presented then get the exisiting key value from that key
they increment that
if the key is not presented then store this key with value as a one only
Advanced Java
difference between Get Put Post Delete htpp methods
About Jsp,servlets,Drivers
what is java bean
what is a servlet
expalin about Servlet mapping
how to create a session in Servlet
what is deployment descriptor
what is servlet lazy loading
what is servletFilter
Explain lifecycle of a servlet
what is WAR file
How to create a cookie using Servlet
A Cookie can be created as below
Cookie cookie = new cookie("username","Pooja");
we can send the cookie from the servlet using response.addCookie(cookie)method
difference b/w cookie and session
Explain the purpose of Servlet container
difference b/w client side and server-side validation
what is jdbc
what is JDBC Driver and its types
difference b/w RowSet and ResultSet
difference b/w java.util.Date and java.sql.Date
Explain MVC Model and its use
Advantages of MVC Design Pattern
difference between web server and application server
what is ServletConfig object and what is ServletContext object
what is Request Dispatcher
what is cookie
difference b/w Generic and HTTP Servlet
#################
java 8 features
#################
3.can you tell Functional Interface which is already there before java8?
.Runnable
.Callable
.Comparator
Intermediate Operations :
Terminal Operations :
Streams in java8
Spring
About Ioc and Handallermapper spring container
Microserves
difference b/w Monolithic and Microservices
Advantges of Microservices
what is Actuator
what is Service registry
what is API GateWay
how to handle fault tolerenace
About Load Balancing
About CircuitBreaker
about fegin client (Inter Service communication)
About Rest Template,Rest Client (our service intracting with the third party Api)
about ribbon
Authentication:checking user credentials to verify whether this user can login into
our application or not (Credentials valoidation)
Authorization: Checking user having access for specific functionality or not (role
checking)
----------
1.what is platform independent in java
2.difference between JDK JRE JVM
JDK is used for during the development of java related projects
JRE is used for to run your programm in different plaforms (MAC/Linux)
JVM is the actual virtual mechaine it takes the byte code and interperts and runs
our programm
3.About String
4.Garbage collector
6.Difference b/w abstract class and Interface when can we go for abstract class and
inteface
you can go for abstract class when there is a IS a relationship,Parent to child
relationship super class sub class relationship,And is no such relation b/w the
objects then we can go for
Interface.
7.Features of Java8
12.About AOP
Aspect-oriented programing is used to solve your cross cutting concerns
about microservices
custom Exception
example of employee class by using HashMap and list in java 8
feature of java8
The job of @Controller is to create a map of model object and return a view name
Restful Api's:
it will handle the resources and it will send the data in the responce body along
side the headers and the status codes and every thing
@GetMapping("/user")
@PostMapping("/user")
@DeleteMapping("/user")
Ex:@GetMapping("{id}")
public String pathVariable(@PathVariable String id){
return "The path Variable is":+ id;
}
Ex:@GetMapping("{id}/{id2}")
public String pathVariable(@PathVariable String id,@PathVariable String id2{
return "The path Variable is":+ id + " : " + name;
}
@RestController
It is a combination of @Controller and @ResponseBody, used for creating a restful
controller. It converts the response to JSON or XML. It ensures that data returned
by each method will be written straight into the response body instead of returning
a template.
What is authentication?
Ans: Authentication is the mechanism to identify whether user can access the
application or not.
What is authorization?
Ans: Authorization is the process to know what the user can access inside the
application and what it cannot i.e which functionality it can access and which it
cannot.
when you writing a method is your method returning a single record to the client or
is your methods returning multiple records to the client based on that we decide
whether we go for Query Parameters or PathParameters
if you are identifying a unique record with the value then we should go for
pathparam pathparameter will represent a single record unique record will go as a
responce to the client
when you have multiple records to retrieve based on the given value then we will go
for query parameters
Both as used to send data to the server query param used key values path param used
directely
Abstraction :
Provide essential features with out including the background details so these
backgrpound details we are hiding at the service impl
we have
crud repository (for crud operations)
jpa repository (for paginatoin,sorting,Query by example)
based on page number selected by user & page size we will retrieve records from
backend using JpaRepository methods
Ex:
Sorting:
-> It is used to retrieve records based on sorting oreder
alphabetical
ascending order
descending order
Ex:
Ex:
PageRequest PageRequest = PageRequest.of(1, 3);
Page<Book> pageData = bookRepository.findAll(pageRequest);
List<Book> findAll = pageData.getContent();
findAll.forEach(book -> System.out.println(book); });
Arrays
---------------
Array is a order sequence, a arrangement and arrangement of same data type when it
comes to java
Array is collection of same data type element stored in memory
Output
This is arr [1, 2, 3, 4, 5]
This is newList [1, 2, 3, 4, 5]
This is newList after adding elements [1, 2, 3, 4, 5, 7, 700]
Note:
Threading concepts
-------------------------
Java Thread pool represents a group of worker threads that are waiting for the job
and reused many times.
In the case of a thread pool, a group of fixed-size threads is created. A thread
from the thread pool is pulled out and assigned a job by the service provider.
After completion of the job, the thread is contained in the thread pool again.
-------------------------
Interview with morgen stanely
Java8 feature
how you secure our rest apis
what is lambda
functional interfaces
Streams example from employee table we want to sort hr depart names of employess
how you handle exceptions in our project
how will you rate for java spring boot microservies rest apis java8
https://javaconceptoftheday.com/solving-real-time-queries-using-java-8-features-
employee-management-system/
compile('org.springframework.boot:spring-boot-starter-web') {
exclude module: "org.springframework.boot:spring-boot-starter-tomcat"
}
compile('org.springframework.boot:spring-boot-starter-jetty')
7.what is constructor?
Constructor is special type of method which is having same name as class name. It
does not have any return type not even void also.
Constructor is special type of method which is having same name as class name.
Constructor is used to construct the values for objects
Method:
you can assign any name to a method.
Method can return any type of value
method is used to execute certain statements.
k2RaZWXswG
TLiQ5WZB29
1. Session :
A session is used to save information on the server momentarily so that it may be
utilized across various pages of the website. It is the overall amount of time
spent on an activity. The user session begins when the user logs in to a specific
network application and ends when the user logs out of the program or shuts down
the machine.
Session values are far more secure since they are saved in binary or encrypted form
and can only be decoded at the server. When the user shuts down the machine or logs
out of the program, the session values are automatically deleted. We must save the
values in the database to keep them forever.
2. Cookie :
A cookie is a small text file that is saved on the user’s computer. The maximum
file size for a cookie is 4KB. It is also known as an HTTP cookie, a web cookie, or
an internet cookie. When a user first visits a website, the site sends data packets
to the user’s computer in the form of a cookie.
The information stored in cookies is not safe since it is kept on the client-side
in a text format that anybody can see. We can activate or disable cookies based on
our needs.
@ControllerAdvice
@ControllerAdvice is a specialization of the @Component annotation which allows to
handle exceptions across the whole application in one global handling component. It
can be viewed as an interceptor of exceptions thrown by methods annotated with
@RequestMapping and similar.
@ExceptionHandler
Annotation for handling exceptions in specific handler classes and/or handler
methods.
filter(predicate) Method
sorted() Method
distinct() Method
map() Method
usecase: These operations should be used to transform stream into another stream