| Parameter | STACK | HEAP | 
| Basic | Memory is allocated in a contiguous
  block. | Memory is allocated in any random
  order. | 
| Allocation and De-allocation | Automatic by compiler instructions. | Manual by the programmer. | 
| Cost | Less | More | 
| Implementation | Easy | Hard | 
| Access time | Faster | Slower | 
| Main Issue | Shortage of memory | Memory fragmentation | 
| Locality of reference | Excellent | Adequate | 
| Safety | Thread safe, data stored can only be
  accessed by owner | Not Thread safe, data stored visible
  to all threads | 
| Flexibility | Fixed-size | Resizing is possible | 
| Data type structure | Linear | Hierarchical | 
| Preferred | Static memory allocation is preferred
  in array. | Heap memory allocation is preferred in
  the linked list. | 
| Size | Small than heap memory. | Larger than stack memory. | 
| Spring IoC
  (Inversion of Control) | Spring
  Dependency Injection | 
| Spring IoC Container is the core of Spring Framework. It
  creates the objects, configures and assembles their dependencies, manages
  their entire life cycle. | Spring Dependency injection is a way to inject the
  dependency of a framework component by the following ways of spring:
  Constructor Injection and Setter Injection | 
| Spring helps in creating objects, managing objects,
  configurations, etc. because of IoC (Inversion of Control).  | Spring framework helps in the creation of
  loosely-coupled applications because of Dependency Injection. | 
| Spring IoC is achieved through Dependency Injection. | Dependency Injection is the method of providing the
  dependencies and Inversion of Control is the end result of Dependency
  Injection. | 
| IoC is a design principle where the control flow of the
  program is inverted. | Dependency Injection is one of the subtypes of the IOC
  principle.   | 
| Aspect-Oriented Programing is one way to implement Inversion of Control. | In case of any changes in business requirements, no code
  change is required. | 
| package play1;   import java.util.HashSet; import java.util.Set;   public class Player1 {       private Integer
  id;     private String
  name;     private Integer
  age;       public String
  getName() {        
  return name;     }     public void
  setName(String name) {        
  this.name = name;     }     public Integer
  getAge() {        
  return age;     }     public void
  setAge(Integer age) {        
  this.age = age;     }     public Integer
  getId() {        
  return id;     }     public void
  setId(Integer id) {        
  this.id = id;     }     @Override     public int
  hashCode() {        
  int hash = 3;   
       hash = 7 * hash + this.name.hashCode();        
  hash = 7 * hash + this.age.hashCode();        
  hash = 7 * hash + this.id.hashCode();        
  return hash;     }       public String
  toString() {        
  return "Alpha : " + id;     }       @Override     public boolean
  equals(Object object) {        
  boolean result = false;        
  if (object == null || object.getClass() != getClass()) {            
  result = false;        
  } else {            
  Player1 tiger = (Player1) object;            
  if (this.id == tiger.getId()) {                
  result = true;            
  }        
  }        
  return result;     }       public
  Player1(Integer color, String stripePattern, Integer height) {       
   this.id = color;        
  this.name = stripePattern;        
  this.age = height;       }       public static
  void main(String[] args) {        
  Set s = new HashSet();        
  Player1 a1 = new Player1(1, "John", 24);        
  Player1 a2 = new Player1(2, "jack", 25);        
  Player1 a3 = new Player1(3, "John", 24);        
  s.add(a1);        
  s.add(a2);        
  s.add(a3);        
  System.out.println(s.size());        
  for (Player1 val: s) {            
  System.out.println(val.getName());        
  }     }   } | 
