Sunday, August 18, 2024

Core Java

What is the way to import only static members of a class?

  • We can import using “import static packagename.classname.*”
  • We can import using “import static packagename.classname.staticMember”
How do we convert string to integer?
  • Use Integer.parseInt() to Convert a String to an Integer.

In Java, why do we use static variable?

  • Whenever we want to have a common property for all objects of a class, we use a class level variable i.e a static variable.
  • This Variable is loaded in memory only once at the time of class loading. So it saves memory, Since it is not defined per object in Java.

Why main method is public and static?

  • Main method is public so that JRE can access it from outside the class.
    • If it is private, JRE will not have the access to call it.
  • It is static so that it can be involved without creating an instance of the class.
  • We can over the main method. It will basically be method hiding. This will create another entry point for program and JRE can invoke any main method for the entry point.

We are serialising a class That contains a non-serialisable member.What will happen and how to fix it?

Algorithm JVM garbage collector Uses for collection?

  • Mark and Sweep/Tricolor algorithm
    • We have three colours, white, grey, and black.
    • Initially, all nodes are white.
    • Once we read a node We mark it as Grey.
    • Once we have all the neighbouring nodes of a node We mark it as black.
    • Black means it is safe, and Grey means there is still more processing to do.
    • Nodes Which remain coloured white can never be reached And are marked as garbage.
      • An object that can never be reached from the start of our program can never be used and thus can never be marked. Such objects are treated as garbage.
    • We can use a stack data structure to mark and pop out nodes Which have been visited.
      • We can go in depth while keeping few nodes in a stack.
    • In queue We have to go level by level, so number of expected nodes is huge.
    • That disadvantage of above algorithm is that once the garbage collector starts running, the application goes in sleep mode.
    • There are three ways in which we can reduce the time of garbage collection.
      • Make the process incremental that is break it into sub processes
      • Optimise the Solution
      • Make the process concurrent.
  • Generation hypothesis
    • Operating system breaks the tasks into time slices.
      • We break The garbage collection into two parts, one for objects that have been recently added to memory and other for old objects.
    • If an object survives particular period of time, then it is going to survive for longer. Old objects, stay long and new objects die immediately.
      • We break the memory into two parts, old region and Young region.
      • The young region Has all the young objects, the old region has objects who have survived a set of garbage collection cycles.
    • The young region is further broken down into Eden region and many survivor regions.
      • At a particular Point of time One of the survivor regions is empty.
      • After the first garbage collector cycle, the object that survive are sent to Survivor one space.
      • After the second garbage collector cycle, both the objects which survive from first survivor space and Eden space are moved to the second survivor space.
      • Fragmentation or compaction of memory also happens during this phase and such available free memory is made up of entire block.
      • After a limited number of above cycles, the leftover objects are promoted to old generation.
    • The old generation objects are polled less frequently for garbage collection.
    • In some cases, the old objects may point to new objects that is new objects may be injected into old objects. For example in a queue etc. Thus, we may have to scan old objects again and again, which is against the idea of generation hypothesis.
    • Generation hypothesis is not true in certain cases
      • Caching
        • Caches have Expiry time.
        • Objects, least recently used are removed fastest.
        • The longer object stays The higher is the chance of getting it kicked out.
        • Caches don’t go by generation hypothesis.
      • Queue
        • Let us suppose we have a Queue With six objects and front point to one.
        • After sometime, First three objects move to old generation and let us say front of Queue changes from 1 to 5.
        • Now 1,2,3,4 Are technically dead because there is no incoming pointer to them. But garbage collector is going to run on old generation less frequently so they will stick around. Since three is pointing to 4 and three is in old generation, thus he has a dirty bloom filter tick Where card table says four Has to be alive, which is in young generation.
        • Thus the object which has to be dead in young generation is still staying.
    • The old objects are keeping young dead objects alive. This is called as Nepotism In garbage collection.
    • Basically, some objects get promoted without being deserving to get promoted.
    • Kafka helps to overcome this problem. They have interesting paging mechanisms.
    • Garbage collector algorithm like Shenandoah Also get around this by getting rid of generation hypothesis
      • Shenandoah was introduced in Java 11, but was improved in Java 12.
  • JIT code injection
    • We use a concept called code injection here.
    • In .class file The JIT sees The place where the old generation is going to make a pointer to the young generation.
    • When ever we make a right operation, it updates the card table. There are a bunch of bits that tell which parts of the old generation point to the New generation objects. It acts like a bloom filter.

How can memory leaks occur in Java even with automatic garbage collection?

  • When objects are Initially held in memory when they are no longer needed.
  • If an object is referenced by a static field, which belongs to a class.
  • Object stored in collection and not removed when they are no longer needed.
  • Not registering callbacks can keep objects alive unnecessarily. Since the objects holding these resources cannot be garbage collected.
  • Objects which are no longer required, but are present in heap and garbage collector is unable to remove them.
  • Most common causes of memory leaks are
    • Excessive use of static methods
    • Unclosed resources
    • Improper equals() And hash code() Implementations
    • Excessive session objects
    • Poorly written custom data structure
  • Prevent memory leaks in Java
    • Do not create unnecessary objects
    • Avoid string concatenation and use string builder.
    • Do not store a massive amount of data in a session.
    • Time out the session when no longer needed.
    • Avoid the use of static objects because they live for the entire life of the application by default, so it is better to set the reference to null explicitly.
    • Always close, the result, set, statements and connection objects in the finally block.

What is the difference between young generation and old generation memory spaces?

  • Once the object is initialised, it is allocated in young generation.
  • We can specify memory via XMX flag Where we can provide total memory for both generations that is young generation and old generation.
  • If application is multithreaded, then it is going to allocate to a thread local allocation buffer.
    • Each thread Independently allocate its data, or variables In different sections Which is marked as pointers that is start pointer of thread and end pointer of thread.
    • After First garbage collection, the object from young generation start moving into survivor spaces.
      • We can define the size of survivor space using flag called as Survivor ratio Which contains value from and to.
      • The allocation happens from young generation to 1st survivor space after first interval, and then after some of the defined intervals, the objects switch among themselves From one Survivor space to another And finally, they enter old generation.
  • How many objects will go into the old generation is defined by the maximum turning threshold.
    • So if the maximum turning fresh hold is 15, then 15 times, objects are going to switch from one survivor space to another And finally, which ever object survive after turning threshold are moved to old generation.

