IQ, Java

Java Interview Questions

|
Divnesh BLOG
Java Interview Questions

Java Statements
Java statements are instructions that tell the programming language what to do. A basic statement, like an assignment statement, assigns a value to a variable, as shown in this image:
double entryFee = 15.75;
All Java statements must end in a semicolon (;). This tells Java that it should attempt to process all information up to that semicolon.
----------------------------------------------------------------------------------------------------------------
Types of Java Statement
Control-flow statements determine the order that statements are executed.
Declaration statements declare variables.
Expression statements change values of variables, call methods, and create objects
----------------------------------------------------------------------------------------------------------------
Why Java is platform independent.
C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent. Java uses compiler and interpreter both. Java source code is converted into bytecode at compilation time.  Java is interpreted that is why it is platform independent.
----------------------------------------------------------------------------------------------------------------
JAR
   A JAR is a package file format typically used to aggregate many Java class files and associated metadata and resources into one file for distribution. It is used to store classes of java created by the user in order to help the runnable and inference concepts embedded within the language.
----------------------------------------------------------------------------------------------------------------
Java Native Interface
   The Java Native Interface is a foreign function interface programming framework that enables Java code running in a Java virtual machine to call and be called by native applications and libraries written in other languages such as C, C++ and assembly.
----------------------------------------------------------------------------------------------------------------
JVMruns Java on a device
JDK is a software development package used to create tools that can be run on phones and tablets.
----------------------------------------------------------------------------------------------------------------
What is serialization?
   Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. ... 
To make a Java object serializable we implement the java.io.Serializable interface
private static final long serialversionUID = 129348938L; 
----------------------------------------------------------------------------------------------------------------
Why there are some null interface in java? What does it mean? Give me some null interfaces in JAVA?
    Null interface is another name for marker interface. Such an interface is empty, i.e. without any method declarations and do not have function declarations in them, they are empty interfaces, this is to convey the compiler that they have to be treated differently
eg : Serializable , Cloneable 
----------------------------------------------------------------------------------------------------------------
Is synchronized a modifier?identifier??what is it??
    It's a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods
----------------------------------------------------------------------------------------------------------------
Is Iterator a Class or Interface? What is its use?
    Iterator is an interface. It is not a class. It is used to iterate through each and every element in a list. Iterator is implemented Iterator design pattern.
----------------------------------------------------------------------------------------------------------------
What is transient variable
    transient is a Java keyword which marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes
----------------------------------------------------------------------------------------------------------------
Is string a wrapper class?
   String is not a wrapper class, simply because there is no parallel primitive type that it wraps. A string is a representation of a char sequence but not necessarily a 'wrapper'. Autoboxing and unboxing for example do not apply to String. But they do apply to primitives such as int long etc.
----------------------------------------------------------------------------------------------------------------
Comparable provides compareTo method, Comparator provides compare method declaration
interface is used for multiple sorting Comparator


----------------------------------------------------------------------------------------------------------------
use of Adapter classes in Java
Adapter classes are used to provide default implementation of the available listeners in java. So as to reduce the overhead of providing implementation of all the methods in the Listener interface.
----------------------------------------------------------------------------------------------------------------
Listener interface in java?
ActionListener
ItemListener
MouseListener
----------------------------------------------------------------------------------------------------------------
static methods can be overloaded but cannot be overridden.