How to create Immutable
class in Java?
•                     The class must be declared as final (So that
child classes can’t be created)
•                     Data members in the class must be declared as
final (So that we can’t change the value of it after object creation)
•                     A parameterized constructor
•                     Getter method for all the variables in it
•                     No setters(To not have the option to change the
value of the instance variable)
| // An immutable class public final class Student {     final String
  name;     final int
  regNo;       public Student(String
  name, int regNo)     {        
  this.name = name;        
  this.regNo = regNo;     }     public String
  getName()     {        
  return name;     }     public int
  getRegNo()     {        
  return regNo;     } }   // Driver class class Test {     public static
  void main(String args[])     {        
  Student s = new Student("ABC", 101);        
  System.out.println(s.getName());        
  System.out.println(s.getRegNo());          
  // Uncommenting below line causes error        
  // s.regNo = 102;     } } Output: ABC 101 | 
User-defined Custom
Exception in Java
| / A Class that represents
  use-defined expception class MyException extends
  Exception {     public
  MyException(String s)     {        
  // Call constructor of parent Exception        
  super(s);     } }   // A Class that uses above
  MyException public class Main {     // Driver
  Program     public static
  void main(String args[])     {        
  try        
  {            
  // Throw an object of user defined exception            
  throw new MyException("GeeksGeeks");        
  }        
  catch (MyException ex)        
  {            
  System.out.println("Caught");              
  // Print the message from MyException object            
  System.out.println(ex.getMessage());        
  }     } } | 
 
Sort a String in Java
| import java.util.Arrays; import java.util.Comparator;   public class GFG {     // Method to
  sort a mixed string     public static
  String sortString(String inputString)     {        
  // convert input string to Character array        
  Character tempArray[] = new Character[inputString.length()];        
  for (int i = 0; i < inputString.length(); i++) {            
  tempArray[i] = inputString.charAt(i);        
  }                            
  // Sort, ignoring case during sorting        
  Arrays.sort(tempArray, new Comparator(){              
  @Override            
  public int compare(Character c1, Character c2)            
  {                
  // ignoring case                
  return Character.compare(Character.toLowerCase(c1),                                        
  Character.toLowerCase(c2));            
  }        
  });                  
  // using StringBuilder to convert Character array to String        
  StringBuilder sb = new StringBuilder(tempArray.length);        
  for (Character c : tempArray)            
  sb.append(c.charValue());          
  return sb.toString();     }           // Driver
  method     public static
  void main(String[] args)     {        
  String inputString = "GeeksforGeeks";        
  String outputString = sortString(inputString);                  
  System.out.println("Input String : " + inputString);        
  System.out.println("Output String : " + outputString);     }   }   | 
Comparable
| // A Java program to demonstrate
  use of Comparable import java.io.*; import java.util.*;   // A class 'Movie' that implements
  Comparable class Movie implements Comparable {     private double
  rating;     private String
  name;     private int
  year;       // Used to sort
  movies by year     public int
  compareTo(Movie m)     {        
  return this.year - m.year;     }       // Constructor     public
  Movie(String nm, double rt, int yr)     {        
  this.name = nm;        
  this.rating = rt;        
  this.year = yr;     }       // Getter
  methods for accessing private data     public double
  getRating() { return rating; }     public String
  getName()   {  return name; }     public int
  getYear()      {  return year;  } }   // Driver class class Main {     public static
  void main(String[] args)     {        
  ArrayList list = new ArrayList();        
  list.add(new Movie("Force Awakens", 8.3, 2015));        
  list.add(new Movie("Star Wars", 8.7, 1977));        
  list.add(new Movie("Empire Strikes Back", 8.8, 1980));        
  list.add(new Movie("Return of the Jedi", 8.4, 1983));          
  Collections.sort(list);          
  System.out.println("Movies after sorting : ");        
  for (Movie movie: list)        
  {            
  System.out.println(movie.getName() + " " +                               
  movie.getRating() + " " +                               
  movie.getYear());        
  }     } } | 
| Output: Movies after sorting : Star Wars 8.7 1977 Empire Strikes Back 8.8 1980 Return of the Jedi 8.4 1983 Force Awakens 8.3 2015 | 
 