How can we maintain code quality?

  • Linter
  • Solid principles
  • Clean code
  • Create feature BRANCH while merging to environment branches
  • Code review, preferably, create a reviewer per repository.

What is Auto boxing?

  • We used to have int, long.
  • We may require object and not primitive type.
  • Conversion of object type to Payment type involves use of autoboxing.
  • Wrapper Classes are example of Auto boxing.
  • Certain libraries like collection and hibernate makes it mandatory for us to use wrapper classes

What is delegation principle?

  • Delegation is an alternative to inheritance.
  • We use the object of another class as an instance, variable and forward the message to the instance.
  • Does not force us to accept all methods.
  • Delegation is a relationship between objects.
  • Advantage is runtime flexibility. The delegate can easily be change at runtime.

How substring can create memory leaks?

  • The reason behind The substring() method Memory leaks is.In the older versions of JDK, when a substring was created, from a parent string, the created substring object maintained a reference to the parent string.

What is intern method in string?

  • Returns a canonical representation for the string object.
  • Object pool of strings is initially empty and is maintained privately by the String class.
  • When the internet method is involved, if the pool already contains a string equal to the string object object, as determined by the equals(object) Method, then the string from the pool is returned. Otherwise, String object is added to the pool, and the reference of the string object is returned.
  • All literal Strings are string, valued, constant expressions, and interned.

If a class is not civilised while transferring between layers, what will happen??

  • We get class, not serialised Exception.

When do we override the hashcode method?

  • When there is too much collision between the objects Comparison, we should override the hash code method.
  • When we have a very big address and we want to convert it into a small value which can be integer, hexa decimal, et cetera, we should override the hash code method.

What is the difference between == and equals method?

  • == and equals
    • == is shallow comparison
    • It checks for reference.
  • Equals
    • This is a deep comparison
    • It checks for content rather than reference.

What is the equals and hash code contact?

  • If two objects are equal according to the equals(object) Method, then the hash code of both the object must be the same(hexadecimal value)
  • It is not necessary that if we have same hash code for two objects, then the two objects are equal. This is called collusion. Better hash function prevents this.
  • Whenever it is invoked on the same object, more than once during an execution of a Java Application,The hash code method must consistently return the same integer.

What does the equal method in object class compares by default?

  • Equals method in object class by default, compares methods by the hashcode() method result or hexadecimal number.

What’s the Difference between Array,ArrayList and Generic List?

  • Array is a list of fixed size of objects.
    • We can store only similar type of data in array
    • It belongs to system.Array
  • Array List can store only object type of data.
    • It is a part of collection framework.
  • List can store generate type or any similar type of data.

Does Array Support General concept in Java?

  • We cannot generate generic arrays Directly in Java, because array Support only one type.
  • We can create an array of objects and cast the components to required generic type.
    • Class genericArray<T> {
    • Private T[] arr;
    • }

What is the difference between shallow copy and Deep copy?

  • In shallow copy, when we create a copy of object The reference of objects, coupled with the object Is created.
    • If we change the property of referenced object In one object, it also to induce in the copied object or vice versa.
  • In deep copy, a separate reference is created of the objects, coupled with the deep copy.
    • Changes to one object, object does not impact changes to other object.

What is difference between context Path and class path?

  • Application loader Loads classes from class path.
  • Path is provided as part of application.It is for reference of operating system.
  • Class path is specific to JVM And is loaded by application loader.

What is transient in Java and where it is used?

  • Transient is used in serialisation process So, if we are transforming an object, and we do not want that some properties of that object to take part in serialisation Process, then we make them transient. By using transient keyword along with them, we can also use static keyword along with that.
  • So these values will not be transferred to Destination class.
  • When we deserialize We will not get exact values of these properties, but we may get default values for these properties. 

There is a parent class and child class.If parent class is Serialisable, then child class is also serialisable. How can we restrict child class entirely to be serialisable, able or a part of it to be restricted as serialisable?

  • We can Use constructor to restrict this override the object class method and restrict.

What is the garbage collector in Java?

  • Garbage collector checks for object objects to which do not have a reference in application. It collects such objects and makes them eligible for the garbage collection. 
  • We can request compiler for garbage collection by calling system.GC().It removes unnecessary objects from the heap memory.
  • Garbage collection in Java frees memory by removing objects that are no longer used.This prevents Java from memory leaks.
  • Finalise is called by Garbage collector on an object when it is determined that there are no more references to the object.
    • It cleans up the object resources before it isdeleted like file, streams, or network resources, et cetera.

Are there, any other Alternative approaches to check heap space as garbage collector may not run immediately on calling system.GC.

We can use finally block and close the resources there in. We can also define statements implicitly to block for example try(File f=new File()) So that once the operation ends The resources are automatically destroyed.

What is the internal implementation of Hash Set?

  • Hash set Does not allow duplicates Whenever we want to add any element to the hash set.It will check the element hash code Whenever we are trying to add any element it will check for hash code of element. If the hash code is present in set, it is not going to add in the hash set. If it is not present, it will check with the equals method with that available elements in the set.If the equal method returns false Then it will add element into the set as it will not insert into the set.
  • Hashset Internally stores values as hash map where the key is the valuable provide in the Hashset And value is “PRESENT” a constant for all keys.

What is Enum in Java?

  • Enum is like a class but has a fixed set of properties, so whenever you want to have some fixed set of properties, we use Enum.It has advantage over classes that is, it is more valuable in message of security. That is, we cannot get a copy of that object object using reflection framework.
What is serialization in Java?
  • Need to re-create objects into its original state in different JVM.
  • Serialization converts object into a stream of bytes for easy shipment of information.
  • Saves the state of the object for recreation without having to be reprocess them in different platform or different JVM.