Class extends (1)
Interface implements(multiple) 
----------------------------------------------------------------------------------------------------------------
StringBuilder & StringBuffer
Both StringBuilder and StringBuffer are mutable. StringBuilder is not thread safe (not  synchronized ) but   StringBuffer is thread safe (synchronized
Both uses heap memory
----------------------------------------------------------------------------------------------------------------
Type of lambda expressions? 
        functional interface 
eg : Runnable,Callable, Comparable
Uses:
they are a way to replace anonymous classes
it helps in the implementation of functional interfaces
it uses target typing to infer the type of arguments
----------------------------------------------------------------------------------------------------------------
In Heap are objects stored in JVM?
String s1;
String literals are stored in only String pool unlike String objects.
----------------------------------------------------------------------------------------------------------------
Generics are type safe
ArrayList a1=new ArrayList();
It allows only String to be stored in this case.
----------------------------------------------------------------------------------------------------------------
Oops concepts in java?
Encapsulation
Inheritance
Polymorphism
Abstraction
----------------------------------------------------------------------------------------------------------------
Encapsulation?
    wraps the data into single unit. It provide security and we can modify easily
Polymorphism?
    It has many method with same name.Its used to avoid naming complexcity.
Inheritance?
     It is used for Resusability
Abstraction?
    Hide the data and showing essential details only
----------------------------------------------------------------------------------------------------------------
Types of Polymorphism?
  • Static or comple time polymorphism.
    • Example : method Overloading
  • Dynamic or runtime polymorphism.
    • Example : method Overring
----------------------------------------------------------------------------------------------------------------
Difference between overload and override?
Overload means same method name with different parameter in a single class.
Override means same method in a parent and child class
----------------------------------------------------------------------------------------------------------------
How many types of relationshilp in java?
IS_A example inheritace (Customer – Regular C/Premier C)
HAS_A example Aggrigation (Customer – Address.Area)
USES_A example Association (CalculateBill(List Product))
----------------------------------------------------------------------------------------------------------------
Inheritance?
Reusability.Derived the data from parent class to child class
----------------------------------------------------------------------------------------------------------------
States of a thread?
Initial
Runnable
Waiting
Blocked
Terminated
----------------------------------------------------------------------------------------------------------------
“final” keyword?
Final keyword is used in three situations:
  • Value of a data member that is declared as final cannot be changed.
  • A method that is declared as final cannot be overridden.
  • A class that has been declared as final cannot be subclassed.
----------------------------------------------------------------------------------------------------------------
When you should we extend Thread class and when we should implement Runnable interface?
Extend Thread class
Implement Runnable interface.
Generally if want to only implement run() method we should go for Runnable interface( Runnable has only one method: run()). Implementing Runnable helps the class to extend some other class.
If we want to override other0 methods( apart from run() )of Thread class then we should extend Thread class.
----------------------------------------------------------------------------------------------------------------
differences between Java and C++?
There are no pointers in Java.
Java does not support multiple inheritance
----------------------------------------------------------------------------------------------------------------
Interface Uses
Interfaces is used replacement of multiple inheritance
In interface we will defining the methods that action is going to perform
In the implementation class we will overriding all the methods and write the logic
----------------------------------------------------------------------------------------------------------------
OOps real life examples
Polymorphism is in which we can identified by one action has different forms, Suppose talking is the feature given god to humans, but for animals the way of communication will be different
Abstraction is the process in which we can relate it with phone, We are able to dial the numbers but what happening inside we exactly don’t know
Encapsulation - Making an entity into single unit, Suppose we have a pack of biscuit, But biscuit is made up of different ingredients, like wheat, vanilla, etc
Inheritance= Inheritance is the concept in which we can compare the relationship between parent and child, A child have two set of 23 chromosomes which is from parents.
----------------------------------------------------------------------------------------------------------------
difference between interface and abstract method?
A class can implement any number of interfaces – a class can extend only one abstract class.
All methods in interface are public - methods in abstract class can have any access level
Methods in interface cannot have body – there can be methods with body in abstract class.
----------------------------------------------------------------------------------------------------------------
Object are passed by reference and primitive data items are passed by value.
----------------------------------------------------------------------------------------------------------------
achieve polymorphism?
You can overload the methods and constructors to achieve overloading.
----------------------------------------------------------------------------------------------------------------
Can we extend more than class?
No we can’t extend more than one class
----------------------------------------------------------------------------------------------------------------
Can we implement more than one interface?
Yes we can implement more than one interface.
----------------------------------------------------------------------------------------------------------------
Subclass: In inheritance, the class that inherits properties from parent class is a subclass.
Inner class: An inner class is a class which is a member of another class. There are 4 types of inner classes:
Nested inner class
Static nested class
Local inner class
Anonymous inner class
----------------------------------------------------------------------------------------------------------------
Access Modefiers:

Public: class, sub-class, package, everywhere
Protected: class, sub-class, package
Default: class, package
Private: class
----------------------------------------------------------------------------------------------------------------
Create singleton class with syncronized block
class SingletonClassExample   
{   
// static variable s of type Singleton   
private static Singleton s = null;   
public String str;   
//private constructor of the Singleton class that restricted to this class itself   
private Singleton()   
{   
str = "it is an example of singleton class.";   
}   
//static method to create an instance of the Singleton class   
// we can also create a method with the same name as the class name  
public static Singleton getInstance()   
{   
//lazy initialization  
             synchronized (SingletonClassExample.class){
if (s== null)   
s = new SingletonClassExample();   
return s;   
            }
}   
}  
----------------------------------------------------------------------------------------------------------------
STACK vs HEAP

Stack : 
  • Startup : The stack memory : physical space (in RAM) allocated to each thread at run time. It is created when a thread creates. 
  • Memory management : LIFO (Last-In-First-Out) order because it is accessible globally. 
  • Stores :  variables, references to objects, and partial results
  • lifecycle : Memory allocated to stack lives until the function returns. 
  • Error : If there is no space for creating the new objects, it throws the java.lang.StackOverFlowError. 
  • The scope of the elements is limited to their threads. The JVM creates a separate stack for each thread.
Heap : 
  • Startup : It is created when the JVM starts up and used by the application as long as the application runs. 
  • Store :  objects and JRE classes. Whenever we create objects it occupies space in the heap memory while the reference of that object creates in the stack.
  • Memory management :  It does not follow any order like the stack. It dynamically handles the memory blocks. It means, we need not to handle the memory manually. For managing the memory automatically, Java provides the garbage collector that deletes the objects which are no longer being used. 
  • lifecycle : Memory allocated to heap lives until any one event, either program terminated or memory free does not occur. The elements are globally accessible in the application. It is a common memory space shared with all the threads. 
  • Error : If the heap space is full, it throws the java.lang.OutOfMemoryError

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.

----------------------------------------------------------------------------------------------------------------
OutOfMemoryError Example

// Java program to illustrate
// Heap error
import java.util.*;
public class Heap {
    static List<String> list = new ArrayList<String>();
 
    public static void main(String args[]) throws Exception
    {
        Integer[] array = new Integer[10000 * 10000];
    }
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at Heap.main(Heap.java:11)
----------------------------------------------------------------------------------------------------------------
What  is StackOverflowError?
 StackOverflowError is that we haven’t provided the proper terminating condition to our recursive function 
 
 public class StackOverflowErrorClass {
    static int i = 0;
    // Method to print numbers
    public static int printNumber(int x)
    {
        i = i + 2;
        System.out.println(i);
        return i + printNumber(i + 2);
    }
    public static void main(String[] args)
    {
        // Recursive call without any
        // terminating condition
        StackOverflowErrorClass.printNumber(i);
    }
}
Output : RunTime Error in java code :- Exception in thread “main” java.lang.StackOverflowError
----------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------


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.

----------------------------------------------------------------------------------------------------------------

Set: Add a Object to set without duplicates

 

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 :
Sorted by rating
8.3 Force Awakens 2015
8.4 Return of the Jedi 1983
8.7 Star Wars 1977
8.8 Empire Strikes Back 1980

Sorted by name
Empire Strikes Back 8.8 1980
Force Awakens 8.3 2015
Return of the Jedi 8.4 1983
Star Wars 8.7 1977

Sorted by year
1977 8.7 Star Wars
1980 8.8 Empire Strikes Back
1983 8.4 Return of the Jedi
2015 8.3 Force Awakens

Bubble Sort in string


public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);
    String tempStr;
    System.out.print("Enter the strings > ");
    String s1 = new String(reader.nextLine());
    String[] t1 = s1.split(", ");

    for (int t = 0; t < t1.length - 1; t++) {
        for (int i= 0; i < t1.length - t -1; i++) {
            if (t1[i+1].compareTo(t1[i])<0) {
                tempStr = t1[i];
                t1[i] = t1[i + 1];
                t1[i + 1] = tempStr;
            }
        }
    }
    for (int i = 0; i < t1.length; i++) {
        System.out.println(t1[i]);
    }
}


List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");

Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
--------------------------------------------------------------------------------------------------------------
Java collections

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).



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

  • Stack : LIFO
  • Queue :FIFOa
  • Vector : syncronized same as arraylist
  • Set : Interface in Java is present in java.util package
  • Map : A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys. A Map is useful if you have to search, update or delete elements on the basis of a key.
----------------------------------------------------------------------------------------------------------------
Collusion in hashmap
a hash code collision in a HashMap, is a situation where two or more key objects produce the same final hash value

----------------------------------------------------------------------------------------------------------------
Autoboxing and unboxing
The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. This is the new feature of Java5

----------------------------------------------------------------------------------------------------------------

Java 8 feature

  • Lambda expressions,
  • Method references,
  • Functional interfaces,
  • Stream API,
  • Default methods,
  • Base64 Encode Decode,
  • Static methods in interface,
  • Optional class,
  • Collectors class,
----------------------------------------------------------------------------------------------------------------

Method to create a java object

  • Using new keywd
  • newinstance
    • classname.class.newinstacce
  • getconstructor of newinstance
    • Constructor<classame> obj=classame.class.getConstriuctor()
    • obj.newinstace
  • clone
  • serialization and deserialization
----------------------------------------------------------------------------------------------------------------

Types of memory

  • Class(Method) Area
  • Heap
  • Stack
  • Program Counter Register
  • Native Method Stack
----------------------------------------------------------------------------------------------------------------
Design Principle

SOLID

        S - Single-responsiblity Principle
        O - Open-closed Principle
        L - Liskov Substitution Principle
        I - Interface Segregation Principle
        D - Dependency Inversion Principle

S - Book - bookprinter

