Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

0-Java Interview Q&A Coding Examples

The document contains a comprehensive list of questions and answers related to Java, Spring, microservices, and software testing concepts. It covers topics such as bean scopes in Spring, threading, functional programming, and the differences between various data structures. Additionally, it discusses best practices for testing and exception handling in Java applications.

Uploaded by

Pratiksh Patel
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

0-Java Interview Q&A Coding Examples

The document contains a comprehensive list of questions and answers related to Java, Spring, microservices, and software testing concepts. It covers topics such as bean scopes in Spring, threading, functional programming, and the differences between various data structures. Additionally, it discusses best practices for testing and exception handling in Java applications.

Uploaded by

Pratiksh Patel
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 88

Achieving Loose Coupling Between Classes

3
What are the different scopes for spring bean ?

What is class level locking?


What is instance level locking?
What is a string pool in java ?
What ia a functional interface from Java 8?

What is lamba expressions in java?

What is the difference between sleep and wait in threads?

What is the difference between primitive data type/int vs class object/Integer ?

Why is string immutable?

What is the difference between a comparator and a comparable?


What is trigger ?

What is the diff between pk and uk ?

What is the different between a hashtable and a concurrent hashmap ?

How does rehashing happen in hashmap?

How can we detect memory leak in our application?


Why microservices were invented?

How do you write a JUNIT Test Case for exception ?


In order to test any Java method for throwing an exception you need to ensure that the
argument provided to that method, from the test must result in expected Exception,
Otherwise, the JUnit test will fail.

What is the difference between a unit test or a integration test

What is TDD?

What are CRON Expressions?


Can you write statements after return statement?
If I write return statement at the end of the function and have a finally block just above
the return statement then what will happen?
What is the benefit of PreparedStatement over Statement?

What is REST?

What is a string tokenizer?

What are the 2 ways of creating threads; which is better ?


What is a callable interface in threads?

What is a fail fast and a failsafe iterator?

...you can support multiple inheritance through interfaces (java doesn’t support more than 1 interfaces extension)
...if you put a object with a key that’s already present in the hashmap then we have to use
equal() to compare the objects content and if its different content then we can add object
...while creating immutable classes we declare all instance variables as final we cannot
change its value because final means CONSTANT not variable

Executor Framework for multijthreading


Java provides its own multi-threading framework called the Java Executor Framework.

What is a Decorator Design Pattern ?

What is the diff between Factory and Abstract Factory?

Can we overload a static method in java?

If a method is throwing null pointers in super class; can we override it with a method
which throws runtime exception in child class ?

In core java, can you access non static variables declated outside of the main() in a static
context(Class.var) in the main() ?
What is singleton?

Is it better to make the whole methods sync or only critical parts sync?
if you have returns in try, catch and finally what is the order of execution ?
What is association, aggregation and composition?

What is a binary tree?

How does a hashmap internally work?


We have a list of employees(id,name) from the last 3 years

How does garbage collection work in java?


What features of Java 8 have you used ?
What other frameworks have you used apart from core java?

What problem does spring boot framework solve relative to Spring ?

What is the difference between a 1st level and a 2nd level cache in Hiberante?
What is a bean factory in Spring ?
What is Application Context ?

What is the concept of Time Zone?


In Spring Boot Microservices; how are the profiles of different envs managed?
We define the profile tags in the project's pom.xml file to create DEV and Prof probile to
enable env specific config properties Note the
<activeByDefault>true</activeByDefault> tag, which means that the development profile
will be used by default assuming no profile is specified at build time.

Write a method to check if two strings are Anagram


Lambda Practice
What are the differences between Spring and Spring Boot ?

How does Spring implement dependency injection?

What is singleton bean scope in Spring?


What is prototype bean scope in Spring?
What is the default bean scope in Spring?
Why is singleton the default bean scope in Spring?

How do you handle mocking a service in a test with JUnit or Mockito ?


What is SonarCloud used for ?

What are CI/CD Pipelines ?

What percentage of code test coverage have you usually reached with your projects or work?

What are streams in java?


What are lambdas in java ?

What version of Java were lambas introduced?

Why are lambdas important in Java ?


How is OOP different from FP?

Why is functional programming at times more efficient than oop?

What is Reactive programming in Java?


What is the flux pattern?

Flux pattern solves the scalability issue by using unidirectional