What is the importance of Serial Version UID in serialization of objects?
  • Serial version UID helps in versioning of classes.
  • Serial version UID Maintains the state of a class.
  • Any changes to the class by Another JVM gives INITIAL CLASS STATE Exception.
  • If we have a serialized class and it changes before it’s be deserialized then the new version should have backward compatibility or JRE should inform about new version.
  • Serialization in Java provides a versioning mechanism for this.
  • The unique version identifier is the 64-bit hash of the class name, interfaces, methods and fields.
  • If we do not add serial version ID it is generated by default by JRE at the run time with the help of Serialization mechanism.
  • Both the name of the class and Serial version UID are written to the object stream.
  • During deserialization again serial version UID is generated and compared with the previously written serial version UID.
    • If there is a mismatch then invalid class exception will be thrown.
  • If we add a serial version UID to a class We can even deserialize it after making changes to the class.
    • Adding a serial version UID provides backward version compatibility to a class.
  • If we don’t add a serial version UID then after making changes at deserialization the JRE will create its own new UID and hence we cannot deserialize old objects.
  • If we have a serial version UID Then we must change UID on each change to class to enforce new version.
  • Serial version UID is used for versioning of the serialized streams.
  • When we think class has grown in a way that it is not compatible with the previous version then we can change the serial version UID.
  • Serial version UID Is declared as private static final long and it is always better to declare one to have control over the class.
  • It is used to maintain state of the class.
  • We do serialisation to save the state of an object.
  • When we deserialise The object we need to get it in same state and we use  serial version ID to maintain it state. 
  • Every jvm has its own implementation for serial version ID. so if we try to show some object using different implementation, then it will throw illegal state exception. 
  • We should declare serial version id manually.

Why constructors cannot be final,static, or abstract in Java?
  • If we set a method as final it means we do not want any class to override it. But the constructor cannot be overridden. So there is no use of marking it final.
  • If we set a method as abstract it means that it has no body and it should be implemented in a child class but the construct is called implicitly when the new keyword is used. Therefore it needs a body.
  •  If we set a method as static it means that it belongs to the class but not particular object. The constructor is always call to initialise an object therefore there is no use of marking construct a static.
Can we inherit a Constructor?
  • No, Java does not support inheritance of constructor.
What is the value returned by constructor in Java?
  • When we call a constructor in Java, it returns the object created by it. That is how we create new objects in Java.
Can we achieve Method Overloading by changing the return type of method only?
  1. In Java, method overloading is not possible by changing the return type of method only because of ambiguity.
Can we overload java main() method?
  1. Yes, we can have any number of main methods in a class by method overloading.
  2. This is because JVM always calls main() method which recieves string array as arguments only.
What is automatic promotion in Java?
  1. One type is promoted to another Implicitly if no matching datatype is found as per below diagram

 package javaimplant.inheritance;  
 public class automatic_promotion {  
      void show(int a) {  
           System.out.println("int method");  
      }  
      void show(String a) {  
           System.out.println("String method");  
      }  
      public static void main(String args[]) {  
           automatic_promotion ap = new automatic_promotion();  
           ap.show('a'); // calls int method
      }  
 }  
In the above case int method will be called.
 package javaimplant.inheritance;  
 public class automatic_promotion {  
      void show(Object a) {  
           System.out.println("object method");  
      }  
      void show(int a) {  
           System.out.println("int method");  
      }  
      void show(String a) {  
           System.out.println("String method");  
      }  
      public static void main(String args[]) {  
           automatic_promotion ap = new automatic_promotion();  
           // calls int method if we comment/remove int method it will call object method  
           ap.show('a'); // calls int method
           ap.show('abc'); // calls String method
      }  
 }  
In the above case also int method will be called but if we  comment or remove int method then object method will be called as it promotes to parent class if method is unavailable for a type.
 package javaimplant.inheritance;  
 public class automatic_promotion {  
      void show(Object a) {  
           System.out.println("object method");  
      }  
      void show(int a) {  
           System.out.println("int method");  
      }  
      void show(int...a) {  
           System.out.println("varargs method");  
      }  
      void show(String a) {  
           System.out.println("String method");  
      }  
      public static void main(String args[]) {  
           automatic_promotion ap = new automatic_promotion();  
           ap.show('a');  
           ap.show('a','b');  
      }  
 }  
In the above case when we pass multiple arguments varargs method will be called.

Which types of inheritance Java supports and Java does not supports?
  1. Inheritance which java supports using classes are as follows
    1. Single
    2. Multilevel
    3. Hierarchical
  2. Inheritance which Java does not supports using classes are
    1. Multiple
    2. Hybrid
  3. Multiple and Hybrid class Inheritance causes Ambiguity problem in Java that is why these are not supported.
  4. For Multiple Inheritance we can use Interfaces which can be used as a reference to objects but cannot be initialized.
  5. Constructors and Private methods are not inherited in Java.
  6. All classes by default inherit Object class.
  7. A class cannot have more than one super/parent class.
How do we perform unit testing in Java using JUnit?
  1. Unit testing is a type of software testing where one individual piece of code or unit is being tested by itself.
  2. Unit tests isolate one single piece of code and verifies that that piece is working correctly.
  3. Add JUnit as a dependency in the dependency management tool you are using.
  4. We should try to get maximum code coverage using our Unit test cases.
    1. Use tools like Ecl Emma in eclipse to get code coverage from your test cases
    2. To run a test case in Eclipse simply debug/run the Unit Test class file as JUnit Test.
    3. If the code coverage plugin(Ecl Emma) is installed in Eclipse you will get option coverage as Junit Test Case.
    4. For Example for following class
      1.  package javaimplant.junitTest;  
         public class Grader {  
              public char determineGrade(int numberGrade) {  
                   if(numberGrade < 0) {  
                        throw new IllegalArgumentException("Number Grade cannot be less than 0");  
                   } else if(numberGrade < 60) {  
                        return 'F';  
                   } else if (numberGrade < 70) {  
                        return 'D';  
                   } else if (numberGrade < 80) {  
                        return 'C';  
                   } else if (numberGrade < 90) {  
                        return 'B';  
                   } else {  
                        return 'A';  
                   }  
              }  
         }  
        
    5. Following Test provides full coverage
      1.  package javaimplant.junitTest;  
         import static org.junit.jupiter.api.Assertions.*;  
         import org.junit.jupiter.api.Test;  
         class GraderTest {  
              @Test  
              void fiftyNineShouldReturnF() {  
                   var grader = new Grader();       
                   assertEquals('F', grader.determineGrade(59));  
              }  
              @Test  
              void sixtyNineShouldReturnD() {  
                   var grader = new Grader();       
                   assertEquals('D', grader.determineGrade(69));  
              }  
              @Test  
              void seventyNineShouldReturnC() {  
                   var grader = new Grader();       
                   assertEquals('C', grader.determineGrade(79));  
              }  
              @Test  
              void eightyNineShouldReturnB() {  
                   var grader = new Grader();       
                   assertEquals('B', grader.determineGrade(89));  
              }  
              @Test  
              void ninetyNineShouldReturnA() {  
                   var grader = new Grader();       
                   assertEquals('A', grader.determineGrade(99));  
              }  
              @Test  
              void ninetyShouldReturnA() {  
                   var grader = new Grader();       
                   assertEquals('A', grader.determineGrade(90));  
              }  
              @Test  
              void eightyShouldReturnB() {  
                   var grader = new Grader();       
                   assertEquals('B', grader.determineGrade(80));  
              }  
              @Test  
              void seventyShouldReturnC() {  
                   var grader = new Grader();       
                   assertEquals('C', grader.determineGrade(70));  
              }  
              @Test  
              void sixtyShouldReturnD() {  
                   var grader = new Grader();       
                   assertEquals('D', grader.determineGrade(60));  
              }  
              @Test  
              void zeroShouldReturnF() {  
                   var grader = new Grader();  
                   assertEquals('F', grader.determineGrade(0));  
              }  
              @Test  
              void negativeShouldReturnIllegalArgumentException() {  
                   var grader = new Grader();  
                   assertThrows(IllegalArgumentException.class,() -> {  
                        grader.determineGrade(-1);       
                   });  
              }  
         }  
        