O - classes should be open for extension, but closed for modification. 
public class SuperCoolGuitarWithFlames extends Guitar {
 
L - if class A is a subtype of class B, then we should be able to replace B with A without disrupting the behavior of our program.

I - larger interfaces should be split into smaller ones. By doing so, we can ensure that implementing classes only need to be concerned about the methods that are of interest to them.

D - The principle of Dependency Inversion refers to the decoupling of software modules. This way, instead of high-level modules depending on low-level modules, both will depend on abstractions.

KISS - Keep It Simple and Stupid - to keep our code readable and simple for humans. If several use cases are handled by the method, we need to split them into smaller functions
DRY - Don't Repeat Yourself - Within a system, each piece of logic should have a single unambiguous representation.
The common functionality in both of them is Eating food so, we can put this common functionality into the parent class, i.e., Animals, and then we can extend that parent class in the child class, i.e., Dog and Cat.
Violations of the DRY principles are referred to as WET solutions
  1. Write everything twice
  2. We enjoy typing
  3. Write every time
  4. Waste everyone's twice
Composition Over Inheritance Principle

The principle states that we should have to implement interfaces rather than extending the classes. We implement the inheritance when
  1. The class need to implement all the functionalities
  2. The child class can be used as a substitute for our parent class.
In the same way, we use Composition whenThe class needs to implement some specific functionalities.
----------------------------------------------------------------------------------------------------------------
Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are. Highly maintainable and testable. Loosely coupled. Independently deployable. Organized around business capabilities.

----------------------------------------------------------------------------------------------------------------
Early Instantiation: creation of instance at load time.
Lazy Instantiation: creation of instance when required.
----------------------------------------------------------------------------------------------------------------
Singleton Pattern says that just "define a class that has only one instance and provides a global point of access to it".

Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface


BSC
C - FBPAS
S - ABCDFFP
B - TO(2)MICS-V
      TOM-MS-CIVICS
      TO-IM-CSC-IVS-M
(Template  observer interpreter momento AS chain startegy command iterator ON visitor state mediator )






----------------------------------------------------------------------------------------------------------------
Streams

IntStream.range(0, 10).forEach(System.out::print);
IntStream.range(0, 10).skip(5).forEach(System.out::println);
System.out.println(IntStream.range(0, 10).sum());
 // 1. Integer Stream
IntStream.range(1, 10).forEach(System.out::print);
// 2. Integer Stream with skip
IntStream.range(1, 10).skip(5).forEach(x -> System.out.println(x));
// 3. Integer Stream with sum
System.out.println(IntStream.range(1, 5).sum());
// 4. Stream.of, sorted and findFirst
Stream.of("Ava", "Aneri", "Alberto")
.sorted()
.findFirst()
.ifPresent(System.out::println);
// 5. Stream from Array, sort, filter and print
String[] names = {"Al", "Ankit", "Kushal", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah"};
Arrays.stream(names) // same as Stream.of(names)
.filter(x -> x.startsWith("S"))
.sorted()
.forEach(System.out::println);
// 6. average of squares of an int array
Arrays.stream(new int[] {2, 4, 6, 8, 10})
.map(x -> x * x)
.average()
.ifPresent(System.out::println);
// 7. Stream from List, filter and print
List<String> people = Arrays.asList("Al", "Ankit", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah");
people.stream().map(String::toLowerCase)
.filter(x -> x.startsWith("a"))
.forEach(System.out::println);
// 8. Stream rows from text file, sort, filter, and print
Stream<String> bands = Files.lines(Paths.get("bands.txt"));
bands.sorted().filter(x -> x.length() > 13).forEach(System.out::println);
bands.close();
// 9. Stream rows from text file and save to List
List<String> bands2 = Files.lines(Paths.get("bands.txt"))
.filter(x -> x.contains("jit"))
.collect(Collectors.toList());
bands2.forEach(x -> System.out.println(x));
// 10. Stream rows from CSV file and count
Stream<String> rows1 = Files.lines(Paths.get("data.txt"));
int rowCount = (int)rows1.map(x -> x.split(","))
            .filter(x -> x.length == 3).count();
System.out.println(rowCount + " rows.");
rows1.close();
// 11. Stream rows from CSV file, parse data from rows
Stream<String> rows2 = Files.lines(Paths.get("data.txt"));
rows2.map(x -> x.split(","))
        .filter(x -> x.length == 3)
.filter(x -> Integer.parseInt(x[1]) > 15)
.forEach(x -> System.out.println(x[0] + "  " + x[1] + "  " + x[2]));
rows2.close();
// 12. Stream rows from CSV file, store fields in HashMap
Stream<String> rows3 = Files.lines(Paths.get("data.txt"));
Map<String, Integer> map = new HashMap<>();
map = rows3.map(x -> x.split(","))
        .filter(x -> x.length == 3)
.filter(x -> Integer.parseInt(x[1]) > 15)
.collect(Collectors.toMap( x -> x[0],  x -> Integer.parseInt(x[1])));
rows3.close();
for (String key : map.keySet()) {
System.out.println(key + "  " + map.get(key));
}
// 13. Reduction - sum
double total = Stream.of(7.3, 1.5, 4.8)
.reduce(0.0, (Double a, Double b) -> a + b);
System.out.println("Total = " + total);
// 14. Reduction - summary statistics
IntSummaryStatistics summary = IntStream.of(7, 2, 19, 88, 73, 4, 10)
.summaryStatistics();
System.out.println(summary);
----------------------------------------------------------------------------------------------------------------

1. Using CommandLineRunner interface : implement it and add @Component annotation above the class or create its bean using @bean.We can create multiple CommandLineRunners in one application. Using the Ordered interface or @Order annotation we can configure the order in which they should run. interpreted as a single value “status=running”.

2. With ApplicationRunner interface : To access command line arguments in parsed format we need to use ApplicationRunner interface. –name= “stacktrace” — Port=8080 –name=”guru”

 

 

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

  • ApplicationContextInitializedEvent : triggered after ApplicationContext is prepared and ApplicationContextInitializers are called but before bean definitions are loaded
  • ApplicationPreparedEvent : triggered after bean definitions are loaded
  • ApplicationStartedEvent : triggered after context has been refreshed but before command-line and application runners are called
  • ApplicationReadyEvent : triggered after any application and command-line runners are called
  • ApplicationFailedEvent : triggered if there is an exception on startup
----------------------------------------------------------------------------------------------------------------
@Postconstruct annotation on a method

The InitializingBean Interface
Init attribute of @bean annotation @Bean(initMethod="<method name>")

----------------------------------------------------------------------------------------------------------------
embedded container

Three different types of embedded servlet containers: 
Tomcat (default), Jetty and Undertow.

----------------------------------------------------------------------------------------------------------------
BeanFactory :
  • Does not support the Annotation based dependency Injection.
  • Lazy loading.
  • doesn't allow configure to multiple configuration files.
ApplicationContext
  • Support Annotation based dependency Injection.-@Autowired, @PreDestroy
  • Its By default support Aggresive loading.
  • It allow to configure multiple configuration files
----------------------------------------------------------------------------------------------------------------

@SpringBootApplication is a 3-in-1 annotation that combines the functionality of @Configuration, @ComponentScan and @EnableAutoConfiguration.

----------------------------------------------------------------------------------------------------------------
Spring Boot DevTools pick up the changes and restart the application
Features : 
  • Property Defaults
  • Automatic Restart
  • LiveReload
  • Remote Debug Tunneling
  • Remote Update and Restart
----------------------------------------------------------------------------------------------------------------
Hashtable vs Conncurrent hahmap
  • Hashtable is belongs to the Collection framework; ConcurrentHashMap belongs to the Executor framework.
  • Hashtable uses single lock for whole data. ConcurrentHashMap uses multiple locks on segment level (16 by default) instead of object level i.e. whole Map.
  • ConcurrentHashMap locking is applied only for updates. In case of retrievals, it allows full concurrency, retrievals reflect the results of the most recently completed update operations. So reads can happen very fast while writes are done with a lock.
  • ConcurrentHashMap doesn't throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it and does not allow null values.
  • ConcurrentHashMap returns Iterator, which fails-safe
----------------------------------------------------------------------------------------------------------------
HashTable
  • A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
  • Java Hashtable class contains unique elements.
  • Java Hashtable class doesn't allow null key or value.
  • Java Hashtable class is synchronized.
  • The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
----------------------------------------------------------------------------------------------------------------

 HashMap can be synchronized using the Collections. synchronizedMap() method
----------------------------------------------------------------------------------------------------------------

ConcurrentHashMap
  • The underlined data structure for ConcurrentHashMap is Hashtable.
  • ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications.
  • At a time any number of threads are applicable for a read operation without locking the ConcurrentHashMap object which is not there in HashMap.
  • In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level.
  • The default concurrency-level of ConcurrentHashMap is 16.
  • In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads.
  • Inserting null objects is not possible in ConcurrentHashMap as a key or value.

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.

Concurrent modification exception

It doesn't throw concurrent modification exception. 

Iterator return by synchronized map throws concurrent modification exception


----------------------------------------------------------------------------------------------------------------
important link:
https://stacktraceguru.com/springboot/run-method-on-startup



//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.
            IntStream intStream = Arrays.stream(arr);
            Stream<int[]> stream = Stream.of(arr);
            Stream<char[]> stream = Stream.of(arr);

·        *  Stream.of() needs flattening whereas Arrays.stream() does not

IntStream intStreamNew = stream.flatMapToInt(Arrays::stream);

·        * Stream.of() is generic whereas Arrays.stream is not:

------------------------------------------------------------------------------
Predicate / Function / Consumer / Supplier


------------------------------------------------------------------------------
Spring JPA

Methods: find / persist / remove / detach / createquery(JPQL)
Annotations: @Entity / @Temporal / @Transitent / @Table /@Id /@Column / @Transactional  / @Modifying
@Temporal: SPecified for table using Date or calendar.it solves one of the major issues for converting the java object to database specified object
@Transactional   - default config
  • isolation = DEFAULT
  • propagation = REQUIRED
  • timeout = TIMEOUT_DEFAULT
  • readOnly =false
  • rollbackFor = RuntimeException or its subclasses
  • noRollbackFor = Exception or its subclasses
------------------------------------------------------------------------------
@Modifying - defaultconfg
clearAutomatically 
flashAutomatically



-----------------------------------------------------------------------------------------
Object Level Locks VS Class Level locks ?
Object Level Locks − It can be used when you want non-static method or non-static block of the code should be accessed by only one thread. 
Class Level locks − It can be used when we want to prevent multiple threads to enter the synchronized block in any of all available instances on runtime

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


public class ClassLevelLockExample {
   public void classLevelLockMethod() {
      synchronized (ClassLevelLockExample.class) {
         //DO your stuff here
      }
   }
}

public class ObjectLevelLockExample {
   public void objectLevelLockMethod() {
      synchronized (this) {
         //DO your stuff here
      }
   }
}


-----------------------------------------------------------------------------------------
@SpringBootApplication - @Configuration, @EnableAutoConfiguration and @ComponentScan
-----------------------------------------------------------------------------------------
Content Negosiation :
WebMvcConfigurerAdapter class.  override ContentNegotiationConfigurer() 

Way1 :
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Way 2:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).
    favorParameter(true).
    parameterName("mediaType").
    ignoreAcceptHeader(true).
    useJaf(false).
    defaultContentType(MediaType.APPLICATION_JSON).
    mediaType("xml", MediaType.APPLICATION_XML).
    mediaType("json", MediaType.APPLICATION_JSON);
  }

-----------------------------------------------------------------------------------------
Connecting to 2 different database in single Serivce
implement these methods in config calss
  • DataSource
  • EntityManagerFactory (userEntityManager)
  • TransactionManager (userTransactionManager)
@Configuration @PropertySource({ "classpath:persistence-multiple-db.properties" }) @EnableJpaRepositories( basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager" ) public class PersistenceUserConfiguration { @Autowired
private Environment env; @Bean @Primary public LocalContainerEntityManagerFactoryBean userEntityManager() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(userDataSource()); em.setPackagesToScan( new String[] { "com.baeldung.multipledb.model.user" }); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); HashMap<String, Object> properties = new HashMap<>(); properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); em.setJpaPropertyMap(properties); return em; } @Primary @Bean public DataSource userDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("user.jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } @Primary @Bean public PlatformTransactionManager userTransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory( userEntityManager().getObject()); return transactionManager; }
}
-----------------------------------------------------------------------------------------
Create a custom annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Init {
}
-----------------------------------------------------------------------------------------
Order the Sql query gets executed
FJWGHSDO - F to J Ward in GH shift on doctor order

