Own Java Notes
Own Java Notes
https://www.baeldung.com/java-oop
Object Oriented Programming is the programming technique to write programs
based on real world objects. The states and behaviors of an object are represented as the
member variables and methods.
1.Abstraction,2.Encapsulation,3.Polymorphism,4.Inheritance,5.Composition,
6.Association,7.Aggregation there are OOPS core concepts
Class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.
A class contains:Fields,Methods,Constructors,Blocks,Nested class and interface.
An object is an instance of a class.
Abstraction is a process of hiding the implementation details from the user. Оnly
the functionality will be provided to the user. In Java, abstraction is achieved using abstract
classes and interfaces. There are many ways to achieve abstraction in object oriented
programming, such as encapsulation and inheritance.
Encapsulation defines the permissions and restrictions of an object and its
member variables and methods.It achieve private modifier providing member variables of
a class and providing public getter and setter methods. Java provides four types of access
level modifiers: public, protected, default and private.
Inheritance:A subclass can inherit the states and behaviors of it’s super class is
known as inheritance.We use extends keyword in java to implement inheritance.used for
code reuse.Multiple Inheritance does not support java.Because it faced diamond problem.
Multiple inheritance: A child class inheriting states and behaviors from
multiple parent classes is known as multiple inheritance.
Multiple inheritance is not supported in classes but it’s supported in interfaces. A
single interface can extend multiple interfaces.
Polymorphism can perform a single action in different ways.There are two types of
polymorphism in Java compile-time polymorphism perform method overloading and
runtime polymorphism perform method overriding.
Example multiple draw methods but they have different behavior. This is a case of
method overloading because all the methods name is same and arguments are different.
Here compiler will be able to identify the method to invoke at compile time
Runtime polymorphism is called as method overriding because subclass has to
override the superclass method. If we are working in terms of superclass, the actual
implementation class is decided at runtime. Compiler is not able to decide which class
method will be invoked. This decision is done at runtime.
Association is a relationship between two objects with multiplicity.For example
Teacher and Student objects. There is one to many relationship between a teacher and
students. However both student and teacher objects are independent of each other.These
relationships can be one to one, One to many, many to one and many to many.
Aggregation is a specialized form of Association where all objects have their own
lifecycle but there is no ownership and child objects can not belong to another parent
object. Let’s take an example of the Department and teacher. A single teacher can not
belong to multiple departments, but if we delete the department teacher will not destroy.
Composition is again a specialized form of Aggregation and we can call this a
“death” relationship. It is a strong type of Aggregation. Child objects do not have their life
cycle and if the parent object deletes all child objects will also be deleted. Let’s take again
an example of the relationship between House and rooms. House can contain multiple
rooms. There is no independent life of room and any room can not belong to two different
houses if we delete the house room will automatically delete.
Collections
https://www.javatpoint.com/java-collections-interview-questions
A Collection is a group of individual objects represented as a single unit. Java
provides Collection Framework which defines several classes and interfaces to represent
a group of objects as a single unit.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are
the two main “root” interfaces of collection classes.Collection framework implements
various interfaces 1.Collection,2.List,4.Set,4.Queue,5.Dequeue,6.Map
Comparable vs Comparator
Comparable Comparator
Comparable affects the original class, i.e., Comparator doesn't affect the original class,
the actual class is modified. i.e., actual class is not modified.
Java provides two interfaces to sort objects using data members of the class:
A comparable object is capable of comparing itself with another object. The class
itself must implement the java.lang.Comparable interface in order to be able to compare its
instances.
A comparator object is capable of comparing two different objects. The class is not
comparing its instances, but some other class’s instances. This comparator class must
implement the java.util.Comparator interface.
1.Comparable(compareTo() method)
this>2 obj = + value
this<2 obj = - value
this= obj = 0 value
2.Comparator (compare() method)
public static Comparator<Student> nameComparator = new Comparator<Student>() {
@Override
public int compare(Student e1, Student e2) {
return (int) (e1.getName().compareTo(e2.getName()));
}
};
Collections.sort(ar, nameComparator);
Compare ArrayList
If you want to represent any object as a string, the toString() method comes into
existence.The toString() method returns the string representation of the object.
By overriding the toString() method of the Object class, we can return values of the
object, so we don't need to write much code.
Exception Handling
Exceptions are events that occur during the execution of programs that disrupt the
normal flow of instructions for bad input and connectivity problems.All exception and errors
types are subclasses of class Throwable base class,
throw throws
Throw is used within the method. Throws are used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions
try-catch – We use try-catch block for exception handling in our code. try is the
start of the block and catch is at the end of try block to handle the exceptions. We can
have multiple catch blocks with try catch blocks that require a parameter that should be of
type exception.
finally – finally block is optional and can be used only with try-catch block.we
might have some resources open that will not get closed, so we can use finally block.
finally the block gets executed always, whether an exception occurred or not.
Multithreading
A constructor initializes an object when it is created. It has the same name as its
class and is syntactically similar to a method. However, constructors have no explicit return
type.
String
String is a sequence of characters. But in Java, a string is an object that represents
a sequence of characters. java.lang.String class is used to create string objects.
There are two ways to create a String object:
1. By string literal : Java String literal is created by using double quotes.
For Example: String s=“Welcome”;
2. By new keyword : Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”);
It creates two objects (in String pool and in heap) and one reference variable where
the variable ‘s’ will refer to the object in the heap.
Java String Pool: Java String pool refers to a collection of Strings which are stored
in heap memory. In this, whenever a new object is created, String pool first checks
whether the object is already present in the pool or not. If it is present, then the same
reference is returned to the variable else new object will be created in the String pool and
the respective reference will be returned.
Java has provided StringBuffer and StringBuilder class that should be used for
String manipulation.StringBuffer and StringBuilder are mutable objects in java and provide
append(), insert(), delete() and substring() methods for String manipulation.
String is immutable.In case you reassign the value the new memory reference will
be created.StringBuffer and StringBuilder reassign the value the no memory reference
created.
StringBuffer StringBuilder
The byte stream created is platform independent. So, the object serialized on one
platform can be deserialized on a different platform.
To make a Java object serializable we implement the
java.io.Serializable interface.
Serializable is a marker interface (has no data member and method).
1.If a parent class has implemented Serializable interface then child class doesn’t need to
implement it but vice-versa is not true.
2. Only non-static data members are saved via the Serialization process.
3. Static data members and transient data members are not saved via Serialization
process.So, if you don’t want to save value of a non-static data member then make it
transient.
4. Constructor of an object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface.
SerialVersionUID
The Serialization runtime associates a version number with each Serializable class
called a SerialVersionUID, which is used during Deserialization to verify that sender and
receiver of a serialized object.
JVM
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM
is the one that actually calls the main method present in a java code. JVM is a part of
JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a
programmer can develop Java code on one system and can expect it to run on any other
Java enabled system without any adjustment.
When we compile a .java file, a .class file(contains byte-code) with the same
filename is generated by the Java compiler. This .class file goes into various steps when
we run it. These steps together describe the whole JVM.
After loading .class file, JVM creates an object of type Class to represent this file in
the heap memory.
An interpreter as opposed to a compiler does not generate machine code. It has
internal logic for processing the statements or byte code instructions and all machine code
or instructions are already in the compiled interpreter.
Lambda Expressions in Java 8
Garbage Collection
Object class
Object class is the superclass of all Java classes. All Java classes inherited from this
class.
protected Object clone() throws Return a new object that are exactly
CloneNotSupportedException ; the same as the current object
Static is a keyword.
Class can not be static.
Method and variable can be static.
If there is a frequent use of a method in a program, then declare that method as
static. The static keyword in java is used for memory management mainly.
Common cases are not going to be changed at any time, so we declare it as static.
Static final
ENUM
Generics(Type safety)
1.The Java Generics programming is introduced in JAVA 5 to deal with type-safe objects.
2.We can hold only a single type of objects in generics. doesn’t allow to store other objects
3.There is no need to typecast the object.
public : Public is an access modifier, which is used to specify who can access this
method. Public means that this Method will be accessible by any Class.
static : It is a keyword in java which identifies it is class based i.e it can be accessed
without creating the instance of a Class.
void : It is the return type of the method. Void defines the method which will not return any
value.
main: It is the name of the method which is searched by JVM as a starting point for an
application with a particular signature only. It is the method where the main execution
occurs.
wrapper classes
Wrapper classes convert the java primitives into the reference types (objects).
Singleton class
Singleton class is a class whose only one instance can be created at any given time, in
one JVM. A class can be made singleton by making its constructor private.
Naming Convention
Marker Interface
It is an empty interface (no field or methods). Examples of marker interface are
Serializable, Clonnable and Remote interface.
Reflection
Reflection is an API which is used to examine or modify the behavior of methods,
classes, interfaces at runtime.
Transient Keyword
Java transient keywords are used in serialization. If you define any data member as
transient, it will not be serialized.
JVM comes across transient keywords, it ignores the original value of the variable
and saves the default value of that variable data type.
Array
Java array is an object which contains elements of a similar data type. It is a data
structure where we store similar elements. We can store only a fixed set of elements in a
Java array.
Ternary Operator
Java ternary operator is the only conditional operator that takes three operands.
Java ternary operator is a one liner replacement for if-then-else statement and used a lot
in java programming.
The first operand in java ternary operator should be a boolean or a
statement with boolean result. If the first operand is true then java ternary operator returns
second operand else it returns third operand.
result = statement ? value1 : value2;
Regex
The Java Regex or Regular Expression is an API to define a pattern for searching or
manipulating strings.
It is widely used to define the constraint on strings such as password and email
validation. // Create a pattern to be searched
Pattern pattern = Pattern.compile("geeks");
// Search above pattern in "geeksforgeeks.org"
Matcher m = pattern.matcher("geeksforgeeks.org");
// Print starting and ending indexes of the pattern in text
while (m.find())
JDBC
Register and Load the Driver: Using Class.forName(), Driver class is registered to
the DriverManager and loaded in the memory.
Use DriverManager to get the Connection object: We get connection object
from DriverManager.getConnection() by passing Database URL String, username and
password as argument.
Class.forName("com.mysql.jdbc.Driver");
// create the connection now
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB","pankaj","pa123");
JAVA VERSIONS
Java SE 8
Lambda Expressions
Default Methods in interface
Java SE 7
Strings in switch Statement
Multiple Exception Handling
Try with Resources
Java nio Package
Java SE 6
Scripting Language Support
J2SE 5.0
Generics
Enhanced for Loop
Typesafe Enums
Varargs
Static Import
J2SE 1.4
XML Processing
Logging API
Assertions
Regular Expressions
J2SE 1.3
Jar Indexing
A huge list of enhancements in almost all the java area.
J2SE Version 1.2
Collections framework.
Java String memory map for constants.
Just In Time (JIT) compiler.
JDK Version 1.1
JDBC (Java Database Connectivity)
Inner Classes
Java Beans
RMI (Remote Method Invocation)
Reflection (introspection only)
Assertion
Assertion is achieved using the assert statement in Java. While executing the
assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError. It
is mainly used for testing purposes during development.
The assert statement is used with a Boolean expression and can be written in two different
ways.
First way : assert expression;
Second way : assert expression1 : expression2;
---------------------------------------------
Spring IOC
https://www.youtube.com/watch?v=suiEGbKf21g
https://www.youtube.com/watch?v=K43qyHJXmWI
https://www.youtube.com/watch?v=IVIhVJJGo68
Spring boot application starts the application created on object in singleton in spring IOC
container.
@Component -instantiate an object and use it to create a bean in a container.
@Scope(value=”prototype”) -instance created not default.not create complex time is
created runtime.
@Autowire- search byType is a class name.
@Qualifer-search byName
byName= create many object based on bean name
byType-one member variable create and one object created by based on class name.
Autowire annotation first looks for types...only one bean as type is autowire is
possible..multiple beans is the same type autowired is not possible.
Container:
1.core-Bean factory
2.J2EE-ApplicationContext,ConfigurableApplicationContext
wat do:
Dependency Injection
The act of connecting objects with other objects, or “injecting” objects into other
objects, is done by an assembler rather than by the objects themselves.
Spring Bean
Any normal java class that is initialized by Spring IoC container is called Spring
Bean. We use Spring ApplicationContext to get the Spring Bean instance.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and
injecting any required dependencies in the bean.
You can configure a Spring bean using @Bean annotation. This annotation is used
with @Configuration classes to configure a spring bean
stateless beans: beans that are singleton and are initialized only once. The only
state they have is a shared state. These beans are created while the ApplicationContext is
being initialized. The SAME bean instance will be returned/injected during the lifetime of
this ApplicationContext. .
stateful beans: beans that can carry state (instance variables). These are created
every time an object is required.
singleton: Only one instance of the bean will be created for each container. This is the
default scope for the spring beans. While using this scope, make sure spring bean doesn’t
have shared instance variables otherwise.it’s not thread-safe.
prototype: A new instance will be created every time the bean is requested.
request: This is the same as prototype scope, however it’s meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet applications.
Spring actuator
Monitoring our app, gathering metrics, understanding traffic or the state of our database
becomes trivial with this dependency.
Actuator is mainly used to expose operational information about the running application –
health, metrics, info, dump, env, etc. It uses HTTP endpoints or JMX beans to enable us to
interact with it.
1.Spring boot actuator monitoring the application any production related stuff
2. health- db connection up or down,process up and running
3.metrics-heap size,space available particular jvm,garbage collections,count url
using,session active
4.env-running port,system properties,system environment,application
Config-application.properties.
5.info-is empty response,u can overwrite something in info
6.trace-accessed the url lists and details,and how much time taken,
7.mappings- show available mapping urls
8.beans-show create all beans and dependencies
9.Custom EndPoint creation in actuator
Spring MVC
MVC
The Model can be some DAO layer or some Service Layers which give some
information about request or requested information or Model can be a POJO which
encapsulates the application data given by the controller.
The View is responsible for rendering the model data and in general it generates
HTML output that the client's browser can interpret.
The Controller is responsible for processing user requests and building appropriate
models and passes it to the view for rendering.
Spring Modules
Spring Framework is using a lot of design patterns, some of the common ones are:
Spring annotations
@ResponseBody – for sending Objects as response, usually for sending XML or JSON
data as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
AspectJ annotations for configuring aspects and advice, @Aspect, @Before, @After,
@Around, @Pointcut etc.
@Component is used to indicate that a class is a component. These classes are used for
auto detection and configured as bean, when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used
with RequestMapping annotation.
@Service is used to indicate that a class is a Service. Usually the business facade classes
that provide some services are annotated with this.
post-initialization and pre-destroy methods in a spring bean –
InitializingBean/DisposableBean interfaces or init-method/destroy-method attributes.
Spring framework also supports @PostConstruct and @PreDestroy annotations for
defining post-init and pre-destroy methods.
Spring batch-These business operations include automated, complex processing
of large volumes of information that is most efficiently processed without user interaction.
These operations typically include time based events (e.g. month-end calculations, notices
or correspondence),
implements ApplicationContextAware
implements Filter
Spring Rest:
JSON
Hibernate
The choice of hibernate over jdbc and sql queries is not because of the
performance but because of reasons mainly object persistence and database
independence in terms of not writing database specific queries.
Hibernate has the capability to generate primary keys automatically while we
are storing the records into a database.
HQL is database independent.Getting pagination in hibernate is quite simple.
Hibernate is little slower than pure JDBC, actually the reason being hibernate
used to generate many SQL statements in run time.
The following are some of the reasons why we use hibernate in the place of jdbc.
In a project data flows between the layers in the form of objects. If we transfer
the data from layer to layer in a text format then number of trips are increased
between layers. It decreases the performance of the project.
In data access layer (persistence layer), If we use JDBC technology then it cannot
transfer objects directly to the database.
A developer needs to convert an object into values(text) and then values are
inserted into a database using JDBC.while reading the data also JDBC can read the row
but we need to convert the values into object. It means JDBC can transfer the data
between Java and database in the form of values(text) but not in the form of object. It
increases the burden on developers for converting data from text to object and vice versa.
Internal state of the SessionFactory is immutable, so it’s thread safe.
Multiple threads can access it simultaneously to get Session instances.
The Hibernate Session object is not thread safe, every thread should
get it’s own session instance and close it after it’s work is finished.
Hibernate SessionFactory getCurrentSession() method returns the
session bound to the context. Once the session factory is closed, this session object gets
closed. The Hibernate SessionFactory openSession() method always opens
a new session.We should open a new session for each request in a multi-threaded
environment. session.load() It will always return a “proxy object” without
hitting the database and the given identifier value, its properties are not initialized yet, it
just looks like a temporary fake object.If no row found , it will throw an
ObjectNotFoundException. session.get() it always hits the database
and returns the real object, an object that represents the database row, not proxy.If no row
found , it returns null. Hibernate merge can be used to update
existing values, however this method creates a copy from the passed entity object and
returns it. Criteria can’t be used to run updates or
delete queries or any DDL statements. It’s only used to fetch the results from the
database. It provides Projection that we
can use for aggregate functions such as sum(), min(), max(). It can be used with
ProjectionList to fetch selected columns only. It can be used for joining
queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and
setProjection(). It can be used for fetching
results with conditions, useful methods are add() where we can add Restrictions.
It provides an addOrder()
method that we can use for ordering the results. hibernate generated
sql queries in log files hibernate.show_sql put on application config.
Hibernate uses
proxy object to support lazy loading. Basically when you load data from tables, hibernate
doesn’t load all the mapped objects. As soon as you reference a child or lookup object via
getter methods, if the linked entity is not in the session cache, then the proxy code will go
to the database and load the linked object. It uses javassist to effectively and dynamically
generate sub-classed implementations of your entity objects. Lazy loading in hibernate
improves the performance. It loads the child objects on demand.Since Hibernate 3, lazy
loading is enabled by default, and you don't need to do lazy="true". It means not to load
the child objects when the parent is loaded. First Level Cache is associated
with Session.It is enabled by default. Second Level Cache is associated with
SessionFactory.It is not enabled by default.
FetchType.LAZY = Doesn’t load the relationships unless explicitly “asked for” via getter
FetchType.EAGER = Loads ALL relationships
EAGER: Convenient, but slow
LAZY: More coding, but much more efficient
Pagination: If Hibernate fetches large amounts of data (records) from the database,
Pagination Hibernate is to divide the large result set into a number of pages and fetch one
page at a time.
paginationDto.getFilters()
criteria.add(Restrictions.like // restriction like where statement
projectionList.add(Projections.property("id"));
projectionList.add(Projections.property("name"));
criteria.setProjection(projectionList); //select particular column only
criteria.setProjection(Projections.rowCount()); //get total count
final Integer totalResult = ((Long) criteria.uniqueResult()).intValue();
criteria.setFirstResult(pageNo * pageSize);
criteria.setMaxResults(pageSize);
criteria.addOrder(Order.desc(sortField)); //asc and desc order
List<?> resultList = criteria.list();
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
Managed beans are lazy by default. It means, bean is instantiated only when a request is
made from the application. @ManagedBean and @ManagedProperty annotation.
@Override
public List<DistrictMaster> load(int first, int pageSize, String
sortField, SortOrder sortOrder,
Map<String, Object> filters) {
---------------------------------------------
JDK,JRE,JVM
SOAP stands for Simple Object Access REST stands for REpresentational State
Protocol. Transfer.
SOAP is a protocol. REST is an architectural style.
SOAP can't use REST because it is a REST can use SOAP web services
protocol. because it is a concept and can use any
protocol like HTTP, SOAP.
SOAP uses services interfaces to REST uses URI to expose business logic.
expose the business logic.
JAX-WS is the java API for SOAP web JAX-RS is the java API for RESTful web
services services.
SOAP requires more bandwidth and REST requires less bandwidth and
resources than REST. resource than SOAP.
SOAP permits XML data format only. REST permits different data formats such
as Plain text, HTML, XML, JSON etc.
SOAP is less preferred than REST REST is preferred over SOAP.
The reason is, abstract classes may contain non-final variables, whereas variables in
interface are final, public and static.
In Java, we can have an abstract class without any abstract method. This allows us to
create classes that cannot be instantiated, but can only be inherited.
An abstract class can provide complete, An interface cannot provide any code at
default code and/or just the details that all,just the signature.
have to be overridden.
In case of abstract class, a class may A Class may implement several
extend only one abstract class. interfaces.Achieve multiple inheritance.
An abstract class can have All methods of an Interface are abstract.
non-abstract methods.Abstract methods
do not have a body.
An abstract class can have instance An Interface cannot have instance
variables. variables
An abstract class can have any An Interface visibility must be public (or)
visibility: public, private, protected. none.
If we add a new method to an abstract If we add a new method to an Interface
class then we have the option of then we have to track down all the
providing default implementation and implementations of the interface and
therefore all the existing code might define implementation for the new method
work properly
An abstract class can contain An Interface cannot contain constructors
constructors.Used for initializing non
static variables.
Abstract classes are fast Interfaces are slow as it requires extra
indirection to find corresponding method
in the actual class
Member variables provide any modifier. Member variable public static final provide
initialization must in member variable jvm Initialization not must in member
variable
The abstract keyword is used to declare Interface keyword used to declare
abstract class. interface
creating a default method in java
interface, we need to use “default”
keyword with the method signature.Java
interface static method is similar to default
method except that we can’t override
them in the implementation classes.
ArrayList internally uses dynamic LinkedList internally uses doubly linked list
array to store the elements. to store the elements.
Manipulation with ArrayList is slow
because it internally uses array. If any Manipulation with LinkedList is faster than
element is removed from the array, all ArrayList because it uses doubly linked list
the bits are shifted in memory. so no bit shifting is required in memory.
ArrayList class can act as a list only LinkedList class can act as a list and queue
because it implements List only. both because it implements List and Deque
interfaces.
ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
HashMap and HashTable difference
HashMap HashTable
Memory Stack memory is used only by one Heap memory is used by all the parts of
thread of execution. the application.
Access Stack memory can’t be accessed Objects stored in the heap are globally
by other threads. accessible.
Lifetime Exists until the end of execution of Heap memory lives from the start till the
the thread. end of application execution.
Usage Stack memory only contains local Whenever an object is created, it’s
primitive and reference variables to always stored in the Heap space.
objects in heap space.
Modifiers
List,Set,Map
Duplicate List allows to Set does not allow Map stores data in the form
elements store duplicate to store duplicate of a key-value pair. It does
elements in java. elements in java. not allow to store duplicate
keys but allows duplicate
values in java.
listIterator listIterator method Set does not Map provides three type of
returns listIterator provide anything iterators -
to iterate over like a listIterator. It map.keySet().iterator()
simply returns the method returns iterator to
elements in List in
Iterator in java. iterate over keys in
java.
listIterator HashMap
provides map.values().iterator()
additional methods method returns iterator to
as compared to iterate over keys in
iterator like HashMap in java.
hasPrevious(),
map.entrySet().iterator()
previous(),
method returns iterator to
nextIndex(),
previousIndex(), iterate over keys in
add(E element), HashMap.
set(E element)
Structure List are Set uses Map for Map uses hashing
and Resizable-array their technique for storing
resizable implementation of implementation. key-value pairs.
Hence, structure is
the java.util.List
map based and
interface in java.
resizing depends
on Map
implementation.
Example >
HashSet internally
uses HashMap.
Index As ArrayList uses Set is not an index Map is not index based
based array for based structure at structure at all in java.
structure implementation it is all in java.
/RandomA
index based
ccess
structure, hence
provides random
access to
elements.
But LinkedList is
not indexed based
structure in java.
gradle maven
Build.gradle is a Groovy script which has Maven build.xml is an xml document that
syntax similar to Java. includes start and end tags.
Single build tools to support multiple
languages.
throw throws
3. They can’t access any non-static 3. It can access any static method
instance variables or methods and any static variable without
creating an instance of the class
with hiding the details and showing the essential things to the user. Thus you can say that
abstraction in Java is the process of hiding the implementation details from the user and
revealing only the functionality to them. Abstraction can be achieved in two ways:
methods and static constants. In an interface, each method is public and abstract but it
does not contain any constructor. Thus, interface basically is a group of related methods
This is the most common way to create an object in java. Almost 99% of objects are created in
this way.
B. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an
object in this way.
C. Using clone()
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject
object = (MyObject) inStream.readObject();
List<String> collect =
alpha.stream().map(String::toUpperCase).collect(Collectors.toList());
The main difference is that bidirectional relationship provides navigational access in both
directions, so that you can access the other side without explicit queries. Also it allows you
to apply cascading options to both directions.
Spring BOOT:
Spring Boot is the best Java framework for microservices.
Bootstrap your application with Spring Initializr.
Spring Boot is a way to ease the creation of stand-alone applications with minimal
or zero configurations.
● Create stand-alone Spring applications
● Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
● Provide opinionated 'starter' dependencies to simplify your build configuration
● Automatically configure Spring and 3rd party libraries whenever possible
● Provide production-ready features such as metrics, health checks and
externalized configuration
● Absolutely no code generation and no requirement for XML configuration
Spring Data
● Prerequisite : Java 8 Optional Class
Optional is a container object which may or may not contain a non-null value. You
must import java.util package to use this class. If a value is present, isPresent() will
return true and get() will return the value. Additional methods that depend on the
presence or absence of a contained value are provided, such as orElse() which
returns a default value if value not present and ifPresent() which executes a block of
code if the value is present.
------------------------------------------------------------------------------------------------------------
What are Annotations?
One word to explain Annotation is Metadata. Metadata is data about data. So Annotations
are metadata for code.
Annotations help to associate metadata (information)
the COALESCE function returns the first non-null expression in the list. If all expressions
evaluate to null, then the COALESCE function will return null.
custom exception
Java String objects are immutable; it is only possible to create modified copies of the
original string. When we need to modify strings in-place, we use StringBuilder.
StringBuilder has methods such as append(), insert(), or replace() that allow you to modify
strings.
@PropertySource({"classpath:inventory.properties"})
@Value("${ntsm.cometServerUrl}")
https://www.geeksforgeeks.org/difference-between-abstract-class-and-interface-in-java/
https://www.geeksforgeeks.org/difference-between-abstraction-and-encapsulation-in-java-
with-examples/
@EnableWebMvc
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(
ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/WEB-INF/view/react/build/static/");
registry.addResourceHandler("/*.js")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.json")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.ico")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/index.html")
.addResourceLocations("/WEB-INF/view/react/build/index.html");
}
}
@Configuration
@EnableWebSecurity
@Profile("!https")
public class SecSecurityConfig
extends WebSecurityConfigurerAdapter {
//...
@Override
protected void configure(final HttpSecurity http)
throws Exception {
http.csrf().disable().authorizeRequests()
//...
.antMatchers(
HttpMethod.GET,
"/index*", "/static/**", "/*.js", "/*.json", "/*.ico")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/index.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html",true)
.failureUrl("/index.html?error=true")
//...
}
}
implementation at all
final
modifier with it
indirection
Normal Class It can extend only one Can implement multiple
Java interfaces
@EnableAutoConfiguration in spring boot tells how you want to configure spring, based on
the jars that you have added in your classpath. For example, if you add
spring-boot-starter-web dependency in your classpath, it automatically configures Tomcat
and Spring MVC.
https://javarevisited.blogspot.com/2012/07/hibernate-get-and-load-difference-interview-que
stion.html
Since load() throws exception when data is not found, we should use it only when we know
data exists.
https://thoughts-on-java.org/ultimate-guide-association-mappings-jpa-hibernate/
https://stackoverflow.com/questions/5998031/complete-list-of-immutable-jdk-classes
@PropertySource({"classpath:ntsmConfig.properties"})
@Value("${ntsm.hibernate.save.chunk.size}")
https://www.baeldung.com/java-executor-service-tutorial
https://javahungry.blogspot.com/2015/09/difference-between-weakhashmap-and-hashmap
-with-exmaple.html?m=1
● Duplicate remove
https://howtodoinjava.com/java8/stream-distinct-by-multiple-fields/
https://www.baeldung.com/java-stream-filter-lambda
https://www.baeldung.com/java-8-collectors
The volatile modifier is used to let the JVM know that a thread accessing the variable
must always merge its own private copy of the variable with the master copy in the
memory. Accessing a volatile variable synchronizes all the cached copied of the variables
in the main memory