JAVA & Angular (for experience) Interview Questions
JAVA & Angular (for experience) Interview Questions
1. What is Abstraction?
Hiding internal implementation and sharing set of services is called as abstarction.
We can achieve abstraction by using “Interface” and “Abstarct Class”.
We can achieve 100% abstraction using “Interface” and partial by using “Abstract Class”.
We can achieve security using abstraction.
E.g. ATM machine, Car, Mobile, etc.
2. What is Encapsulation?
Wrapping of data member and methods called as Encapsulation.
We can achieve it by making data members “private”.
POJO class is good example of encapsulation.
In a class if it has every data member as a “private” then such class is called as tightly
encapsulated.
E.g. Engine, Gear box within Car,etc.
3. Difference between Abstraction and Encapsulation?
Abstraction Encapsulation
Hiding internal implementation and sharing Wrapping of data member and methods.
set of services.
We can achieve abstraction by using We can achieve it by making data members
“Interface” and “Abstarct Class”. “private”.
It increases code. It decreases code.
It solves problem at Design level. It solves problem at implementation level.
4. What is Inheritance?
Acquiring properties of Parent class is called inheritance.
It is also called as IS-A relationship.
It can be achieved by using “extends” keyword, by making Parent-Child relationship.
It helps in reusability of code.
E.g. New Car version inherits properties from old versions.
5. What is Polymorphism?
It means one name many forms.
It makes reusability simple and also makes code understanding easy.
There are two types of Polymorphism :
o Run-time Polymorphism (Dynamic Binding, Overriding)
Decision making at Runtime by using runtime object.
Used for adding additional functionality into existing one.
Useful only in Parent-Child Relationship.
o Compile-time Polymorphism (Static Binding, Overloading)
Best example of polymorphism is “println” method of “printstream” class.
6. Difference between IS-A relationship & HAS-A relationship?
IS-A relationship HAS-A relationship
It is also known as inheritance, it is It is acquiring class properties by creating
acquiring parent class properties. instance of that class.
It is achieved by “extends” keyword. It is achieved by “new” keyword.
Method with same name, signature but Method with same name and different
different return types can’t be created in return type can be created.
parent-child class.
7. Difference between Overloading & Overriding?
Overloading Overriding
Decision making done at compile-time, Decision making done at run-time, where
where compiling is based on reference JVM run is based on runtime object.
type.
We can overload method and constructor We can override method but we can’t
both. override constructor.
We can overload static, private and final We can’t override static, private and final
method. method.
E.g. “println” method of Printstream E.g. ‘equals’ method of object class and
class. ‘equals’ method of String class.
8. What is Static?
Static is keyword.
We can apply static keyword with variables, methods, blocks and classes.
The static variable gets memory only once in the class area at the time of class loading.
It can be used to refer to the common properties of all objects, for example, the
company name of employees, college name of students, etc.
A static method belongs to the class rather than the object of a class. It can be invoked
without the need for creating an instance of a class. It can access static data member
and can change the value of it. It can be used to setup database connection.
Static block is used to initialize the static data member. It is executed before the main
method at the time of class loading.
9. What is non-static block?
It is used for non-initializing content.
Before calling constructor non-static block is executed.
10. What is constructor?
A constructor in Java is a special method that is called when an object of a class is
created.
It is used to initialise object as well as non-static variables.
Constructors can also take parameters to initialize data members.
11. What is Object?
An object is an instance of a class.
Objects have states and behaviours. Example: A dog has states - color, name, breed as
well as behaviours – eat, bark, smell.
Ways we can create an object :
o By using new Operator :
Test t = new Test();
o By using newInstance() :(Reflection Mechanism)
Test t=(Test)Class.forName("Test").newInstance();
o By using Clone() :
Test t1 = new Test();
Test t2 = (Test)t1.clone();
o By using Factory methods :
Runtime r = Runtime.getRuntime();
DateFormat df = DateFormat.getInstance();
o By using Deserialization :
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Test t = (Test)ois.readObject();
EXCEPTION HANDLING
12. What is Exception?
In our application, there are chances of abnormal condition, normal flow of program get
disturbed, such situation is called as an exception.
All types of exceptions only occurs at runtime.
So avoiding such abnormal termination we need to handle exception.
Exception will occur because of wrong user input.
13. What is Exception Handling?
To avoid occurring exception we need to provide alternative way to execute rest of
program, this is called as exception handling.
Keywords to handle exception: try, catch, finally, throw, throws.
14. Difference between Exception and Error?
Exception Error
Classified as checked and unchecked type. Classified as an unchecked type.
It belongs to java.lang.Exception. It belongs to java.lang.error.
We need to handle the exceptions. We need to solve the errors.
It can occur at run-time & compile-time It doesn't occur at compile-time, only
both. occurs at run-time.
E.g. NullPointerException , SqlException, E.g. OutOfMemoryError ,
etc. AbstractMethodError, etc.
Collection
1. What is Collection?
The Collection is a framework that provides an architecture to store and manipulate the
group of objects.
It provides operations that you perform on a data such as searching, sorting, insertion
and deletion on the group of objects.
Collection represents a single unit of objects as a group.
2. Why do we use Collection?
(Explain Difference between Array & Collection)
Array Collection
It is Fixed in Size. It is Growable in nature.
It can hold only Homogeneous Data It can hold both Homogeneous and
Elements. Heterogeneous Elements.
With Respect to Memory Arrays are Not With Respect to Memory Collections are
Recommended to Use. Recommended to Use.
Hibernate
1. What is Hibernate & ORM tool?
(Hibernate)
It is Java Frame work that simplifies development of Java Application to interaction with
database.
It creates SQL (Structured Query Language) queries at runtime according to database.
It provide automatic table creation feature, relationship mapping like IS-A relationship
(Default, Single Table, Joint, table per Class) & HAS-A relationship (one to one, one to
many, many to one, many to many).
It provide primary key auto increment feature.
It converts all checked exception into uncheck exception.
It provides cache mechanism.
It provide HQL (Hibernate Query Language) query and Criteria API.
(ORM)
It is a programming technique that maps the object to the data stored in the
database.
It overcomes the mismatch between OOP language & database.
It reduces developer’s efforts, time and cost.
2. What is disadvantage of hibernate?
Can’t perform multiple insert operations.
Debugging is difficult as compare to JDBC.
Contain lots of boiler plate code.
Can’t be used for small type of applications.
Slow execution as it perform SQL queries at runtime.
3. Difference between get( ) & load( )?
get ( ) load ( )
Eager Loading Lazy Loading
If value is absent in database then it If value is absent in database then
returns null. hibernate exception
(ObjectNotFoundException) occurs.
It always hit database. It may or may not be hit to database.
4. What are the ways to implement Restful web service? Which one you have used?
In JAX-RS, there are 3 types to implement Restful web service.
o Jersey.
o REST easy.
o Spring with REST.
We have used spring with REST type.
5. By using spring with REST, how do we create Restful web service?
Add REST dependency in pom.xml. (spring-boot-starter-data-rest)
Add @RestController annotation for controller class.
Map the methods written in controller class.
6. What is REST? Why do you choose Restful web service?
REST is the acronym for REpresentational State Transfer. REST is an architectural style
for developing applications that can be accessed over the network.
REST is a stateless client-server architecture where web services are resources and can
be identified by their URIs (Uniform Resource Identifiers).
We choose Restful web service because-
o It is architectural style not protocol.
o It is fast and has no restrictions like SOAP.
o It uses data formats like XML, HTML, Plain Text, JSON, etc.
o It also can use SOAP.
o It is programming language and platform (OS) independent.
7. Annotations used in Restful web service?
@RestController
@GetMapping
@PostMapping
@DeleteMapping
@PutMapping
@PathVariable
@RequestBody
@ResponseBody
8. Difference between @Controller & @RestController?
@Controller @RestController
It is used to mark a class as Spring MVC It is used in RESTFul web services and the
Controller. equivalent of @Controller +
@ResponseBody.
It returns view. It returns data.
Added in Spring 2.5 version. Added in Spring 4.0 version.
Design Pattern
1. Explain with example Factory Method Design Pattern?
It is used if a java class is having private constructor and outside of that class object
creation of that class is not possible.
Factory method is java method, having a capability of constructing and returning its own
java class object.
E.g. Example for pre defined instance factory method is:
String s1=”welcome to durga software solutions”; // Existing Object
String s2=s1.substring(3,7); // New Object i.e. it gives come
E.g. (Sample Code)
class Test
{
int x;
//private zero argument constructor
private Test()
{
System.out.println("Test: 0-arg Con");
}
//static factory method
public static Test staticFactoryMethod()
{
Test t=new Test();
t.x=5;
return t;
}
//instance factory method
public Test instanceFactoryMethod()
{
Test t=new Test();
t.x=this.x+5;
return t;
}
public String toString()
{
return "x="+x;
}
}
class Demo
{
private static Demo instance;
private Demo()
{
System.out.println("Demo : 0-arg Con");
}
//static factory method
public static Demo getInstance()
{
// Singleton Logic
if (instance == null)
instance = new Demo();
return instance;
}
//override Object class clone()
public Object clone()
{
return instance;
}
}
3. How to break Singleton Class?
To Break Singleton Using Reflection
import java.lang.reflect.Constructor;
The singleton will only work per classLoader. To break it, use multiple classLoaders.
One more way is to Serialize the Object store it in a file and Deserialize it to get a new
Object.
4. What is Class Loader?
The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads
Java classes into the Java Virtual Machine. The Java run time system does not need to
know about files and file systems because of classloaders.
Java classes aren’t loaded into memory all at once, but when required by an application.
At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load
classes into memory dynamically.
Serialization
1. What is Serialization?
The process of saving (or) writing state of an object to a file is called serialization.
But strictly speaking it is the process of converting an object from java supported form
to either network supported form (or) file supported form.
By using FileOutputStream and ObjectOutputStream classes we can achieve serialization
process.
2. Have you used Serialization in your project?
3. What is real time technical example of Serialization?
Flipkart/Amazon application, all buying section contains images of products, that are
stored in binary format in their database using serialization technique. When client
download them from their website then these images are deserialised into client’s
device.
4. How to serialize particular states of objects of class?
By using Externalization process.
To provide Externalizable ability for any object compulsory the corresponding class
should implements externalizable interface.
Externalizable interface is child interface of serializable interface.
Agile
1. Do you know Agile? Have you implemented in your project?
The Agile Method and methodology is a particular approach to project management
that is utilized in software development, it is iterative approach to software delivery that
builds software incrementally from the start of the project, instead of trying to deliver it
all at once near the end.
We have not implemented 100 % agile, we have followed agile.
2. What is Sprint?
It is of maximum 2 weeks or minimum 2 days.
It is time duration, in which decided work is completed.
3. What is Story?
Whichever task is assigned is called as Story.
4. Who is Scrum Master?
Manager who carry all agile process from team.
In our case team manager was Scrum Master as we can’t afford resource for that as we
were small scale industry.
5. Who is Product Owner?
It is person who interacts with client.
Gets requirements from client and convert it into stories in document format. So that it
could be assigned to developers.
6. What is your daily routine?
On every start of week, at start time of office at 9 AM, daily stand up or scrum meeting
was held approximately 15 min or can be extended to 30 min.
Scrum master manages this meeting and assigns stories to developers.
In this meeting, road blocks or problems occurred in stories are discussed and resolved.
7. What is Grooming Session?
It held by Product Owner.
Also upcoming stories are explained to developers.
8. What is Retrospective Call?
It happens at Sprint end.
All issues that stopped working of stories are discussed and taken care of not repeating
them in next sprint.
Kudos & Thanksgiving done.
9. What is Demo Call?
It held at the end of sprint.
Its call with client to show demo of story completed.
Client suggestions are added in next sprint stories by product Owner.
10. How did you gather requirements from Client?
We had resource as a product owner, for gathering requirement who also divided it into
stories to assign it to developer.
11. How did Stories assign to you?
We used to receive mails from product owner with stories attached in document format.
In big scale companies JIRA like softwares are used to handle all agile process.
GitHub
1. Tell all the steps followed in Github in your project?
git clone url (by-default points master branch)
git checkout sprint1
git branch (new branch name)
git checkout new branch (now it points to new branch created)
(now make changes in code, after that follow below commands)
git status
git add
git commit –m “commit message”
git push origin “branch_name”
2. What was Master Branch?
Branch name “develop”, that contains clean code which goes for execution.
Team leader was developing new master branch for each sprint and then we clone that.
String
1. What is String Constant Pool (SCP) concept?
When we create String object without using new operator the objects are created in SCP
(String constant pool) area.
String s1=”ABC”;
S1 ABC
String s2=”DEF”;
String s3=”DEF”; S2
When we create object in SCP area then DEF
S3
just before object creation it is always checking
previous objects. SCP Area
If the previous object is available with the same content
then it won’t create new object that reference variable pointing to existing object.
If the previous objects are not available then JVM will create new object.
SCP area does not allow duplicate objects.
2. When does object get created in SCP?
When String object is created with new keyword.
When only String variable with content is created.
3. Why String is immutable?
String object is immutable means its 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.
The String is widely used in Java applications to store sensitive pieces of information like
usernames, passwords, connection URLs, network connections, etc. It's also used
extensively by JVM class loaders while loading classes.
Hence securing String class is crucial regarding the security of the whole application in
general.
Being immutable automatically makes the String thread safe since they won't be
changed when accessed from multiple threads.
As we saw previously, String pool exists because Strings are immutable. In turn, it
enhances the performance by saving heap memory.
E.g. Database connection properties are stored in String, so that no one can update that
object to hack database data and database security can be achieved.
4. Difference between String & StringBuffer?
String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more memory StringBuffer is fast and consumes less
when you concat too many strings because memory when you cancat strings.
every time it creates new instance.
String class overrides the equals() method StringBuffer class doesn't override the
of Object class. equals() method of Object class.
5. What are the String Scenarios related to String object creation while using Concat ( )?
Concatenation of String :
String s="cjc";
String s1=s.concat("class");
String scenarios :
Logical Problems
1. Find Even-Odd Number?
Public class Test1
{
public static void main(String[ ] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt( );
if (n%2==0)
{
System.out.println(n+”is Even number.”);
} else {
System.out.println(n+”is Odd number.”);
}
}
}
}
}
}}
7. Find Neon Number?
E.g. 92 =81 => 8+1 = 9
Public class Test
{
public static void main(String[ ] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt( );
int m=n x n, sum=0;
while(m>0)
{
sum = sum + m%10 ;
m=m/10;
}
if(sum == n)
{
System.out.println(n + “is Neon number.”);
} else {
System.out.println(n + “is not a Neon number.”);
}
}
}
}
}
9. Swap the numbers?
o ng new myNewApp
Step-3: Go to your project directory:
o cd myNewApp
Step-4: Run server and see your application in action:
o ng serve
3) What is NPM?
NPM stands for Node Package Manager.
NPM is used to fetch any packages (JavaScript libraries) that an application needs for
development, testing, and/or production, and may also be used to run tests and tools used
in the development process.
NPM is 3rd party library or 3rd party package.
NPM is the package manager for the Node JavaScript platform. It puts modules in place so
that node can find them, and manages dependency conflicts intelligently.
Most commonly, it is used to publish, discover, install, and develop node programs.
4) How to create modules, components, services, interfaces, classes in Angular 4 using NPM?
=> *for Module:
- ng g module newModule
*For Components:
- ng g component new-module/new-component
*for Service
- ng g service newservice
- ng g s newservice
* for Interface
- ng generate interface interfaceName
*for Class
- ng g class className
(Manually)
- Go to component (where new component to create) Right Click to create component
files .ts file is compulsory needed, other than that .html, .scss & .spec.ts files are
also created while creating component add @Component Decorator in .ts file that
contains metadata of component.
Angular 3:
o Why we don’t have Angular 3?
Angular is being developed in a MonoRepo it means a single repo for
everything. @angular/core, @angular/compiler, @angular/router etc are in
the same repo and may have their own versions.
The angular router was already in v3 and releasing angular 3 with router 4
will create confusion
To avoid this confusion they decided to skip the version 3 and release with
version 4.0.0 so that every major dependency in the MonoRepo are on the
right track.
Angular 4
o Released in 2017
o Changes in core library
o Angular 4 is simply the next version of angular 2, the underlying concept is the same
& is an inheritance from Angular 2
o Lot of performance improvement is made to reduce size of AOT compiler generated
code
o Typescript 2.1 & 2.2 compatible — all feature of ts 2.1 & 2.2 are supported in
Angular 4 application
o Animation features are separated from @angular/core to @angular/animation
don’t import @animation packages into the application to reduce bundle size and it
gives the performance improvement.
o Else block in *ngIf introduced:
— Instead of writing 2 ngIf for else , simply add below code in component template:
*ngIf=”yourCondition; else myFalsyTemplate”
“<ng-template #myFalsyTemplate>Else Html</ng-template>”
Angular 5
o Released 1st November 2017
o Build optimizer: It helps to removed unnecessary code from your application
o Angular Universal State Transfer API and DOM Support — by using this feature, we
can now share the state of the application between the server side and client side
very easily.
o Compiler Improvements: This is one of the very nice features of Angular 5, which
improved the support of incremental compilation of an application.
o Preserve White space: To remove unnecessary new lines, tabs and white spaces we
can add below code(decrease bundle size)
// in component decorator you can now add:
“preserveWhitespaces: false”
// or in tsconfig.json:
“angularCompilerOptions”: { “preserveWhitespaces”: false}`
o Increased the standardization across all browsers: For internationalization we were
depending on `i18n` , but in ng 5 provides a new date, number, and currency pipes
which increases the internationalization across all the browsers and eliminates the
need of i18n polyfills.
o exportAs: In Angular 5, multiple names support for both directives and components
o HttpClient: until Angualar 4.3 @angular/HTTP was been used which is now
depreciated and in Angular 5 a new module called HttpClientModule is introduced
which comes under @angular/common/http package.
o Few new Router Life-cycle Events being added in Angular 5: In Angular 5 few new
life cycle events being added to the router and those are:
o ActivationStart, ActivationEnd, ChildActivationStart, ChildActivationEnd,
GuardsCheckStart, GuardsCheckEnd, ResolveStart and ResolveEnd.
o Angular 5 supports TypeScript 2.3 version.
o Improved in faster Compiler support:
o A huge improvement made in an Angular compiler to make the development build
faster. We can now take advantage of by running the below command in our
development terminal window to make the build faster.
ng serve/s — aot
Angular 6
o Released on April 2018
o This release is focused less on the underlying framework, and more on tool-chain
and on making it easier to move quickly with angular in the future
o No major breaking changes
o Dependency on RxJS 6 (this upgrade have breaking changes but CLI command helps
in migrating from older version of RxJS)
o Synchronizes major version number of the:
— Angular framework
— Angular CLI
— Angular Material + CDK
o All of the above are now version 6.0.0, minor and patch releases though are
completely independent and can be changed based on a specific project.
o Remove support for <template> tag and “<ng-template>” should be used.
o Registering provider: To register new service/provider, we import Service into
module and then inject in provider array. e.g:
// app.module.ts
import {MyService} from './my-service';
...
providers: [...MyService]
...
o But after this upgrade you will be able to add provided In property in injectable
decorator. e.g:
// MyService.ts@Injectable({ providedIn: 'root'})
export class MyService{}
o The way ngModelChange event works:
Let’s understand this with output produced by older and this version:
// Angular 5:
<input [(ngModel)]=’name’ (ngModelChange)=’onChange($event)’ />
onChange(value){ console.log(value); } // Would log updated value