-----------------------------------------------------------------------------------------
Generics
 Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.
-----------------------------------------------------------------------------------------
create arrayList and hashmap
-----------------------------------------------------------------------------------------
types of microservices
-----------------------------------------------------------------------------------------
cache and security
-----------------------------------------------------------------------------------------
Composition
Two objects associated with each other exists when there is a strong relationship between one class and another. Other classes cannot exist without the owner or parent class. For example, A 'Human' class is a composition of Heart and lungs.
-----------------------------------------------------------------------------------------
Builder design pattern
First of all you need to create a static nested class and then copy all the arguments from the outer class to the Builder class. We should follow the naming convention and if the class name is Computer then builder class should be named as ComputerBuilder.
Java Builder class should have a public constructor with all the required attributes as parameters.
Java Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute.
The final step is to provide a build() method in the builder class that will return the Object needed by client program. For this we need to have a private constructor in the Class with Builder class as argument.


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);
}

}

}

 




Notice that Computer class has only getter methods and no public constructor. So the only way to get a Computer object is through the ComputerBuilder class.

Computer comp = new Computer.ComputerBuilder("500 GB", "2 GB").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
-----------------------------------------------------------------------------------------
Interceptors : Spring its - AOP
-----------------------------------------------------------------------------------------
Types of cloning : Swallow cloning and deep cloning
object primitive(Integer, Float, Double, Character, Boolean, String, etc) properties are cloned.

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