What are Records in Java?
  1. Records are used in Java to remove excess code in entity classes.
  2. For example if we have an entity class employee our traditional code would be like.
    1.  package javaimplant.records;  
       import java.util.Objects;  
       public class EmployeeClass {  
            private final String employeeName;  
            private final int employeeNumber;  
            public EmployeeClass(String employeeName, int employeeNumber) {  
                 super();  
                 this.employeeName = employeeName;  
                 this.employeeNumber = employeeNumber;  
            }  
            public String getEmployeeName() {  
                 return employeeName;  
            }  
            public int getEmployeeNumber() {  
                 return employeeNumber;  
            }  
            @Override  
            public int hashCode() {  
                 return Objects.hash(employeeName, employeeNumber);  
            }  
            @Override  
            public boolean equals(Object obj) {  
                 if (this == obj)  
                      return true;  
                 if (obj == null)  
                      return false;  
                 if (getClass() != obj.getClass())  
                      return false;  
                 EmployeeClass other = (EmployeeClass) obj;  
                 return Objects.equals(employeeName, other.employeeName) && employeeNumber == other.employeeNumber;  
            }  
       }  
      
    2. Above is a lot of code just to hold 2 fields.
  3. With records we can reduce the code as follows
    1.  package javaimplant.records;  
       public record Employee(String name,int employeeNumber) {}  
      
  4. Java automatically generates private fields for the class of parameters given in Record.
  5. It also generates public getter methods without appending "get" for example for above code getter would be "name()" and "employeeNumber()".
  6. It automatically creates a constructor with fields. This constructor is called as a canonical constructor.
  7. It automatically generates implementation of the toString(), equals() and hashCode() methods.
    1. We can override these methods with our implementations if required.
  8. It does not generate any setter methods
    1. So records are immutable by default.
  9. We can add our methods in a record.
  10. We can also add static fields, static methods.
  11. Records can't extend any other class.
  12. All Java records implicitly extends Record class like Enums which implicitly extend the enum class.
  13. Records are implicitly final classes which means they can't be extended by any other class either.
  14. We can implement interfaces in the records.
  15. We can define our own constructors overriding the default canonical constructor.
  16. We can also use a compact constructor in records.
Do you think 'main' used for main method is a keyword in java?
No, main is just a name of method. There can be multiple methods with same name main in a class file. It is not a keyword in Java.

Explain the JVM architecture?
JVM consists of three parts which process the “.class” file
  1. Class loader subsystem
    1. Loading
      1. Bootstrap class loader
        1. Used to load files from rt.jar.
        2. Bootstrap class path 
        3. All core Java API classes are loaded
      2. Extension class loader
        1. Classes present inside EXT folder
        2. JDK,JRE, Lib, EXT folders.
        3. Extends bootstrap class loader.
      3. Application class loader
        1. Classes are loaded from sec/java path.
        2. Extends extension class loader.
    2. Linking
      1. Verify
        1. Check weather code is prepared by genuine Loader, compiler etc.
      2. Prepare
      3. Resolve
    3. Initialization
  2. Memory areas present inside JVM
    1. Method area
      1. Class data
    2. Heap area
      1. Object data
      2. Object reference in a stack are stored in heap With following areas
        1. Instance, variable area
        2. Instance, function area
    3. Stack area
      1. Contains runtime stack for every thread.
      2. Each stack frame contains three areas local   Variable array, Operand stack, frame data.
      3. Each entry in stack is called as stack frame.
      4. Every method has its own stack.
    4. PC Registers
      1. Contains register for each thread
      2. Contains next instruction to be executed by Thread.
    5. Native method stacks
      1. For native methods only
  3. Execution engine
    1. Interpreter
    2. JIT compiler
      1. Intermediate code generator
      2. Code optimizer
      3. Target code generator
      4. Profiler decides which function should be JIT compiled
    3. Garbage collector
    4. Security manager
  4. Java native Interface (JNI)
    1. Provides native method libraries
Why people say that Java is ‘right once and run  anywhere language’?
  1. You can write Java code on windows and compile it in Windows platform. The class and jar files that you get from Windows platform can be run as it is on UNIX environment. So it is truly a platform independent language.
  2. Behind all this probability is Java byte code byte code is generated by Java compiler that can be interpreted by any JVM. So it becomes much easier to write programs in Java and expect those to run on any platform.
  3. Java compiler Javac compiles Java code and JVM Java runs that code.
How Java platform is different from Other platforms?
  1. Java is a platform independent language. Java compiler converts Java code into byte code that can be interpreted by JVM. There are JVM written for almost all the popular platforms in the world.
  2. Java byte code can run on any supported platform in same way. Where as other languages require libraries compiled for specific that form to run.
How does a Class Loader Work in Java?
  1. In Java, ClassLoader is a class that is used to load files in JVM.ClassLoader loads files from their physical file locations e.g. Filesystem, Network location etc.
  2. There are three main types of ClassLoaders in Java.
    1. Bootstrap ClassLoader: 
      1. This is the first ClassLoader. 
      2. It loads classes from rt.jar file.
    2. Extension ClassLoader: 
      1. It loads class files from jre/lib/ext location.
    3. Application ClassLoader: 
      1. This ClassLoader depends on CLASSPATH to find the location of class files. 
      2. If you specify your jars in CLASSPATH, then this ClassLoader will load them.