Comparable
| //A Java program to demonstrate
  Comparator interface import java.io.*; import java.util.*;   // A class 'Movie' that implements
  Comparable class Movie implements Comparable {     private double
  rating;     private String
  name;     private int
  year;       // Used to sort
  movies by year     public int
  compareTo(Movie m)     {        
  return this.year - m.year;     }       // Constructor     public
  Movie(String nm, double rt, int yr)     {        
  this.name = nm;        
  this.rating = rt;        
  this.year = yr;     }       // Getter
  methods for accessing private data     public double
  getRating() { return rating; }     public String
  getName()   {  return name; }     public int
  getYear()      {  return year;  } }   // Class to compare Movies by
  ratings class RatingCompare implements
  Comparator {     public int
  compare(Movie m1, Movie m2)     {        
  if (m1.getRating() < m2.getRating()) return -1;        
  if (m1.getRating() > m2.getRating()) return 1;        
  else return 0;     } }   // Class to compare Movies by name class NameCompare implements
  Comparator {     public int
  compare(Movie m1, Movie m2)     {        
  return m1.getName().compareTo(m2.getName());     } }   // Driver class class Main {     public static
  void main(String[] args)     {        
  ArrayList list = new ArrayList();        
  list.add(new Movie("Force Awakens", 8.3, 2015));        
  list.add(new Movie("Star Wars", 8.7, 1977));        
  list.add(new Movie("Empire Strikes Back", 8.8, 1980));        
  list.add(new Movie("Return of the Jedi", 8.4, 1983));          
  // Sort by rating : (1) Create an object of ratingCompare        
  //                 
  (2) Call Collections.sort        
  //                 
  (3) Print Sorted list        
  System.out.println("Sorted by rating");        
  RatingCompare ratingCompare = new RatingCompare();        
  Collections.sort(list, ratingCompare);       
   for (Movie movie: list)            
  System.out.println(movie.getRating() + " " +                               
  movie.getName() + " " +                               
  movie.getYear());            
  // Call overloaded sort method with RatingCompare      
    // (Same three steps as above)        
  System.out.println("\nSorted by name");        
  NameCompare nameCompare = new NameCompare();        
  Collections.sort(list, nameCompare);        
  for (Movie movie: list)            
  System.out.println(movie.getName() + " " +                               
  movie.getRating() + " " +                               
  movie.getYear());          
  // Uses Comparable to sort by year        
  System.out.println("\nSorted by year");        
  Collections.sort(list);        
  for (Movie movie: list)            
  System.out.println(movie.getYear() + " " +                               
  movie.getRating() + " " +                               
  movie.getName()+" ");     } }  | 
| Output : | 
Bubble Sort in string
| 
 | 
List<String> locations =
Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");
| HashMap | HashMap
  is the implementation of Map, but it doesn't maintain any order. | 
| LinkedHashMap | LinkedHashMap
  is the implementation of Map. It inherits HashMap class. It maintains
  insertion order. | 
| TreeMap | TreeMap
  is the implementation of Map and SortedMap. It maintains ascending order. | 
| Access Modifier | within class | within package | outside package by subclass only | outside package | 
| Private | Y | N | N | N | 
| Default | Y | Y | N | N | 
| Protected | Y | Y | Y | N | 
| Public | Y | Y | Y | Y | 
|   |   | 
| String[] GetSourceArgs() | Gives u  nprocessed arguments that were
  passed to the application | 
| Set<String> getOptionNames() | Names of all optional arguments, optional
  arguments are preceded by “—“ eg: –name= “stacktrace” | 
| List<String> getNonOptionArgs() | Returns unprocessed non-optional arguments.
  Arguments without “—“ | 
| boolean containsOption(String
  name)  | Checks if name is present in the optional
  arguments or not | 
| List<String> getOptionValues(String
  name) | Gives the argument value by name | 
3. Spring boot Application events -@EventListener
| No. | Key | Concurrent hash map | Synchronized hashmap | 
| 1 | Implementation | It is a class that implements a Concurrent hash map and
  serializable interface. | It is a method in Collection class.  | 
| 2 | Lock mechanism | Locks the portion | Locks the whole map.  | 
| 3 | Performance | Concurrent hashmap allows concurrent read and write. So
  performance is relatively better than a synchronized map.  | Multiple threads can't access the map concurrently. So,
  performance is relatively less than a concurrent hash map. | 