-----------------------------------------------------------------------------------------
Java - Pass by value
public class Main {
     public static void main(String[] args) {
          Foo f = new Foo("f");
          changeReference(f); // It won't change the reference!
          modifyReference(f); // It will modify the object that the reference variable "f" refers to!
     }
     public static void changeReference(Foo a) {
          Foo b = new Foo("b");
          a = b;
     }
     public static void modifyReference(Foo c) {
          c.setAttribute("c");
     }
}
-----------------------------------------------------------------------------------------
Exception annotation - @ControllerAdvice and @ExceptionHandler
-----------------------------------------------------------------------------------------
Get the 2nd highest number in array in optimized way without sorting

int highest = Integer.MIN_VALUE; 
int secondHighest = Integer.MIN_VALUE;
// 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 array
public 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();
}

-----------------------------------------------------------------------------------------
Thread local
The ThreadLocal class is used to create thread local variables which can  only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

Type

Method

Description

T

get()

This method returns the value in the current thread's copy of this thread-local variable.

void

set()

This method sets the current thread's copy of this thread-local variable to the specified value.

void

remove()

This method removes the current thread's value for this thread-local variable.

protected T

initialValue()

This method returns the current thread's initial value for this thread-local variable.







class RunnableDemo implements Runnable {
   int counter;
   ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<Integer>();
   public void run() {     
counter++;

if(threadLocalCounter.get() != null) {
threadLocalCounter.set(threadLocalCounter.get().intValue() + 1);
} else {
threadLocalCounter.set(1);
}
System.out.println("Counter: " + counter);
System.out.println("threadLocalCounter: " +threadLocalCounter.get());
}
}
public class TestThread {
   public static void main(String args[]) {
      RunnableDemo commonInstance = new RunnableDemo();
Thread t1 = new Thread(commonInstance);
Thread t2 = new Thread(commonInstance);
Thread t3 = new Thread(commonInstance);
Thread t4 = new Thread(commonInstance);
      t1.start();
t2.start();
t3.start();
t4.start();
      // wait for threads to end
      try {
t1.join();
         t2.join();
        t3.join();
        t4.join();
} catch (Exception e) {
System.out.println("Interrupted");
    }
}
}


ThreadLocal
The 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

  1. First, the application borrows a thread from the pool.
  2. Then it stores some thread-confined values into the current thread's ThreadLocal.
  3. Once the current execution finishes, the application returns the borrowed thread to the pool.
  4. After a while, the application borrows the same thread to process another request
  5. Since the application didn't perform the necessary cleanups last time, it may re-use the same ThreadLocal data for the new request.

-----------------------------------------------------------------------------------------

Prototype Class example

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();
}
}

 

Output:
TwitterMessageService Implementation
null


------------------------------------------------------------------------------------------------
Make a call from singleton class to prototype class ?
ref video
  • applicationContext
  • proxy @Lookup
  • provider
  • objectFactory


------------------------------------------------------------------------------------------------
Integration between different microservice
------------------------------------------------------------------------------------------------
Real time example for ManytoMany
customer and product -
  • customer can by any number of products
  • products can be also by many customers
OneToOne : EmailAddress and User
OneToMany : Cart and items
ManyToOne : Book and student - same book as given to any students
-----------------------------------------------------------------------------------------
Idempotency
They are HTTP methods that can be called multiple times and they will produce the same result. They are considered the safe option to update a resource on the Server.
Some examples of idempotent HTTP methods are GET, PUT, and PATCH. No matter how many times you call them, they will produce the same result with the same URI.
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned.
-----------------------------------------------------------------------------------------
Livlock and Deadlock
Two or more threads keep on transferring states between one another instead of waiting infinitely
example
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);
    }
}
    static class Diner {
    private String name;
    private boolean isHungry;
    public Diner(String n) { name = n; isHungry = true; }
    public String getName() { return name; }
    public boolean isHungry() { return isHungry; }
    public void eatWith(Spoon spoon, Diner spouse) {
    while (isHungry) {
        // Don't have the spoon, so wait patiently for spouse.
        if (spoon.owner != this) {
        try { Thread.sleep(1); }
        catch(InterruptedException e) { continue; }
        continue;
    }

    // If spouse is hungry, insist upon passing the spoon.
    if (spouse.isHungry()) {
        System.out.printf("%s: You eat first my darling %s!%n", name, spouse.getName());
        spoon.setOwner(spouse);
        continue;
    }

    // Spouse wasn't hungry, so finally eat
    spoon.use();
    isHungry = false;
    System.out.printf("%s: I am stuffed, my darling %s!%n", name, spouse.getName());
    spoon.setOwner(spouse);
    }
}
}


public static void main(String[] args) {
final Diner husband = new Diner("Bob");
final Diner wife = new Diner("Alice");

final Spoon s = new Spoon(husband);

new Thread(new Runnable() {
public void run() { husband.eatWith(s, wife); }
}).start();

new Thread(new Runnable() {
public void run() { wife.eatWith(s, husband); }
}).start();
}
}

-----------------------------------------------------------------------------------------
thread state
-----------------------------------------------------------------------------------------
Diff between abstract class and interface in java8
The key difference is that an abstract class can maintain a state but the interface cannot, and an abstract class can also have a constructor that is not allowed inside the interface even in Java 8.
If you are designing API then use interface and if you are abstracting both state and behavior then use an abstract class.
object's state is stored in fields and behavior is shown via methods.
-----------------------------------------------------------------------------------------
Different type of class loader
-----------------------------------------------------------------------------------------
Can we create object for abstract class and interface
You cannot create an object of abstract class or interface since they are incomplete class 
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

-----------------------------------------------------------------------------------------
Create a runtime exception
public class MyCustomException extends RuntimeException {
   public MyCustomException(String message) {
      super(message);
   }
}
-----------------------------------------------------------------------------------------
Runnable vs callable
  • A Callable needs to implement call() method while a Runnable needs to implement run() method.
  • A Callable can return a value but a Runnable cannot.
  • A Callable can throw checked exception but a Runnable cannot.
  • A Callable can be used with ExecutorService#invokeXXX(Collection<? extends Callable<T>> tasks) methods but a Runnable cannot be.

public interface Runnable {
    void run();
}

public interface Callable<V> {
    V call() throws Exception;
}
-----------------------------------------------------------------------------------------
Can we change the level of access specifier and exception while overriding the method
  • Access Specifiers
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
Access modifier restrictions in decreasing order:
    • private
    • default
    • protected
    • public
i.e. private is more restricted then default and default is more restricted than protected and so on
  • Exception handling 
 An overriding method can throw any unchecked exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

1. If an overridden method does not throw an exception using throws clause then
  • The overriding method can not throw any checked or compile-time exception.
  • The overriding method can throw any unchecked or runtime exception.