data flow to pass data among the different component views in the
app.
FluxJava Framework implements Flux Pattern.

Diff between monolith and microservice architecture ?


A monolithic application is simply deployed on a set of identical servers behind a load
balancer. A
microservice application typically consists of a large number of services. Each service will
have multiple runtime instances. And each instance need to be configured, deployed,
scaled, and monitored. In addition, you will also need to implement a service discovery
mechanism.

Have you used React or Angular before? What kind of React tests have
you written with Jest?

How would you test the onClick event of a component in React?


What are promises in JavaScript?

How do you handle errors from HTTP Requests in JavaScript?


Exception handling in spring boot. How do you handle
exception and where and how you use @controllerAdvice
whats the version of spring boot that we are on right now?

When there is an with entity association in database what


do you add in the bean configuration file? This is for the relation ship to ONE TO
ONE , One to Many and others
Scenario question there is a user and many loans what kind of relationship there will be
between these two entities? And which one will persist and which one will cascade?

After when you right a query based on the relationship you


design when you right the query for the user entity does all
the loans data populate as well?
How does dispatcher servlet work in Spring MVC?
What’s the use of SPARK? Why would you choose spark
over other frameworks? What’s Spring boot?

Can you deploy Spring boot on an external web application


server?

arraylist vs linked list Hashset vs hashmap

What’s microservice Should the database be self contained


within the microservice? Why? What’s Kafka?

Step by Step: How to set up a database connection in Spring


H2 is a ram storage database
MySQL is a disk storage database

Step by Step: Create a REST API from scratch and display a basic
string for a GET request using Spring Boot
Change folder structure: group.artifact.controllerFolder
Change folder structure: group.artiface.modelFolder
Inversion Of Control (IOC) - delegate responsibility to another class

Dependency Inversion Principle (DIP) : interfaces -> abstractions

Dependency Injection (DI)- Moving Object creation out of the class


Singleton: creates a single bean object that’s returned for all requests
Prototype: creates a new bean object for a new request
Request: creates a single bean object for a single http request
Session: creates a bean object for an http session
Application: creates a bean object for the lifecycle of a ServeletContext
Websocket: bean object stored in Web Socket Session (singleton for websocket session)

Threads acquire class level locks via [static sync function OR sync block]
Threads acquire object level locks via [sync function ]
Functional Interface contains 1 abstract function

Lambda expression is used to provide the implementation of an interface which has f

wait() releases the lock while the thread is waiting


sleep() doesn't releases the lock while the thread is sleeping (to get data from async call)

Integer takes more memory

string is Immutable in Java because String objects are cached in the String pool

Comparable is a interface to compare a object on 1 instance variables to sort the list of objects
Comparator is a interface to compare a object on 1+ instance variables to sort the list of objects
triggers are functions that track db table updates

primary keys are unique and define the row (we cannot have null primary keys)
we can have null unique keys and a combination of columns make up the unique keys

Concurrent hashmap; reading or updating locks on the row and not the entire datastructure object
Hashtable ; reading or updating locks the entire datastructure object

put() calculates hashcode and find a bucket and see if the hashcode matches or not
if hashcode is matching but value is different then another node will be inserted
microservices modularize controller functions that handle api web service calls
unit test is testing objA.fA()
integration test is testing objB.objA.fA()

thinking of all test cases means we are writing down the requirements first and using it to code so
developing in that manner means accurately developing the code to fullfill the requirements

CRON Expressions for scheduling batch jobs to execute


after return the compiler will say code not rechable

after finally the compiler will say code not rechable


If you know the db schema you can write SQL Statements to inject fake data into Statement
you cannot do sql injection for Prepared Statement

REST is a an API that communicates between a web browser and a web server executing MVC Code

{BETTER} Using Runnable Interface: you arent overriding run()


Extending Thread Class: you are overriding run()
Callable Interface is done to do async tasks by a separate thread

Iterators are used to iterate over a list/collection of objects

more than 1 interfaces extension)


add new method but don’t nodify existing method for new requirements via interfaces

AbstractFactory is an Interface that needs to be extended by a factory to create objects


Factory is a concrete class that automates creation of objects

yes; We can have two or more static methods with the same name, but different input param

Yes, overriding method can throw runtimeException. There is no policy


for RuntimeException (unchecked exceptions) in method overriding.

non static method can access static variable/methods


you cannot access a non-static variable/method from a static method in Java.
Restricts object creation to 1 instance

