Friday, May 17, 2024

Connection Pooling

  • When we create a java enterprise application interacting with database is very common.
  • Creating and establishing connection with database is an expensive process.
    • Establish Network Connections
    • Initialize Database sessions
    • Authorize back-end database
  • So it is always a good process to use connection pool in our application.
    • It increases the performance and scalability of application.
  • We can reuse existing connections and prepared statements which helps to avoid the cost of establishing connections.
  • Example of Libraries for connection pooling are "C3P0" and "dbcp" etc.
  • Hibernate c3p0 dependency is used for Connection Pooling in Hibernate?

Monday, September 25, 2023

Java Collection Framework

 What is a difference between list and set?

  • List can contain multiple values with duplicates, whereas set contains multiple values where values cannot be duplicates.
  • Order is maintained in a list, whereas order is not maintained in a set.

Thursday, October 20, 2022

Tools and Technologies for Java Developers

  • Build Management Tools
    • ANT
    • Maven
    • Gradle
  • Front end
    • Angular/React
  • IDE
    • Net beans
    • Eclipse
    • STS
    • IntelliJ 
  • Testing
    • junit
  • Framework
    • Spring
    • Struts
    • Spring Boot
  • Services
    • REST Services
    • Rest Clients
  • Versioning
    • Github
    • Bit bucket
  • Devops
    • CI/CD
    • Jenkins
  • Docker
  • Cloud

Tuesday, August 9, 2022

Static

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

Wednesday, July 13, 2022

Inheritance

Q What is the purpose of this keyword in Java?
  • In Java this keyword refers to current instance of the object.
  • It is useful for differentiating between instance variables and local variables.
  • It can be used to call constructors. Or It can be used to refer to the instance.
    • To call a constructor this statement must be placed at the top of overloaded constructor.
    • For example in a class vehicle 
      • this(“Car”, 4) 
    • Above statement calls an argument constructor from a no args constructor. The no args constructor should have above as first line of code.
  • In case of method overriding, this is used for falling the method of current class.
Q Explain the concept of inheritance?
  • Inheritance is an important concept in object oriented programming. Some objects share certain characteristics and behaviour. By using inheritance, we can put the common behaviour and characteristics in a base class which also known as superclass. And then all the objects with common behaviour inherit from this base class.
  • It is also represented by IS-A relationship.
  • Inheritance promotes, code reuse, method overriding and polymorphism.
  • Child class object carries the body of the parent class when initiated. Moreover there are certain privileges attached to method overloading to the classes related this way. This relationship exists for Code reuse, method overriding and interfacing (through abstract class).
  • Is a relationship can be achieved by using “extends” keyword.
Q Which class in Java is superclass of every other class?
  • Java is an object oriented programming language. In Java, object class is the superclass of every other class.
Q Why Java does not support multiple inheritance?
  • Multiple inheritance means that a class can inherit behaviour from two or more parent classes.
  • The issue with multiple inheritance is that both the payment classes may have different implementation of the same method. So they have different ways of doing the same thing. Now which implementation should the child class choose?
  • This leads to ambiguity in multiple inheritance this is the main reason for Java not supporting multiple inheritance in implementation.
  • Let’s see you have a class TV and another class Steriliser. Both have method switch on but only TV has switch off method. If your class in adults from both these classes then we have an issue that we can switch on both parents but switch off will only switch off TV.
  • We can implement multiple interfaces in Java.
Q What is the difference between abstract class and interface?
  • In interface we do not need to define abstract keyword for methods. All methods are abstract by default.
  • We can implement multiple interfaces but can extend only one abstract class.
  • All data members of interface are static and final. We need to instantiate it with a value. Some values are applied to every object of a class.Data members in abstract class or not same across all the objects
  • If we have a set of closely related classes That have same functionality and same types of fields available we can use abstract class. If we have a set of unrelated classes that we want to achieve certain functionality then we use interfaces.
Q In OOPS what is meant by composition?
  • Composition is also known as “has-a” relationship. In composition, “has-a” relation relates two classes. Example class car has a steering wheel.
  • If a class holds the instance of another class, then it is called composition.
Q What is association?
  • Association is relation between two separate classes which establishes through their objects. Association can be one-to-one, one-to-many, many-to-one, many-to -many.
  • In object oriented programming, an object communicates to other object to use functionality and services provided by that object.
  • There are two forms of association
    • Aggregation
    • Composition
Q How aggregation and composition are different concepts?
  • In OOPS, Aggregation and composition are the types of association relations. A composition is a strong relationship. If the composite object is destroyed, then all its parts are destroyed. Example a car has a steering wheel if the car object is destroyed then there is no meaning of steering wheel.
  • In aggregation, the relationship is weaker then composition.
  • Example a library has students. If a library is destroyed, students exist. So library and student or related by aggregation. A library has books if Library is destroyed then books are also destroyed. Books of a library cannot exist without the library. So book and library Are related by composition.
  • In aggregation without existing container object if there is a chance of existing contained objects, then container and contained objects are weakly associated and this weak association is known as aggregation.
    • For example College consist of several Professors, without existing College, There may be a chance of existing professor objects, hence College and Professor objects are weakly associated and this is known as aggregation.
    • With aggregation,The college also performs its functions through Professor, But the professor is not always an internal part of the college. Professor may be swapped, Or even completely removed. Not only that, but the outside world can still have a reference to the professor, and tinker with it regardless of whether it’s in the college.
    • In aggregation container object holds just reference of the contained objects.
    • final class College {
      • private Professor professor
      • setProfessor();
      • getProfessor();
    • }
  • In composition without existing container object if there is no chance of existing contained objects, then container and contained objects are strongly associated and this strong association is known as composition.
    • In composition container object hold directly contained objects.
    • In the case of composition, the branches is completely encapsulated by the college. There is no way for the outside world to get other friends to the branches. The branches lives and dies with the college.
    • Final class College {
      • private final Branches branches;
      • College(BranchesNames names) {
        • branches = new Branches(names);
      • }
    • }