2. If an overridden method throws an unchecked or runtime exception then
  • The overriding method can throw any unchecked or runtime exception.
  • The overriding method can throw the same exception which is thrown by the overridden method.The overriding method can ignore the method level exception.
3. If the superclass method throws checked or compile-time exception then
  • Subclass method can throw an exception which is a subclass of the superclass method’s exception.
  • Subclass method cannot throw the exception which is a superclass of the superclass method’s exception.
  • Subclass method can throw any unchecked or runtime exception.

-----------------------------------------------------------------------------------------
Types of inheritance in java with examples
-----------------------------------------------------------------------------------------
Copy Constructor

In Java, a copy constructor is a special type of constructor that creates an object using another object of the same Java class. It returns a duplicate copy of an existing object of the class.
We can assign a value to the final field but the same cannot be done while using the clone() method. It is used if we want to create a deep copy of an existing object. It is easier to implement in comparison to the clone() method.

public class Fruit  
{  
private double fprice;  
private String fname;  
//constructor to initialize roll number and name of the student  
Fruit(double fPrice, String fName)  
{   
fprice = fPrice;  
fname = fName;  
}  
//creating a copy constructor  
Fruit(Fruit fruit)  
{  
System.out.println("\nAfter invoking the Copy Constructor:\n");  
fprice = fruit.fprice;  
fname = fruit.fname;  
}  
//creating a method that returns the price of the fruit  
double showPrice()  
{  
return fprice;  
}  
//creating a method that returns the name of the fruit  
String showName()  
{  
return fname;  
}  
//class to create student object and print roll number and name of the student  
public static void main(String args[])  
{  
Fruit f1 = new Fruit(399, "Ruby Roman Grapes");  
System.out.println("Name of the first fruit: "+ f1.showName());  
System.out.println("Price of the first fruit: "+ f1.showPrice());  
//passing the parameters to the copy constructor  
Fruit f2 = new Fruit(f1);  
System.out.println("Name of the second fruit: "+ f2.showName());  
System.out.println("Price of the second fruit: "+ f2.showPrice());  
}  
}  
-----------------------------------------------------------------------------------------
Row number, Rank, Dense rank
row_number numbers the rows 1, 2, 3, etc by the columns in the ORDER BY clause, and if there are ties, it is arbitrary which rows that gets the same number.

rank and dense_rank are similar to row_number, but when there are ties, they will give the same value to the tied values. rank will keep the ranking, so the numbering may go 1, 2, 2, 4 etc, whereas dense_rank will never give any gaps.

-----------------------------------------------------------------------------------------

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

-----------------------------------------------------------------------------------------
HTTP Status code

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

-----------------------------------------------------------------------------------------
1. **@Repository**   - Automatic exception translation in your persistence layer.
2. **@Service**      - It indicates that the annotated class is providing a business service to other layers within the application. 
3. @Controller: This annotation enables the detection of @RequestMapping annotation in the class.
-----------------------------------------------------------------------------------------
ClassNotFoundException and NoClassDefFoundError are the errors when JVM or ClassLoader not able to find appropriate class while loading at run-time. ClassNotFoundException is a checked exception and NoClassDefFoundError is an Error which comes under unchecked

 ClassNotFoundException is an exception while NoClassDefFoundError is an error.
ClassNotFoundException occurs when classpath does not get updated with required JAR files while error occurs when the required class definition is not present at runtime.

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.


-----------------------------------------------------------------------------------------
Can we inherit entity class from non-entity class and vice-versa
extreme programming
saga design pattern   
how to make wait for other service to return some value and pass it to other service once it returned
how to make wait for other service to return some response which has also some child call

-----------------------------------------------------------------------------------------
Reading the value from application.properties fie in spiring oot
@value
@ConfigurationProperties 
Enviorment - org.springframework.core.env.Environment
@Autowired
    private Environment environment;
-----------------------------------------------------------------------------------------
spring-multiple-configuration-classes  chapter-5
  • @ExternalBean : One configuration class may need to reference a bean defined in another configuration class (or in XML, for that matter). The @ExternalBean annotation provides just such a mechanism. When JavaConfig encounters a method annotated as @ExternalBean, it replaces that method definition with a lookup to the enclosing bean factory for a bean with the same name as the method name
  • @Import : @Import represents JavaConfig's equivalent of XML configuration's element. One configuration class can import any number of other configuration classes, and their bean definitions will be processed as if locally defined
  • ConfigurationSupport : As a convenience, @Configuration classses can extend ConfigurationSupport, primarily in order to facilitate easy lookup of beans from the enclosing BeanFactory / ApplicationContext.
-----------------------------------------------------------------------------------------
What Is Cascading?
Entity relationships often depend on the existence of another entity, for example the Person–Address relationship. Without the Person, the Address entity doesn't have any meaning of its own. When we delete the Person entity, our Address entity should also get deleted.
Cascading is the way to achieve this. When we perform some action on the target entity, the same action will be applied to the associated entity.

Types
  • ALL.
  • PERSIST.- Cascade Type PERSIST propagates the persist operation from a parent to a child entity. When we save the person entity, the address entity will also get saved.
  • MERGE.
  • REMOVE.
  • REFRESH.
  • DETACH
-----------------------------------------------------------------------------------------
Thread class methods
if u try to start the same thread 2 times, we will get java.lang.IllegalThreadStateException
-----------------------------------------------------------------------------------------

Runnable r = ()->{system.out.println("hi");}
public static Thread currentThread() : returns a reference to the currently running thread.
public static void sleep() : This blocks the currently running thread for the specified amount of time. 
public void join() : It causes the main current thread to block until the thread which has join to terminates or the specified amount of milliseconds passes.
public final int getPriority() : used to check the priority of the thread. default priority of a thread is 5.
public final void setPriority() : used to change the priority of the thread. priority of every thread from 1 to 10.
public final void setName() :
public final String getName()
public long getId() :  returns the identifier of the thread. The thread ID is a number generated when the thread was created. This ID cannot be changed during its lifetime.
But when the thread is terminated, the ID can be reused
public static void yield() : pauses the execution of the current thread to execute other threads temporarily.
public final void suspend()
public final void resume()
public final void stop()
public void destroy()
-----------------------------------------------------------------------------------------
Strings 

concat() method takes concatenates two strings and returns a new string object only string length is greater than 0, otherwise, it returns the same object.
+ operator creates a new String object every time irrespective of the length of the string.
-----------------------------------------------------------------------------------------
Volatile

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.
-----------------------------------------------------------------------------------------
compleablefuture

supplyAsync(): It complete its job asynchronously. The result of supplier is run by a task from ForkJoinPool.commonPool() as default. The supplyAsync() method returns CompletableFuture on which we can apply other methods.
CompletableFuture.supplyAsync — In case if you want the return value.
CompletableFuture.runAsync —  In case if you don't want the return value.
thenApply(): The method accepts function as an arguments. It returns a new CompletableStage when this stage completes normally. The new stage use as the argument to the supplied function.
join(): the method returns the result value when complete. It also throws a CompletionException (unchecked exception) if completed exceptionally.