Illustrate with Example ClassLoading and Arguments in JVM?
  • JVM does not load 2 classes with same name.
  • Let's create 2  classes with same name and package them into 2 separate jar files.
  • We create their class files by compiling them and then package them into 2 separate jar files.
    • We will use command jar -cvf first.jar * to create a jar.
  • Next we will load these two jar files in our CLASSPATH.
    • We use the following command
      • set CLASSPATH=F:\tmp\second.jar;F:\tmp\first.jar
  • Let us check which of the class gets loaded
    • Let us now execute class HelloWorld using "Java HelloWorld"
    • We find that the class which was loaded first in class path is executed i.e the jar which was added first to the classpath is executed.
  • Now lets check with JVM arguments.
    • Lets now pass argument to change the heap size twice using 2 different values.
      • Let's pass the argument to change the heap size i.e. -Xmx128m -Xmx512m
        • We use the following command
          •  java -Xmx128m -Xmx512m HelloWorld
      • Next get the process Id of Java from the task manager or using command/shel of your operating system.
      • Using jinfo lets get the MaxHeapSize of the process
        • jinfo -flag MaxHeapSize 5604
          • Here 5604 is the processId
        • The Response is
          • -XX:MaxHeapSize=536870912
      • We get that the argument passed later is taken by jvm
  • So in case of classes JVM loads the first one in case of arguments JVM loads the latest one
How many types of Memory areas are allocated by JVM?
  1. Class(Method) area : 
    1. It stores per-class structures Such as  runtime constant pool, Field and method data, and the code for methods.
    2. Static Variables, Static Methods, Non Static Methods are stored in this area.
    3. If this memory is not sufficient JVM will throw out of memory error.
  2. Class Loader: 
    1. It is a component of JVM used to load class files.
  3. Heap
    1. Heap is created runtime and it contains the runtime data area in which objects are allocated.
    2. It is a run-time data area in which the memory is allocated to the objects.
    3. Heap stores data that has longer life time span than a code block for example objects that can be shared across multiple methods.
    4. A heap is shared by all the threads.
    5. All objects are stored on heap.
      1. The reference to these objects is stored on a stack
      2. An object in heap may be referenced by multiple stacks.
    6. "new" keyword is used to find a space on heap enough to store the object.
    7. Non static variables of class are also stored in heap area.
  4. Stack
    1. Stack Stores local variables and partial results at runtime. It also helps in method invocation and return value. Each thread creates a private JVM stack at the time of threat creation.
    2. Java stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.Each thread has a private JVM stack,created at the same time as the thread.A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
    3. Each Frame is divided into 3 parts
      1. Local Variable Storage Area
      2. Operand Stack
        1. All operations on variables stored in above part occur in this part. 
      3. Frame Data
        1. Exceptions arising out of exceptions are stored here.
    4. Every thread in Java has its own stack.
    5. Java decides when data on Stack can be destroyed.
    6. Each time we call a function java pushes the local variables of that function on stack.
      1. The local variables of the function includes its arguments as well.
    7. When a new method is called the stack is pushed with new variables and copy of any passed variable from the last method is created.
    8. When we reach the closing curly bracket all local variables within that bracket are pushed out from the stack.
    9. All primitive types are pushed on stack.
    10. When we exit from a code block all local variables in that block are popped out.
    11. Each thread has its own stack so data on the stack can be seen only by owned thread. 
  5. Program Counter Register :
    1. This memory area contains the address of the Java virtual machine instruction that is currently being executed. 
    2. PC(Program Counter) register contains the address of the Java Virtual Machine instruction currently being executed.
  6. Native Method Stack :
    1. This area is reserved for all the native methods used in the application. 
    2. It contains all the native methods used in the application.
    3. Methods in c, c++ used in program are stored here
What is the difference between JDK,JRE and JVM?
  1. JDK(Java Development Kit)
    1. Contains tools and libraries for development of Java Programs.
    2. It also contains Compilers, and Debuggers needed to compile Java Programs
    3. JDK stands for Java development kit. It contains the tools and libraries for development of Java programs. It also contains compilers and debuggers needed to compile Java program.
  2. JRE(Java Runtime Environment)
    1. JRE provides libraries  and JVM that is required to run a Java Program.
    2. JRE stands for Java runtime environment. 
    3. This is included in JDK.
    4. Java interpreter is a part of JRE.
    5. JVM + Libraries equals JRE
  3. JVM(Java Virtual Machine)
    1. JVM stands for Java Virtual Machine
    2. An abstract machine that executes java bytecode.
    3. JVM is platform dependent.
    4. It is the software in the form of interpreter written in C language through which we can execute our Java programs.
    5. JVM is responsible for loading, verifying and executing the Bytecode  on a platform.
What is JIT(Just In Time Compiler)
  1. Just In Time compiler also known as JIT compiler is used for performance improvement in Java. It is enabled by default. It is compilation done at execution time rather earlier. Java has popularized the use of JIT compiler by including it in JVM.
Define the scope of a static variable?
  1. A variable declared as static is shared by all the instances of the class and its subclass instances.
What is the difference between J2EE and J2SE?
  • J2SE
    • Also known as Core Java, this is the most basic and standard version of Java.It’s the purest form of Java, a basic foundation for all other editions. 
    • It consists of a wide variety of general purpose API’s (like java.lang, java.util) as well as many special purpose APIs.
    • J2SE is mainly used to create applications for Desktop environment.
    • It consist all the basics of Java the language, variables, primitive data types, Arrays, Streams, Strings, Java Database Connectivity(JDBC) and much more.
    • This is the standard, from which all other editions came out, according to the needs of the time.
    • The famous JVM of Java, the heart of Java development, was also given by this edition only.It’s because of this feature, that Java has such a wide usage.
  • J2EE
    • The Enterprise version of Java has a much larger usage of Java, like development of web services, networking, server side scripting and other various web based applications.
    • J2EE is a community driven edition, i.e. there is a lot of continuous contributions from industry experts, Java developers and other open source organizations.
    • J2EE uses many components of J2SE, as well as, has many new features of it’s own like Servlets, JavaBeans, Java Message Services, adding a whole new functionalities to the language.
    • J2EE uses HTML, CSS, JavaScript etc., so as to create web pages and web services. It’s also one of  the most widely accepted web development standard.
Can we write main method as public void static instead of public static void?
  • NO,The modifiers must come before the return type though the order of modifiers can change.
  • We can write static public void main() instead of public static void main()