| 4 | Null key | It doesn't allow null as a key or value.  | It allows null as a key. | 
| 5  | Concurrent modification exception | It doesn't throw concurrent modification exception.  | Iterator return by synchronized map throws concurrent
  modification exception | 
| //Generate -n-random-numbers-whose-sum-is-m public static double[] getRandDistArray(int n, double m) { double randArray[] = new double[n]; double sum = 0; // Generate n random numbers for (int i = 0; i < randArray.length; i++) { randArray[i] = Math.random(); sum += randArray[i]; } // Normalize sum to m for (int i = 0; i < randArray.length; i++) { randArray[i] /= sum; randArray[i] *= m; } return randArray; } getRandDistArray(5, 1.0) | 
When to use Stream.of()  and Arrays.stream()
Passing an integer array, the Stream.of() method returns Stream whereas
Arrays.stream() returns an IntStream
· * Different return types:
For primitives arrays (like int[], long[] char[]), Arrays.stream() and Stream.of() have different return types.·        *  Stream.of() needs flattening whereas
Arrays.stream() does not
IntStream intStreamNew =
stream.flatMapToInt(Arrays::stream);
·        * Stream.of() is generic whereas Arrays.stream is not:
| Sr. No. | Key | Object Level Lock | Class Level Lock | 
| 1 | Basic  | It can
  be used when you want non-static method or non-static block of the code
  should be accessed by only one thread | It can
  be used when we want to prevent multiple threads to enter the synchronized
  block in any of all available instances on runtime | 
| 2 | Static/Non Static  | It should always be used
  to make non-static data thread safe.  | It should always be used
  to make static data thread safe.  | 
| 3 | Number
  of Locks  | Every
  object the class may have their own lock | Multiple
  objects of class may exist but there is always one class’s class object lock
  available | 
| package com.journaldev.design.builder; public class Computer { //required parameters private String HDD; private String RAM; //optional parameters private boolean isGraphicsCardEnabled; private boolean isBluetoothEnabled; public String getHDD() { return HDD; } public String getRAM() { return RAM; } public boolean isGraphicsCardEnabled() { return isGraphicsCardEnabled; } public boolean isBluetoothEnabled() { return isBluetoothEnabled; } private Computer(ComputerBuilder builder) { this.HDD=builder.HDD; this.RAM=builder.RAM; this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled; this.isBluetoothEnabled=builder.isBluetoothEnabled; } //Builder Class public static class ComputerBuilder{ // required parameters private String HDD; private String RAM; // optional parameters private boolean isGraphicsCardEnabled; private boolean isBluetoothEnabled; public ComputerBuilder(String hdd, String ram){ this.HDD=hdd; this.RAM=ram; } public ComputerBuilder setGraphicsCardEnabled(Boolean isGraphicsCardEnabled) { this.isGraphicsCardEnabled = isGraphicsCardEnabled; return this; } public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) { this.isBluetoothEnabled = isBluetoothEnabled; return this; } public Computer build(){ return new Computer(this); } } } | 
| Shallow
  Copy | Deep
  Copy | 
| Cloned
  Object and original object are not 100% disjoint. | Cloned
  Object and original object are 100% disjoint. | 
| Any
  changes made to cloned object will be reflected in original object or vice
  versa. | Any
  changes made to cloned object will not be reflected in original object or
  vice versa. | 
| Default
  version of clone method creates the shallow copy of an object. | To
  create the deep copy of an object, you have to override clone method. | 
| Shallow
  copy is preferred if an object has only primitive fields. | Deep
  copy is preferred if an object has references to other objects as fields. | 
| Shallow
  copy is fast and also less expensive. | Deep
  copy is slow and very expensive | 
// Loop over the array
for (int i = 0; i < array.Length; i++) {
    // If we've found a new highest number...
    if (array[i] > highest) {
        // ...shift the current highest number to second highest
        secondHighest = highest;
        // ...and set the new highest.
        highest = array[i];
    } else if (array[i] > secondHighest)
        // Just replace the second highest
        secondHighest = array[i];
    }
}
// After exiting the loop, secondHighest now represents the second
// largest value in the arraypublic static int secondLargestNumberInArray(int[] numbers) {
    Integer[] arr = new Integer[numbers.length];
    Arrays.setAll(arr, i -> numbers[i]);
    return Arrays.stream(arr).sorted(Collections.reverseOrder()).skip(1).findFirst().get();
}
| Type | Method | Description | 
| T | This method returns the value in the current thread's copy of
  this thread-local variable. | |