-----------------------------------------------------------------------------------------
Splitting monolythic to microservice
  • Service boundaries
  • SingleResponsibility
  • Common ClosurePrinciple
-----------------------------------------------------------------------------------------
Order of executing the file
  • yaml for that profile
  • properties for that profie
  • application.yaml
  • application.properties
-----------------------------------------------------------------------------------------

@RefreshScope and /refresh - actuator endpoint - used for refreshing the cloudconfig while service is already running
this is manual process. we can use cloud config like Rabbit MQ
-----------------------------------------------------------------------------------------

LoadBalancing - Ribbon - default - NoOpPing_Strategy, thinks that all services are up even though its down
Latest - Iping - if service is down, Send ping for specific duration, then stops
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
// System.out.println(randomString(-229985452)+' '+randomString(-147909649)); 
// Insert code here to make loop infinite
for (int i = a; i <= a + 1; i++) 
// Infinite loop
//parallel execution with controlled - java concurrent future concurrent semaphor 
}
// public static String randomString(int seed) { 
//     Random rand = new Random(seed); 
//     StringBuilder sb = new StringBuilder(); 
//     for(int i=0;;i++) { 
//         int n = rand.nextInt(27); 
//         if (n == 0) break; 
//         sb.append((char) ('`' + n)); 
//     } 
//     return sb.toString(); 
// }

Rest and RestFul



static methods can only access other static methods and static variables
Non static methods can access static variables
Life cycle of Bean in spring Boot
  1. Spring instantiates the bean.
  2. Spring injects values and bean references into the bean’s properties.
  3. If the bean implements BeanNameAware, Spring passes the bean’s ID to the setBeanName() method.
  4. If the bean implements BeanFactoryAware, Spring calls the setBeanFactory() method, passing in the bean factory itself.
  5. If the bean implements ApplicationContextAware, Spring calls the setApplicationContext() method, passing in a reference to the enclosing application context.
  6. If the bean implements the BeanPostProcessor interface, Spring calls its postProcessBeforeInitialization() method.
  7. If the bean implements the InitializingBean interface, Spring calls its afterPropertiesSet() method. Similarly, if the bean was declared with an init-method, then the specified initialization method is called.
  8. If the bean implements BeanPostProcessor, Spring calls its postProcessAfterInitialization() method.
  9. At this point, the bean is ready to be used by the application and remains in the application context until the application context is destroyed.
  10. If the bean implements the DisposableBean interface, Spring calls its destroy() method. Likewise, if the bean was declared with a destroy-method, the specified method is called.






Problems : 
Given the arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits. 
We are given two arrays that represent the arrival and departure times of trains that stop.
Examples:  
1. Input: arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00} 
dep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}

9.00 - 9.10 - 1
9.40 - 12.00 - 1 910
9.50 - 11.20 -2 
11.00 - 11.30 - 3
15.00 - 19.00 - 1
18.00 - 20.00 - 2

int p =1;
List<Integer> list = new ArrayList<>();
for(int i=0;i<arr.length-1;i++){
list.add(arr[i]);
if(dep[i]>arr[i+1]){
p++;
}else if(dep[i]<arr[i+1]){
list.remove(arr[i]);
if(list.isEmpty()){
p=1;
}else{
p--;
}
}
}
-------------------------------------------------
Given two given arrays of equal length, the task is to find if given arrays are equal or not.
 Two arrays are said to be equal if both of them contain the same set of elements and in the same order.
 
for(inti =0 ;i<n;i++){
if(a1[i] != a2[i]){
return false;
}
return true;
 -------------------------------------------------

Given an integer array nums, find the continuous subarray (containing at least one number) which has the largest sum and return its sum.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]

i =-2

j = 1

-------------------------------------------------
emp

name
address 
id

list.streams().filter(x->x.getId%2!=0).map(x->x.getName()).collect(Collectors.toList());
-------------------------------------------------
int[] arr = {1,2,3}
 int[] b = {2,3,4} 
 List<Integer> l2 = new ArrayList<>();