If we do not specify value for local variables then what will be the default value of the local variables?
  • Java does not initialize local variables with any default value. So these variables will be just null by default.
What is the difference between byte and char datatypes in Java
  • Both byte and char are numeric data types in Java.
    • They are used to represent numbers in a specific range.
  • A byte can store raw binary data where as a char stores characters or text data.
  • Byte values range from -128 to 127.
  • A byte is made of 8 bits, but a char is made of 16 bits. 
    • So it is equivalent to 2 bytes.
What is the default value of an object reference defined as an instance variable in an object?
  • All the instance variable object references in Java are null.
Why do we need constructor in Java?
  • A constructor is a piece of code similar to a method. It is used to create an object and set the initial state of the object. 
  • A constructor is a special function that has same name as class name.
  • By default, Java provides a default constructor for every object.
    • If we overload a constructor then we have to implement default constructor.
  • Without a constructor, there is no way to create an object.
Why do we need default constructor in Java classes?
  • Default constructor is the no argument constructor that is automatically generated by Java if no other constructor is defined.
  • Java specification says it will provide a default constructor if there is no overloaded constructor in a class. But it does not say anything about the scenario in which we write an overloaded constructor in a class.
  • We need at least one constructor to create an object, that’s why Java provides a default constructor.
  • When we have overloaded constructor, then Java assumes that we want some custom treatment in our code. Due to which it does not provide default constructor. But it needs default constructor as per the specification. So it gives error.
What is the use of "Keytool" command in JDK?
  • Java Keytool is a digital certificate management platform where the software developer keeps all certificates and private keys in a single place. 
  • The Java Keytool Keystore is the perfect solution to maintain the flow of trust and validation of all required certificates.
    • The command to generate a Java keystore and keypair:
      • keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
    • The command to generate a certificate signing request (CSR) for an existing Java keystore:
      • keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr
    • The command for importing a root or intermediate certificate to an existing Java keystore:
      • keytool -import -trustcacerts -alias root -file Thawte.crt -keystore keystore.jks
    • The command for importing a signed primary certificate to an existing Java keystore:
      • keytool -import -trustcacerts -alias mydomain -file mydomain.crt -keystore keystore.jks
    • The command to generate a keystore and a self-signed certificate:
      • keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
    • The command for checking a standalone certificate:
      • keytool -printcert -v -file mydomain.crt
    • The command for checking which certificates are in a Java keystore:
      • keytool -list -v -keystore keystore.jks
    • The command for checking a particular keystore entry using an alias:
      • keytool -list -v -keystore keystore.jks -alias mydomain
    • The command for deleting a certificate from a Java Keytool keystore:
      • keytool -delete -alias mydomain -keystore keystore.jks
    • The command for changing a Java keystore password:
      • keytool -storepasswd -new new_storepass -keystore keystore.jks
    • The command for exporting a certificate from a keystore:
      • keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
    • The command to view a list of trusted CA certs:
      • keytool -list -v -keystore $JAVA_HOME/jre/lib/security/cacerts
    • The command for importing new CAs into your trusted certs:
      • keytool -import -trustcacerts -file /path/to/ca/ca.pem -alias CA_ALIAS -keystore $JAVA_HOME/jre/lib/security/cacerts
When you should make a variable public?
  1. The variable should have no con-vincible reason to ever change in its implementation.
    1. This should be specifically taken care when variable is used in a library/framework.
  2. The variable needs to be referenced frequently enough that the minimal gains from reducing verbosity warrants it.
  3. An example of a public variable is "out" in "System.out".
What is a Stub?
  1. Stub is used to describe a function that is declared and callable, but has no effect.
  2. It is used as a placeholder for the real implementation to be done at a later time.
Difference between Static Import and Regular Import?

Here we will discuss the difference between static import and regular import in java

i.e
Difference in

import java.lang.character.*

import static java.lang.character.isUppercase

Ans :
The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes and packages ,allowing them to be used without a package qualification

The static import declaration imports static members from the classes allowing them to be used without class qualification.
We should use a static import very sparingly only use when we have tempted to declare local copies of constants or to abuse inheritance.

Use it when you require frequent access to static members from 1 or 2 classes.

Example

i.
import static java.lang.character.isUppercase
if(isUpperCase(symbol))
{
}

ii.
import java.lang.character.*
if(character.isUppercase(symbol))
{
}

Q What happens if you have a parameterized constructor but do not define a no-argument constructor in you class?

Ans 
The compiler will give a runtime error.
There was an unexpected error (type=Internal Server Error, status=500).
No default constructor for entity: : com.springimplant.votingsystem.entity.Citizen; nested exception is org.hibernate.InstantiationException: No default constructor for entity: : com.springimplant.votingsystem.entity.Citizen

What are the different operations that can be performed on String?
Ans
  • Joining strings 
  • comparing strings
    • ==, equals
  • String interning
    • intern()
    • explicit/implicit
  • Start and end of String
    • startsWith(),endsWith()
  • Sequencing strings
    • compareTo()
  • Accessing string connectors
    • CharAt();
  • Searching
    • indexOf()
    • lastIndexOf()
    • substring()
  • Token
    • split()
    • replace()
    • trim()
    • toCharArray()
    • getChars()
    • getBytes()
Why Java is not hundred  percent object oriented?
Ans
  • Because of primitive their types namely boolean, byte, char, int, float, double, long, short.
  • To make them object oriented we have the wrapper classes which actually “wrap” the primitive data type into an object of that class.
  • Primitive types are not objects.
Why pointers are not used in Java?
Ans
  • They are unsafe
  • Increases complexity of the program and since Java is known for it’s simplicity of code, adding the concept of pointers will be contradicting.
  • Since JVM is responsible for implicit memory allocation, does in order to avoid direct access to memory by user pointers all discouraged in Java.
What is JIT compilation in Java?
Ans
  • Once code is converted to bite code it goes into JRE which has interpreter and JIT compiler.
  • Since the interpreter is slow In converting byte code to machine code the JIT compiler converts bunch of lines from byte code to machine code which makes this process faster.
  • It compiles the byte code To machine level code.
Why String is immutable in Java?
Ans
  • String pool requires String to be immutable otherwise shared reference can be changed from anywhere.
  • Security because string is stored on different area like filesystem, networking connection, database connection, having immutable string allows you to be secure and safe because no one can change reference of string once it gets created.