| void | This method sets the current thread's copy of this
  thread-local variable to the specified value. | |
| void | This method removes the current thread's value for this
  thread-local variable. | |
| protected T | This method returns the current thread's initial value for
  this thread-local variable. | 
| 
  | 
ThreadLocalThe TheadLocal construct allows us to store data that will be accessible only by a specific thread.
| ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>(); threadLocalValue.set(1); Integer result = threadLocalValue.get(); ThreadLocal<Integer> threadLocal =ThreadLocal.withInitial(() -> 1); threadLocal.remove(); public
  class ThreadLocalWithUserContext implements Runnable {    
  private static ThreadLocal<Context> userContext = new
  ThreadLocal<>();    
  private Integer userId;    
  private UserRepository userRepository = new UserRepository();    
  @Override    
  public void run() {        
  String userName = userRepository.getUserNameForUserId(userId);        
  userContext.set(new Context(userName));        
  System.out.println("thread context for given userId: " + userId +
  " is: " +userContext.get());    
  }    
  // standard constructor } ThreadLocalWithUserContext
  firstUser   = new ThreadLocalWithUserContext(1); ThreadLocalWithUserContext
  secondUser   =  new ThreadLocalWithUserContext(2); new
  Thread(firstUser).start(); new
  Thread(secondUser).start(); ThreadLocal and ThreadPool 
 | 
-----------------------------------------------------------------------------------------
| package net.javaguides.spring.scope; public interface MessageService { String getMessage(); void setMessage(String message); } @Component @Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class TwitterMessageService implements MessageService { private String message; @Override public String getMessage() { return message; } @Override public void setMessage(String message) { this.message = message; } } package net.javaguides.spring.scope; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages= "net.javaguides.spring") Public class AppConfig { } package net.javaguides.spring.scope; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Application { public static void main(String[] args) { context = new AnnotationConfigApplicationContext(AppConfig.class); MessageService messageService = context.getBean(MessageService.class); messageService.setMessage("TwitterMessageServiceImplementation"); System.out.println(messageService.getMessage()); MessageService messageService1 = context.getBean(MessageService.class); System.out.println(messageService1.getMessage()); context.close(); } } TwitterMessageService Implementation null | 
| public class Livelock { static class Spoon { private Diner owner; public Spoon(Diner d) { owner = d; } public Diner getOwner() { return owner; } public synchronized void setOwner(Diner d) { owner = d; } public synchronized void use() { System.out.printf("%s has eaten!", owner.name); } } 
 | 
| abstract class Diagram { double dim1; double dim2; Diagram(double a, double b) { dim1 = a; dim2 = b; } // area is now an abstract method abstract double area(); } class Rectangle extends Diagram { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Diagram { Triangle(double a, double b) { super(a, b); } // override area for triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } public class Test { public static void main(String args[]) { // Diagram d = new Diagram(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Diagram diagRef; // This is OK, no object is created diagRef = r; System.out.println("Area of Rectangle is: " + diagRef.area()); diagRef = t; System.out.println("Area of Triangle is:" + diagRef.area()); } } | 
| Inside Area for Rectangle. Area of Rectangle is: 45.0 Inside Area for Triangle. Area of Triangle is:40.0 | 
public class MyCustomException extends RuntimeException { public MyCustomException(String message) { super(message); } }
| Spring | Spring
  Boot | 
| Widely used for building
  enterprise Java applications | Widely used for building REST APIs | 
| Aims to simplify enterprise Java
  development | Aims to shorten code length and
  easily build web applications | 
| Allows building loosely coupled
  applications | Allows building standalone
  applications | 
| Main feature is dependency
  injection | Main feature is auto-configuration | 
| Involves writing lots of boilerplate
  code | Reduces boilerplate code | 
| Needs dependencies to be defined
  manually | Starters take care of dependencies | 
| Involves setting up server
  manually | Includes embedded server like
  Tomcat and Jetty | 
| 200 |  OK | 
| 201
   | Created | 
| 202
   | Accepted | 
| 204
   | No
  Content | 
| 301
   | Moved
  Permanently | 
| 304
   | Not
  Modified | 
| 307
   | Temporary
  Redirect | 
| 400
   | Bad
  Request | 
| 401
   | Unauthorized | 
| 402
   | Payment
  Required | 
| 403
   | Forbidden | 
| 404
   | Not
  Found | 
| 405 |  Method Not Allowed | 
| 500
   | Internal
  Server Error | 
| 501
   | Not
  Implemented | 
| 502
   | Bad
  Gateway | 
| 503
   | Service
  Unavailable | 
| ClassNotFoundException | NoClassDefFoundError | 
| It is an
  exception. It is of type java.lang.Exception. | It is an
  error. It is of type java.lang.Error. | 
| It occurs
  when an application tries to load a class at run time which is not updated in
  the classpath. | It occurs
  when java runtime system doesn’t find a class definition, which is present at
  compile time, but missing at run time. | 
| It is thrown
  by the application itself. It is thrown by the methods like Class.forName(),
  loadClass() and findSystemClass(). | It is thrown
  by the Java Runtime System. | 
| It occurs
  when classpath is not updated with required JAR files. | It occurs
  when required class definition is missing at runtime. | 
| Authentication | Authorization | 
| Authentication is the process of identifying a user to provide access to a system. | Authorization is the
  process of giving permission to access the resources. | 
| In this, the user or
  client and server are verified. | In this, it is
  verified that if the user is allowed through the defined policies and rules. | 
| It is usually
  performed before the authorization. | It is usually done
  once the user is successfully authenticated. | 
| It requires the
  login details of the user, such as user name & password, etc. | It requires the
  user's privilege or security level. | 
| Data is provided
  through the Token Ids. | Data is provided
  through the access tokens. | 
| Example: Entering Login details is necessary
  for the employees to authenticate themselves to access the organizational
  emails or software. | Example: After employees successfully
  authenticate themselves, they can access and work on certain functions only
  as per their roles and profiles. | 
| Authentication
  credentials can be partially changed by the user as per the requirement. | Authorization
  permissions cannot be changed by the user. The permissions are given to a
  user by the owner/manager of the system, and he can only change it. | 
| Volatile Keyword | Synchronization Keyword | 
| Volatile keyword is a field modifier. | Synchronized keyword modifies code blocks and methods. | 
| The thread cannot be blocked for waiting in case of volatile. | Threads can be blocked for waiting in case of synchronized. | 
| It improves thread performance. | Synchronized methods degrade the thread performance. | 
| It synchronizes the value of one variable at a time between thread memory and main memory. | It synchronizes the value of all variables between thread memory and main memory. | 
| Volatile fields are not subject to compiler optimization. | Synchronize is subject to compiler optimization. | 
BeanNameAware, Spring passes the bean’s ID to the setBeanName() method.BeanFactoryAware, Spring calls the setBeanFactory() method, passing in the bean factory itself.ApplicationContextAware, Spring calls the setApplicationContext() method, passing in a reference to the enclosing application context.BeanPostProcessor interface, Spring calls its postProcessBeforeInitialization() method.InitializingBean interface, Spring calls its afterPropertiesSet() method. Similarly, if the bean was declared with an init-method, then the specified initialization method is called.BeanPostProcessor, Spring calls its postProcessAfterInitialization() method.DisposableBean interface, Spring calls its destroy() method. Likewise, if the bean was declared with a destroy-method, the specified method is called.