In Java is there a difference between Iterator and Iterable?
The names of the interfaces are perfectly fitting, they should give you a hint, if not the direct
answer already. A class that implements the Iterable interface is - ITERABLE.
So it can be iterated on this class.
This for example is used by the for each loop:
1. for(Item item: items) {
2. System.out.println(item);
3. }
This code will ONLY work on the condition that “items” is a class that implements the Iterable
interface.
The Iterable interface has just one method:
1. Iterator<T> iterator();
ArrayList al = new ArrayList();
for (int i = 0; i < 10; i++)
al.add(i);
Iterator itr = al.iterator();
while (itr.hasNext())
{
// moving cursor to next element
int i = (Integer)itr.next();
// getting even elements one by one
System.out.print(i + " ");
// Removing odd elements
if (i % 2 != 0)
itr.remove();
}
It will return an iterator, and the iterator will be used internally by the JVM to iterate over your
object.
An Iterator is an object used to Iterate over another object. Like a smart pointer object, that
stores the state (current, last, next, hasNext…).
So you could say - Iterable is a tree of pears. Iterator is a pear.
A tree of of pears “returns pears”. A tree of pears is not a pear.
Hibernate version vs audit
@Version - is used to implement optimistic locking, see 2.2.1.2. Versioning for optimistic
locking. Optimistic locking is useful when you don't expect many concurrent writes and don't
want to pay the price of database locking.
@Autidted - comes from Envers API and can be used to automatically track changes to entities
in a separate auditing table. Use Envers to keep history of changes of some of your entities.
Optimistic
Optimistic locking assumes that multiple transactions can complete without affecting each other,
and that therefore transactions can proceed without locking the data resources that they affect.
Before committing, each transaction verifies that no other transaction has modified its data. If
the check reveals conflicting modifications, the committing transaction rolls back[1].
Pessimistic
Pessimistic locking assumes that concurrent transactions will conflict with each other, and
requires resources to be locked after they are read and only unlocked after the application has
finished using the data.
Why use entity manager
You use an EntityManager when you are using JPA API. Hibernate implementation of
EntityManager internally calls HibernateSessionFactory and manages Hibernate
sessions for you.
EntityManagers in JPA serve basically the same purpose as Hibernate sessions.
JavaBean class in Java
JavaBeans are classes that encapsulate many objects into a single object (the bean). It
is a java class that should follow following conventions:
1. Must implement Serializable.
2. It should have a public no-arg constructor.
3. All properties in java bean must be private with public getters and setter
methods.
filter_none
brightness_4
// Java program to illustrate the
// structure of JavaBean class
public class TestBean {
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
Spring Bean Life Cycle
1. Creation of bean instance by a factory method.
2. Set the values and bean references to the bean properties.
3. Call the initialization call back method.
4. Bean is ready for use.
5. Call the destruction call back method.
Spring can recognize the initialization and destruction callback methods in the below
three ways.
1. A Bean can implement the InitializingBean and DisposableBean life cycle
interfaces and overriding the afterPropertiesSet() (Called during Spring bean
initialization) and destroy() methods for initialization and destruction
respectively.
2. Set the init-method and destroy-method attributes in the bean configuration
file.
3. Use @PostConstruct and @PreDestroy over the methods (Spring 2.5 or later)
which is defined in JSR-250.
Life cycle of thread in java
/**
* Java Program to show that, you can not override static method in Java.
* If you declare same method in subclass then, It's known as method hiding.
*
* @author Javin Paul
*/
public class StaticOverrideTest {
public static void main(String args[]) {
Parent p = new Parent();
p.name(); // should call static method from super class (Parent)
// because type of reference variable
// p is Parent
p = new Child();
p.name(); // as per overriding rules this should call to child's static
// overridden method. Since static method can not be overridden
// , it will call parent static method
// because Type of p is Parent.
Child c = new Child();
c.name(); // will call child static method because static method
// get called by type of Class
}
}
class Parent{
/*
* original static method in super class which will be hidden
* in subclass.
*/
public static void name(){
System.out.println("static method from Parent");
}
}
class Child extends Parent{
/*
* Static method with same signature as in super class,
* Since static method can not be overridden, this is called
* method hiding. Now, if you call Child.name(), this method
* will be called, also any call to name() in this particular
* class will go to this method, because super class method is hidden.
*/
public static void name(){
System.out.println("static method from Child");
}
}
Output
static method from Parent
static method from Parent
static method from Child
*.The crosscutting concern is a concern which is applicable throughout the
application and it affects the entire application. For example: logging, security and data
transfer are the concerns which are needed in almost every module of an application,
hence they are cross-cutting concerns.
*. AOP (Aspect oriented programming) is on top of OOP and is specialized in
addressing cross cutting concern and promotes dynamic decoupling.
Default Methods In Java 8
// A simple program to Test Interface default
// methods in java
interface TestInterface
{
// abstract method
public void square(int a);
// default method
default void show()
{
System.out.println("Default Method Executed");
}
}
class TestClass implements TestInterface
{
// implementation of square abstract method
public void square(int a)
{
System.out.println(a*a);
}
public static void main(String args[])
{
TestClass d = new TestClass();
d.square(4);
// default method executed
d.show();
}
}
In summary, Default methods enable us to add new functionality to existing interfaces
without breaking older implementation of these interfaces.
When we extend an interface that contains a default method, we can perform following,
● Not override the default method and will inherit the default method.
● Override the default method similar to other methods we override in subclass..
● Redeclare default method as abstract, which force subclass to override it.
@Bean ApplicationContext
public interface HelloWorld {
void printHelloWorld(String msg);
}
public class HelloWorldImpl implements HelloWorld {
@Override
public void printHelloWorld(String msg) {
System.out.println("Hello : " + msg);
}
}
@Configuration
public class AppConfig {
@Bean(name="helloBean")
@Scope(value=”Prototype”)
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}
public class App {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printHelloWorld("Spring3 Java Config");
}
}
AOP
@Aspect
@Component
public class ExecutionTimeTrackerAdvice {
Logger logger=LoggerFactory.getLogger(ExecutionTimeTrackerAdvice.class);
@Around("@annotation(com.webbot.demo.Advice.TrackExecutionTime)")
public Object trackTime(ProceedingJoinPoint pjp) throws Throwable {
long stratTime=System.currentTimeMillis();
Object obj=pjp.proceed();
long endTime=System.currentTimeMillis();
logger.info("Method name"+pjp.getSignature()+" time taken to execute : "+
(endTime-stratTime)+" ms");
return obj;
}
}
Difference between Java Heap Space and Stack Memory
Based on the above explanations, we can easily conclude following differences
between Heap and Stack memory.
1. Heap memory is used by all the parts of the application whereas stack memory is
used only by one thread of execution.
2. Whenever an object is created, it’s always stored in the Heap space and stack
memory contains the reference to it. Stack memory only contains local primitive
variables and reference variables to objects in heap space.
3. Objects stored in the heap are globally accessible whereas stack memory can’t
be accessed by other threads.
4. Memory management in stack is done in LIFO manner whereas it’s more
complex in Heap memory because it’s used globally. Heap memory is divided
into Young-Generation, Old-Generation etc, more details at Java Garbage
Collection.
5. Stack memory is short-lived whereas heap memory lives from the start till the
end of application execution.
6. We can use -Xms and -Xmx JVM option to define the startup size and maximum
size of heap memory. We can use -Xss to define the stack memory size.
7. When stack memory is full, Java runtime throws java.lang.StackOverFlowError
whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java
Heap Space error.
8. Stack memory size is very less when compared to Heap memory. Because of
simplicity in memory allocation (LIFO), stack memory is very fast when compared
to heap memory.
● Class is a parameterizable class, hence you can use the syntax Class<T> where
T is a type. By writing Class<?>, you're declaring a Class object which can be of
any type (? is a wildcard). The Class type is a type that contains meta-
information about a class.
● Now, you don't need to use @Controller and @RestponseBody annotation,
instead you can use @RestController to provide the same functionality. In
short, it is a convenience controller which combines the behavior of @Controler
and @Response body into one
Method reference.
(args) -> Class.staticMethod(args)
Class::staticMethod
What does flatmap() function do? why you need it? (answer)
The flatmap function is an extension of the map function. Apart from transforming one
object into another, it can also flatten it.
For example, if you have a list of the list but you want to combine all elements of lists
into just one list. In this case, you can use flatMap() for flattening. At the same time, you
can also transform an object like you do use map() function.
By using Optional, we can specify alternate values to return or alternate code to run.
This makes the code more readable because the facts which were hidden are now
visible to the developer.
// Java program with Optional Class
import java.util.Optional;
public class OptionalDemo{
public static void main(String[] args) {
String[] words = new String[10];
Optional<String> checkNull = Optional.ofNullable(words[5]);
if (checkNull.isPresent()) {
String word = words[5].toLowerCase();
System.out.print(word);
} else
System.out.println("word is null");
}
}
@RequestBody
Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or
domain object, enabling automatic deserialization of the inbound HttpRequest body onto
a Java object.
First, let's have a look at a Spring controller method:
@PostMapping("/request")
public ResponseEntity postController(
@RequestBody LoginForm loginForm) {
exampleService.fakeAuthenticate(loginForm);
return ResponseEntity.ok(HttpStatus.OK);
}
Spring automatically deserializes the JSON into a Java type assuming an appropriate
one is specified. By default, the type we annotate with the @RequestBody annotation
must correspond to the JSON sent from our client-side controller:
public class LoginForm {
private String username;
private String password;
// ...
}
@ResponseBody
The @ResponseBody annotation tells a controller that the object returned is
automatically serialized into JSON and passed back into the HttpResponse object.
Suppose we have a custom Response object:
public class ResponseTransfer {
private String text;
// standard getters/setters
}
Next, the associated controller can be implemented:
@Controller
@RequestMapping("/post")
public class ExamplePostController {
@Autowired
ExampleService exampleService;
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(
@RequestBody LoginForm loginForm) {
return new ResponseTransfer("Thanks For Posting!!!");
}
}
In the developer console of our browser or using a tool like Postman, we can see the
following response:
{"text":"Thanks For Posting!!!"}
● Fortify is used to look for security vulnerability.
Rest Template
public class SpringRestTemplateExample {
public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
Country bhutan = restTemplate
.getForObject("http://localhost:8080/SpringRestfulWebServicesCRUDExample/
country/{id}", Country.class,2);
System.out.println("Country Name:"+bhutan.getCountryName());
System.out.println("Population:"+bhutan.getPopulation());
}
}