What Is Marker interface?
Ans
  • A marker interface can be defined as the interface having no get a member and member functions. And empty interface is called S Michael interface example serializable, cloneable etc.
  • These are just marker interfaces which tells your Compiler that you have something special to do with the class like stop cloning or serializing object etc.
Can we overload static methods in Java?
  • Yes, we can overload static method in Java. We can have two or more static methods with the same name, but different parameters.
Can you override private or static method in Java?
Ans
  • We cannot override a private or static method in Java.
  • We cannot override a private method in sub class because it’s not accessible from there, what you do is create another private Method with the same name in the child class.
  • For static methods If you create a similar method with same return type and same method arguments In child class then it will hide the super class method,This is known as method hiding.
  • We can call static method from both class name and object offense too.
Does finally always execute in Java?
Ans
  • Not in Following cases
    • System.exit() Function
    • System Crash
  • In all other cases of try, catch, finally will always execute.
What methods does the object class have?
Ans
  • Protected object clone() Throws clone not supported exception.
    • Creates and returns copy of this object.
  • Public Boolean equals()
    • Indicates whether some other object is equal to this one.
  • Protected void finalize() throws throwable
    • Called by the garbage collector on an object when garbage collection determines that there are no more References to the object.
  • Public final class getClass()
    • Returns the run time class of an object.
  • Public int hashcode()
    • Returns a hashcode value for the object
  • Public String toString()
    • Returns a String representation of the object.
  • Public final void notify()
  • Public final void notifyAll()
  • Public final void wait()
  • Public final void wait (long timeout)
  • Public final void wait (long time out, int names)
How can you make our class immutable?
  • An Immutable class generates Immuratble objects in Java.
    • Immutable Objects are objects which cannot be changed.
  • Declare the class as final so it can’t be extended.
  • Make all fields private and final so that direct access is not allowed.
  • Don’t provide setter methods for variables.
  • No Getter method can return a data field that is mutable.
  • If there is a getter method that returns an object this object should be immutable.
  • Make all mutable fields final so that its value can be assigned only once.
  • Initialise all the fields via constructor performing a deep copy.
    • Create a parameterised constructor.
  • Perform cloning of Objects in the getter methods to return copy rather than returning the actual object reference.
  • If you we are using any mutable members, like Hash set, set, Priority queue, stacks, list perform a deep copy in constructor and get method.
  • An immutable object Is an object whose contents cannot be changed.
  • The values of the data fields of immutable objects cannot be changed.
  • Sometimes we want to create an object whose contents cannot be changed, once the object is created. Such an object is called as an immutable object, object and its class is called as an immutable class.
  • The string class is immutable, class and string objects are immutable objects.
  • Example
What is singleton and how can we make a class singleton? 
  • Singleton class is a class who’s only one instance can be created at any given time in one JVM.
  • To create a Singleton class
    • Make constructor private.
    • Create a static null instance of that class.
    • Create a static getter block and check for above instance if it is null create a new instance and return else return the old instance.
Finally, block is used when in Java.
  • It is used when we need to perform some cleaning operations.
  • Even if there is exception, finally will execute.
  • If we want to perform Some activity activity after an operation, we use finally
In serialisation, if we do not want to serialise Any data member, so what keyword we will use?
Transient is used to stop serialisation of member variable.

Are static keyword serialised?
Static keyword will not play A role in serialisation But if we use default constructor to initialise it, then that concept will be used to initialise it each time, but they are not the deserialised.

What is Cohesion and Coupling?
  • Coupling signifies “has a” relationship. One module has dependency with other module. We use dependency injection to inject one module into Another module.
    • If dependency injection is not implemented, then it is called as tight coupling.
    • In dependency injection dependency on caller and not on implementer.
  • Cohesion is based on open close design principle.
    • Any implementation should be open for extension and close for modification.
    • It should work for all parameters
    • Redundancy in code should not be there.
What is Auto boxing in Java?
  • Auto boxing is related to the wrapper class. 
  • To convert primitive type to wrapper type/object type We require Auto boxing.
  • We may require an object sometimes, and not primitive type.

Monday, August 5, 2024

Java Persistence API

What is Second Level Caching in JPA?
What is the difference between hibernate and JPA?
  • JPA defines the specification. It is an API.
    • Provides following definitions
      • How we define the entities
      • How do we define primary key?
      • Who manages the entities?
      • How we map attributes
    • JPA stands for Java persistence API
    • The JPA specification was developed by Java as a standard way to map objects to relational databases.
    • JPA just provides specification It does not provide the implementation.
    • So we cannot use JPA By itself, we need to use a JPA provider That implements that JPA framework Like eclipselink, toplink and hibernate.
    • The advantage of using a framework that implements the JPA specification Is that you can easily switch the framework.
    • So if we are using top link, we can easily change our framework to eclipse link or hibernate without having to change code.
    • If we use JPA methods In our code, we will be easily able to switch to some other JPA provider Like eclipse link or top link.
    • Spring Data JPA Is an abstraction layer on top of JPA To reduce the amount of boiler plate code required to implement data access object(DAO) layer.
    • Spring data JPA Uses hibernate as a default JPA provider.
    • Spring data JPA cannot work without a JPA provider.
  • A JPA repository abstracts our database operations.
  • Hibernate is an implementation of JPA
    • Using hibernate directly would result in a lock into hibernate.
      • There are other JPA implementation available like top link, et cetera.
    • When we use hibernate in our code, we can use the proprietary methods Off hibernate, or we can use the JPA methods implemented by hibernate.
    • Hibernate is a Java based ORM Tool that provides a framework for mapping application domain objects to Relational database tables, and vice versa.
    • Hibernate is a JPA provider(JPA specification implementation) Spring data JPA is not a JPA provider. It simply hides the Java persistent API.(And the JPA provider) Behind its repository Abstraction.
What is the difference between @Entity and @Table annotations in JPA?
  • We can use the name attribute of the @Entity annotation to provide an explicit entity name to match with the database table name. For our example we could have used @Entity(name = “tbl_address”) in our Address class if our table name was tbl_address.
    • @Entity is needed for annotating a POJO class as an entity
  • We can use a @Table (defined in the javax.persistence package) annotation just below the @Entity annotation and use its name attribute to specify the table name explicitly
    • @Table is optional
Q What are the difference values of spring.jpa.hibernate.ddl-auto?
Ans 
  • Create
    • Drops and Creates the tables whenever we start the server
  • Create-Drop
    • Drops all the tables as soon as we stop the server.
    • Recreates them fresh when we start the server
  • update
    • Only updates the database when we start the server.
  • insert
  • validate