its not a matter of better; its just alternative way:


if you want to lock an object for thread safety then
synchronize the method like this

its not a matter of better; its just alternative way:


if you want to lock part of a method for thread safety then use
a synchronized block like this
Parent Node with at most 2 leaf Nodes

Hashing is a way of assigning a unique code for any variable/object


Two Equal objects produce the same hash code
Sort the employee object on salary for descending order
write a for loop that does i<=N-1 in order to print top N paid employee objects
Spring Boot Framework, Hibernate ORM Framework

it automates dependency managemenbt via XML file for large projects

First level cache is a session level cache and it is always associated with session level object. This type
of cache is used for minimizing Db interaction by caching the state of the object. That is instead of
updating after every modification done in the transaction, it updates the transaction only at the end of
the transaction.
Second level cache is session factory level cache and it is available across all sessions.While running the
transactions, in between it loads the objects at the Session Factory level, so that those objects will be
available to the entire application, not bound to a single user. By default, it is disabled in hibernate.
Git Server -> Global Config Server -> Microservice gets global configs
1st, we add a parameter in application.properties file to tell Spring to use a different env specific
property file corresponsing to the active profiles
spring.profiles.active=@activatedProperties@
2nd, we
have to create 2 new env specific property files in the same path as application.properties file (one to be
used by the DEV profile and one to be used by the PROD profile) application-
dev.properties
application-prod.properties
Within each
of these files, properties can be defined that will only be applied when the corresponding profile is
active.
Configuration of dependencies are read from XML, annotations or Java DSL (JavaConfig). Then Spring DI
engine wires the dependencies based on the metadata from the configuration using the Java reflection
API.

Singleton scope in the spring framework is the default bean scope in the IOC container. It tells the
container toisexactly
If the scope create
declared a singlethen
prototype, instance of IOC
spring the container
object. This single
will instance
create a new is stored in
instance of the
thatcache
bean and
all the
every subsequent
time a requestrequests for that named bean return the cached instance.
Singleton is the isdefault
made for that specific
scope bean. A the
for a Bean, request
onecan be made
that to used
will be the bean instance either
if nothing else
programmatically using getBean() method or by XML for Dependency Injection of secondary type.
is indicated. This scope implies that Spring container will create an only shared
Singleton
instanceScope
of the class designated by this bean, so each time the Bean is required the
same object will be injected.
SonarCloud is a cloud-based code quality and security service for catching Bugs and Security
Vulnerabilities in your Pull Requests and throughout your code repositories.

pipelines are a series of automated steps that must be performed in order to deliver a new version of software

80% to deliver

streams provide a filter() which take a Predicate object


Java SE 8.
Lambda functions are pure functions means they don’t change the passed in
objectList thus we have surity the sorted objectList is sorted but not
changed.
OOP is a connected node of classes (allows objects to change)
FP is a connected node of functions (doesn’t allow objects to change)

outputs of a function in functional programming purely relies on arguments


of the function,
Functional programming provides high performance in processing large data for applications. Object-
oriented programming is not good for big data processing.

Reactive Programming is a programming paradigm that focuses on making async and non blocking
component Spring
Webflux is a reactive-stack web framework that is fully non-blocking, supports Reactive Streams
yes. No i have not written any react tests using JEST
@ Controller Advice is a specialization of @Component which allows to handle exceptions across the
whole application in one global handling component
The current stable version, as of July 2022, is Spring Boot 2.7
UPDATE User SET loan = 100 WHERE loanName IN ('loanA', 'loanB', 'loanC');
DispatcherServelet acts as a front controller for Spring Web Apps by handling incoming http requests,
delegates the http requests and processess the http requests per controller functions ,end points and
response objects

Spark is a big data processing framework; Spring boot is a back end framework for making web apps

n Spring
interface which has functional interface.

he String pool
but different input parameters
rsion of software
Java Concept Clarity https://www.youtube.com/watch?v=hainZwgvGYY&list=PLk58B65P9YaZIUuZICiQOt9W
Spring Boot Concept Clarity https://www.youtube.com/watch?v=-_tPeb3VE6w&list=PLk58B65P9YaZfKMxVue4LA2
=PLk58B65P9YaZIUuZICiQOt9WXBAO_r_oR
=PLk58B65P9YaZfKMxVue4LA2M0iFg7KR1U

You might also like