Q Why there are no pointers in Java?
  • In Java there are references instead of pointers. These references point to objects in memory but there is no direct access to these memory locations. JVM is free to move the objects within VM memory.
  • The absence of pointers helps Java in managing memory and garbage collection effectively. Also it provides developers with convenience of not getting worried about memory allocation and de-allocation.
  • Pointer variable must require static memory allocation but Java has dynamic memory allocation.
  • Pointer variables are supported by static languages in general but Java is a dynamic programming language.
  • Pointers are very suitable in platform dependent languages but Java is platform independent language.
  • Pointer variables refer address locations of data directly which is insecure.
Q What are the difference between pointer variables and reference variables?
  • Pointer variable refers to a block of memory by storing its address location. Pointer variables are recognised and initialised at compilation. Pointers are used in C/C++.
  • In reference variable JVM asks heap manager for memory.In heap depending on the class initialised. Heap manager creates a particular block of memory with an identity which has an integer value called as hash code of the Object. Heap manager returns the hash  code to the JVM. JVM Converts hash code To a hexadecimal value which is called as reference value Of an object. The reference value is assigned to the variable and variable is called as reference variable. Reference variables are recognised and initialised at runtime mainly. Reference variables are used in Java.
Q If there are no pointers In Java, then why do we get null pointer exception?
  • In Java the pointer equivalent is object reference. When we use a pointer it points to the object reference. So JVM uses pointers but programmers only see object references.
  • In case an object reference points to Null object, and we try to access a method or member variable on it, then we get NullPointerException.
Q What is the purpose of ‘super’ keyword in Java?
  • ‘super’ Keyword Is used in the methods or constructor of a child class. It refers to immediate parent class of an object.
  • By using ‘super’ We can call a method of parent class from the method of child class.
  • We can also call the constructor of a parent class from the constructor of a child class by using ‘super’ keyword.
Q Is it possible to use this() and super() Both in same constructor?
  • No, Java does not allow using both super() and this() in same constructor.
  • As per Java specification, super() and this() must be the first statement in a constructor.
Q What is the meaning of object cloning in Java?
  • Object.clone() Method is used for creating an exact copy of the object in Java. It acts like a copy constructor. It creates and returns a copy of the object, with the same class and with all the fields having same values as of the original object.
  • One disadvantage of cloning is that the return type is an object. It has to be explicitly cast to actual type.

Monday, April 25, 2022

Core Java

 What is the difference between Hash-map, Synchronized HashMap, concurrent Hash-map, Hash Table?

  • Hash-map
    • Hash-map is not synchronized by default. 
    • Multiple threads can read and write at same time.
    • Not thread safe
    • Can have one Null key and multiple Null values.
  • Hash-table
    • Thread safe
    • Slow performance
    • NULL key and values are not allowed.
    • Provides lock at object level.
  • Synchronized map
    • Thread Safe
    • Provides lock at object level
    • Slow performance
    • Null key and multiple Null values are allowed
    • Concurrency level cannot be set for better optimization.
  • Concurrent Hash Map
    • Thread Safe
    • Fast performance
    • NULL key and values are not allowed. 
      • If we try to add we get NULL  pointer exception.
    • Introduced in JDK 1.5.
    • Provides a concurrent version of the standard Hashmap.
    • Object is divided into 16 segments (0–15) by default.
    • Depending upon the level of concurrency required the concurrent Hashmap is internally divided into segments.
    • Lock is applied only on write operation.
    • Segment level based locking.
    • Lock is not applied when reading from a segment.
    • Does not throw any Concurrent Modification Exception.
    • Multiple threads cannot write in the same segment.
      • Thread acquires a lock on segment in put() operation and at the time only one thread can write in that segment.
    • Two threads are allowed to write concurrently in different segments.
    • Thread doesn’t acquire a lock on segment in get() operation and any number of threads can read from the same segment.
    • If one thread Is writing in a segment, another thread can read from that segment but in this case last updated value will be seen by the reading thread.

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

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 keyboard 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
    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. 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 Jay 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 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?
  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables.
  • Make all mutable fields final so that it’s value can be assigned only once.
  • Initialize all the fields via constructor performing a deep copy.
  • Perform cloning of Objects in the getter methods to return copy rather than returning the actual object reference.
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.

Thursday, July 8, 2021

Java 8

 Q 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 
  • Default methods in the interface
  • Static methods
  • Functional interface
  • Optional
  • Method references
  • Date API
  • 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 it’s implementation.