Friday, August 2, 2024

Java 8

 What is map-reduce in streams?

  • Map-Reduce is a functional programming model which serves our 2 purpose.
    • Map- Transform Data
    • Reduce- Aggregating data
  • It combines element in a stream and produces a single value.
  • Example stream of integers and to calculate sum of those integers.
  • Map Transform Stream<Object> to Stream Int.
  • Reduce - Combine Stream of Integer and produce the sum result.
  • T reduce(T identity,BinaryOperator<T> accumulator);
    • Identity is initial value of type T.
    • Accumulator is the function for combining two values.
  • Integer someResult  = Stream.of(2,4,6).reduce(0,(a,b)->a+b);
  • Reduce is used for Aggregation.

Can we override default method in an interface?

  • Yes, we can override default method in an interface
  • When we are implementing two interfaces with same method, and we want a particular interface to be used, we override The default method in interface to select, which one of the two interfaces will be used.
  • The syntax is Interface. Super. Method().

What are the benefits of using streams?

  • A stream is a pipeline Of aggregate operations that process a sequence of elements.
  • Behaviour parameters exclamation simplify coping with changing requirements.
  • A stream is conceptually , unbounded, though it is often bound by practical constraints.
  • They are concise and readable.
  • Focus on what function should perform instead of how to perform them.
  • Flexible that is functions or automatically compared together output of one becomes input of another
    • Thus, we can perform multiple operations at once.
  • Stable that is parallel performance without The need to write any multi-threaded code.
  • Parallel streams run from a pool of threads And the pool used is common fork join pool.
    • Common fork join pool is a singleton.
    • It works on task, stealing
  • We don’t have to worry about thread management.
  • Threads created are called as worker threads.
    • Thread safe code is there in parallel streams
  • Data is automatically mapped to processor cores.
  • In a non-stream, the flow is sequential Which is not a good approach and stream provides para processing making it faster.

What is lazy evaluation in streams?

What is the difference between static methods and default methods in an interface?

  • Static methods in interfaces is similar to default methods, just that it’s static. Hence its implementation cannot be changed in child classes.
  • Implementing class need not and cannot change the definition
  • Static methods of interface can’t be overridden.If they are overridden, then That process is called as method hiding.
  • These are called through interface Name that is interface.static method name.
  • Interface, static method helps us in providing security by not allowing implementation classes to override them.
  • Interface, static methods are good for providing utility methods, for example, null checking, I.e Who’s definition will never change.

Why Java 8 was introduced?

  • Significant reason four introducing Java eight was to introduce conciseness in code.
  • Java brings in functional programming which is enabled by Lambda expressions.
  • With Python,Scala we can do the same thing in very less LOC. Java upgraded it’s self from only object oriented programming structure language to some concepts of functional programming to create concise code base.
Q What are the new features that got introduced in Java eight?
  • Lambda expressions
  • Streams API
    • This was an enhancement in collection framework
      • We can have Intermediate methods
      • We can have terminal methods
  • Default methods in the interface
  • Static methods in the interface
  • Functional interface
    • This introduced functional programming.
    • As a part of functional programming we get lambda, we get method references.
  • Optional
  • Method references
  • Date API
    • This is a dedicated package for time
  • Nashhorn, JavaScript engine
Q What are the main advantages of using Java eight?
  • Compact code
  • More readable and reusable code
  • More testable code
  • Parallel operations
Q What is lambda expression?
  • Lambda expression is and anonymous function without having (name, return type and access modifier) and having one lambda symbol (->).
  • Example
Normal Programming Equivalent Lambda Expression
public void add(int a,int b) {
    System.out.println(a+b);
}
BiConsumer<Integer,Integer> biConsumer = (a,b) -> System.out.println(a+b);
  • Remove name, return type, access modifier and types of arguments from the function to get lambda function.
  • In the above example a,b has been inferred from a functional interface such as Bi Consumer which takes in arguments and give output has nothing.
    •      BiConsumer<Integer,Integer> biConsumer = (a,b) -> System.out.println(a+b);
    •      biConsumer.accept(5, 10);
Q What are functional interfaces?
  • Functional interfaces all those interfaces which have only one abstract method.
  • It can have any number of static method, default methods. No restriction on that.
  • There are many Functional interfaces already present in Java such as example comparable, runnable.
  • Functional interfaces are used as a reference to lambda expressions.
Q How can we create our own functional interface?
  • As we know functional interface Is an interface with exactly one single Abstract method and can have multiple static or default methods.
  • To create our own functional interface
    • Create an interface
    • Annotate that with @Functional Interface
    • Define exactly one abstract method.
    • There is no restriction on number of static and default methods defined in such an interface.
    • Java can implicitly identify functional interface but still you can also annotate it with @functional Interface.
      • It just gives you security that in case if you by mistake add 2 abstract methods then compiler will give a compile time error.
Q What is method reference in Java 8?
  • Method reference is replacement of lambda expressions.
  • It is used to refer method of functional interface to an existing method.
  • Mainly it is used for code reusability.
  • Functional interfaces abstract method can be mapped to specific existing method using double colon operator(::)
  • This is method reference.
  • Hence method reference is an alternative to Lambda expression.
  • Whenever we have existing implementation of abstract method of our functional interface then we can go for method reference.
  • Example of method reference 
  •  @FunctionalInterface  
     public interface FunctionalInterfaceDemo {  
     void singleAbstractMethod();  
     }  
     public class Test {  
     public static void testImplementation() {  
          System.out.println("This is an distinct Method");  
     }  
     }  
     public class MethodReferenceDemo {  
          public static void main(String[] args) {  
               FunctionalInterfaceDemo functionalInterfaceDemo= Test::testImplementation;  
               functionalInterfaceDemo.singleAbstractMethod();  
          }  
     }  
    
  • So we see in class method reference demo we can replace lambda expression with method references.
  • If we do not have a method Reference then only we can use is Lambda expressions which is called as Single Abstract Method.
Q What is difference between method reference and Single Abstract Method?
  • In a single abstract method we only have a functional interface with abstract method. We can only use lambda expressions.
  • In a Method reference We also have a class with another abstract method which defines its implementation.
Q What is the advantage of using functional expression in lambda?
  • Enable functional programming
  • Readable and concise code
  • Easier to use API and libraries
  • And enable support for parallel processing.
  • We can pass behaviour as the argument to the object.