List<Integer> l =  Arrays.stream(arr).collect(Collectors.toList());
IntStream.range(0,b.length-1).boxed().forEach(x->{
if(l.indexOf(x)!=-1){
l2.add(x);
}
}
-------------------------------------------------
Stream<int[]> \
list<list<>>
-------------------------------------------------
List<Integer> l = Stream.of(arr).flatMap(Streams::Array).collect(Collectors.toList());
-------------------------------------------------
@FunctionalInterface
class Test{
public void test1();
}
-------------------------------------------------
 Integer i1=100;
 Integer i2=100;
 sop (i1==i2)
 -------------------------------------------------
 class A{
String s = "vikneshwar";
 }
 
 Class B extend A{
String s = "arumugam";
 }
 
A a = new B();
A.s = 
-------------------------------------------------
String s = "aabc";
List<Character> c = s.chars().mapToObj(c->(char)c).collect(Colletors.groupingBy(Function.identity(),Collectors.counting()).entrySet().streams().filter(x->x.getValue()==1).map(x->x.getKey()).collect(Collectors.toList());
AutomicInteger  a= new AutomicInteger(s.length);
c.streams().forEach(x->{
int b = s.indexOf(x);
if(b<a){
   a=b;
}
});
syso(s.charAt(a));
-------------------------------------------------
[ {name: 'kranthi', age: 20, dob: 08-20-1970},

 {name: 'rambabu', age: 30, dob: 08-20-1990},

{name: 'Giridhar', age: 32, dob: 06-02-1992} ]

Update the dob by 1 day and filter by age greater than 30

SimpleDateFormat format = new SimpleDateFomat("mm-dd-yyyy");
int count
list.streams().forEach(x->{
Dax.getDob().getDate()+1;
}).collect(Collectors.toList()).streams().filter(x->x.getAge()>30).forEach(System.out::println);


Input :
["CRICKET",
"SOCCER",
"HOCKEY",
"BADMINTON",
"VOLLEYBALL"]

Output:

CSHBVROOAOICCDLCCKMLKEEIEERYNYTTBOANLL

size of word whose length is max
create a 2 dimetional array
insert the elements in the array and if values in not in that position insert special character
use for loop to print the elements if it is not special character

AutomicInteger a = new AutomicInteger(0);
list.streams.forEach(x->{
if(x.length()>a.get()){
a = x.length();
}
});

String[][] s = new String[list.size()][a];
int l=0;
for(String str : list){
int k=0;
for(String c:str.split("")){
s[l][k]=c;
k++;
}
l++;
}

for(int i=0;i<a;i++){
for(int j=0;j<list.size();j++){
if(!s[i][j].equals(""))
System.out.println(s[i][j]);
}
}

Employee : id, first name, last name, dept_id,sal
Dept : id, name
Select d.name, sum(e.sal) as totalsalary from  employee e inner join dept d on e.dept_id = d.id groupby dept_id where max(totalsalary);
-------------------------------------------------
Stream1: (
                new User(1, "Sachin", "Tendulkar"),
                new User(2, "Virat", "Kohli"),
                new User(3, "Ricky", "Ponting"),
                new User(4, "Brian", "Lara")
        );   
User -> id, firstName, lastName

Stream 2 : (0,2,4,6,8,10)

stream1.filter(x->list.contains(x.getId())).map(x->x.getFirstName()).collect(Collectors.toList());
-------------------------------------------------
list.streams().filter(x->x%2==0).collect(Collectors.toList());

 0 1 1 2 3 5 8 13..

int i=0;
int j=1;
syso(i);
syso(j);
 int in=100;
while(j<in){
int x=i+j;
syso(x);
i=j;
j=x;
}

list<String> list = viknesh, nitin, gavs, pst
colletions.sort(list);

employe  
id
name
salary

toString()

list.streams().sorted(Comparator.compringBy(Emp::getSalary)).reversed().collect(Collectors.toList()).streams().forEach(System.out::println);

select * from (Select salary, dense_Rank() as r over(salary orderby desc) from employee )where r=3;
select dept_nam, sum(salary) as total from employee groupby dept orderby total desc;

FJGHSOD
-------------------------------------------------
Java8
        Write a lambda exp for all criteria below:
            create list of integers from 1-31
            Filter for odd numbers
            Sort by descending
            Multply each value by 3
            Print only last 3 item
List<Integer> list= IntStreams.range(1,31).boxed().filter(z->z%2!=0).sorted().reversed().map(x->x*3).collect(Collectors.toList());
list.streams().skip(list.size()-3).

list<integer> = 1,2,3,4,5,6,7

a[i]+a[a.length-i]==8
-------------------------------------------------
Array =[ 3,2,5,6];


for(int i=0;i<arr.size()-1;i++){
for(j=i+1;j<arr.size();j++){
if(arr[i]<arr[j]){
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

35
53
56
65

6235

23
32
35
53

6523

23
32
[6,5,3,2]

main

Singleton s = Singleton.getInstance();
Singleton s1 = Singleton.getInstance();



public class Singleton{
public static Singleton s;
private Singleton(){
}
public static Singleton getInstance(){
if(s==null){
syncronized(Singleton.class){
s= new Singleton();
}
}
return s;
}
}

class a extends c
b - c

x
@Autowired
@Qualifier("a")
C c;
-------------------------------------------------

[17:40] Sitaram Cherukuvada
    class A {​​
​[17:41] Sitaram Cherukuvada
    class A {​​
public String f;
public int g;
getF();
getG();
setF();
setG();
}​​
​[17:47] Sitaram Cherukuvada
    C {​​ add }​​
A extends C {​​ add }​​
B extends C {​​ add }​​
D {​​ add }​​
​[17:51] Sitaram Cherukuvada
    String f(int a, int b);
Boolean f(int a, int b);
​[17:51] Sitaram Cherukuvada
    f(10,10);
​[17:54] Sitaram Cherukuvada
    
final Person {​​
firstName,
lastName,
address {​​
line1, line2, city
}​​
}​​
Edited​[17:54] Sitaram Cherukuvada
    Person(fn, ln, addr);
​[17:55] Sitaram Cherukuvada
    addr.line1 = "xyz";

--------------------------------------
Class A{

public void syncronized m1{
syso
}

}
class level syncronized
objectlevel
T1 A o1 = new 
T2 A o2

Id Salary Name Dept Id
1 34000 ANURAG UI DEVELOPERS
2 33000 harsh BACKEND DEVELOPERS
3 36000 SUMIT BACKEND DEVELOPERS
4 36000 RUHI UI DEVELOPERS
5 37000 KARAN UI DEVELOPERS
6 37000 Kunal UI DEVELOPERS


id salary name Dept id
3 36000 SUMIT BACKEND DEVELOPERS
5 37000 KARAN UI DEVELOPERS

6 37000 Kunal UI DEVELOPER

Select * from emp where (deptid,name) in(
Select min(name),deptid from 
(Select * from emp where (deptid,salary) in(
Select deptid,max(salary) from emp group by deptid )) emp1 group by deptid) ;

public int doMethod(){
        try{
            throw new Exception();
        }
        catch(Exception ex){
            return 1;
        }
        finally{
            return 2;
        }
    }

    public static void main(String[] args) {

        MyFinalTest testEx = new MyFinalTest();
        int rVal = testEx.doMethod();
        System.out.println("The return Val : "+rVal);
    }

}

[17:12] S, Surender (Chennai) (Guest)
    public class Test
{​​
public static void test (String args[])
{​​
System.out.println(100 + 100 +"Test1");
System.out.println("Test2" + 100 + 100);
}​​
}​​
​[17:14] S, Surender (Chennai) (Guest)
    private boolean isHelloWord(String str) {​​
return str == "Hello World";
return str.equals("Hello World");
return "Hello World".equals(str);
}​​
​[17:16] S, Surender (Chennai) (Guest)
    class Test{​​
int counter;
public static void increment(){​​
counter++;
System.out.println("Current value of Counter is: " + counter);
}​​
}​​

public class Main{​​
public static void main(String args[]){​​
Test.increment();
}​​
}​​
​[17:20] S, Surender (Chennai) (Guest)
    package pack;
class A{​​
void msg(){​​System.out.println("Hello");}​​
}​​

package mypack;
import pack.*;
class B{​​
public static void main(String args[]){​​
A obj = new A();
obj.msg();
}​​
}​​
​[17:38] Vikneshwar Arumugam (Guest)
    A 1 1 0 null
B10null null

110null
​[17:41] Vikneshwar Arumugam (Guest)
    list.stream().map(x->x.toLowerCase()).filter(x->x,startsWith("a").collect(Collectors.toSet());
-----------------------------------
arr = {2,1,3,4,5};
int j;
for(int i=0;i<arr.length-1;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]<arr[j]){
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
-------------------------------------------
Input:123456789012345
Output:123-456-789-012-345

Input:1234567890  1 
Output:123-456-78-90
-------------------------------------------
Empl
id
name
gender
salary

Optional<Emp> e = list.streams().collect(Collectors.groupingBy(Emp::getGender)).entrySet().streams().filter(x->x.getKey().equals("M")).sorted(Comparator.comparable(Emp::getSalary)).reversed().findFirst();
-------------------------------------------
a[] = ["tn","ka"]
b[] = ["tn","ap"]
List<String> l = new ArrayList<>();
List<String> list1 =Arrays.streams(b).collect(Collectors.toList());
List<String> list2 =Arrays.streams(a).collect(Collectors.toList());
List<String> list3= list1;
list1.removeAll(list2);
list2.removeALL(list3);
-------------------------------------------

Featured Post

HTML cheetsheet

List: Link tgs Dropdown

Popular Post

(C) Copyright 2018, All rights resrved InShortView. Template by colorlib