Java Interview
- Introduce about Java Programming Language
- Java is object-oriented programming language and it’s one of the most popular languages in the world.
- It’s a high security language and often used to build large software systems like ecommerce or banking.
- It’s famous for its write one and run anywhere feature or in other word; it’s crossplatform programming language.
- Compare for me following three concepts JDK, JRE and JVM
- Talk about the different between three concepts:
- JVM stands for Java Virtual It considers as a heart of whole application. It transfers byte code into machine code and runs the application. That’ the reason why java can run in multiple plassform.
- JRE is an evironment to execute Java It consists of JVM and nesscessary libraries like Java.Lang, Java.Utils. It can run applications because it has JVM but it doesn’t have any complier so it just execute complied code.
- JDK stands for Java Development Kit. It consists of JRE and some development tool like javac complier and debugging JDK focuses on development purpose while jre focuses on executing application.
- Talk about the different between three concepts:
- Why Java is platform-independent?
- Because it has Firstly, java source will be compiled into bytecode by Javac compiler and after that JVM is responsible for interpreting bytecode into machine code and this process don’t depend on platform/
- Compare to stack memory and heap
Heap |
Stack |
Java Heap Memory is the memory used at runtime to store Objects. Whenever anywhere in your program when you create an Object it will be stored in the Heap (execute the new operator) | Stack Memory is memory to store local variables in functions and function calls at runtime in a java Thread. Local variables include: primitive types,
reference types to objects in the heap (reference), declarations in functions, or arguments passed to the function. |
Objects stored in the heap are globally accessible | Stack memory is used only by one thread of execution. |
Heap’s management mechanism is more complex. Heap is divided into 2 types Young-Generation, Old-
Generation. (Garbage Collection) |
The operating mechanism is LIFO (Last-In-First- Out) |
Heap memory lives from the start till the end of application execution. | Stack memory is short-lived. |
- Pass by value and pass by references?
- There are two kinds of passing machenism in Java:
+ Pass by value: It indicates that we pass primitive variables into a method as an argument. And in that method, a copy parameter will be created, and it copies the value of arguments, and it has its own memory space. All the changes we made with copy
parameter will not affect to actual parameters outside the method.
+ Pass by reference: We pass a reference variable as an arguments into a method. And in that method, a copy of that variable is created, and it refers to the same location of the object in heap memory. Any changes we made with the object inside that method will be reflect to outside scope because, we have changed real object.
- Pass a wrapper class into a method is pass by value or pass by reference?
- It’s pass by value because wrapper class in Java is When you try to change the value of a wrapper class, JVM create a new wrapper class with the value we just changed
- Can we override the main method?
- No, we can overload main method, but we can’t override main method because the main method is static method and static method can’t be overriden
- Why is the main method being static method?
- Because the main method is the entry point of whole application. JVM have to execute the main () method to start application so it needs to be loaded into main memory so that JVM can be find it and execute beacause the static method will be loaded into main memory by class loader.
- Can override the static method?
- No, we can’t override static methods because some following reason:
+ The static method belongs to a class, not belong to any specific instance of class. It will be share between all the instance of that class
+ Static method is bond at the compiler time, and it’s loaded into main memory by class loader before application execution while the overriding method is based on dynamic binding at runtime. So, we can’t override static method.
- Advantages and disadvantages of OOP?
- There are many advantages of OOP like:
+ OOP can model complex system and make it more simplier
+ Reusibilty
+ It has high security level through encapsulation pillar
+ It’s easy to extend and maintain
- Disadvantages:
+ It more complicated to learn and understand OOP
- Compare Java and C
- Java is an OOP language so it has the features and advantages of OOP but it has compiler time slower than C because Java needs to interprete from bytecode to machine code while C can compile directly source code to machine code.
- The pillar of
- The first and I think the most important of OOP is Abstraction is used to model the relevant attributes and interactions between entites as classes and define an abstract representation of a system. We can achive abstract pillars in OOP through abstract class or interface.
- Encapsulation is when you wrap up your data under a single To achive encapsulation, you must:
+ Declare class field with private access modifier
+ Provide public getter and setter method to access and update the value of private variable
- Inheritant: it allows subclass to reuse all the attributes and method from parent class except private There are three kinds of inheritance in OOP. There is single inheritance, multi level inheritance and hierarchical inheritance
- Polymorphism: It’s expressed by you can execute an action in various ways. There are two types of polymorphsim: compile-time polymorphism achive by overloading method and runtime polymorphism achive by overloading method.
+ For example, about runtime polymorphism: we start with three classes: animal class, dog class and cat class. Animal class has abstract method is speak () and dog class and cat class extend from animal class, and it has its own speak () method. We created a reference variable of animal class. And we can create an instance of Cat class or Dog class. The speak () method is call will be belonged to this instance. Or in other way, the calling method is decided by JVM, not compiler, so it’s polymorphism at runtime
- Compare to overloading and overriding method
No. | Method Overloading | Method Overriding |
1) | Method overloading is used to increase the readability of the program. | Method overriding is used to provide the specific implementation of the method that is already provided by its super class. |
2) | Method overloading is performed within class. | Method overriding occurs in two classes that have IS-A (inheritance) relationship. |
3) | In case of method overloading, parameter must be different. | In case of method overriding,
parameter must be same. |
4) | Method overloading is the example of compile time polymorphism. | Method overriding is the example of run time polymorphism. |
5) | In java, method overloading can’t be performed by changing return type of the method only.
Return type can be same or different in method overloading. But you must have to change the parameter. |
Return type must be same or covariant in method overriding. |
- Does java support multiple inheritance?
- Java does not support multiple inheritance through class, but we can achive that through interface. In Java, a class can implement multiple inteface and an interface can extend multiple But when we use multiple inheritence. However, we need to carefully with multiple inheritances because it can cause diamond problems. For example, we have class A implement 2 interface is interface B and interface C. Two interface have method ed has the same name. So, there is an ambigous to know whether method from interface B or interface C will be called.
- Compare abstract class and interface
Abstract Class |
Interface |
Expression of abstraction < 100% | 100% Abstraction |
An abstract class can have abstract and non- abstract methods | Java version < 8 Interface can only have abstract method.
Java 8 version can add default and static methods. Java 9 version can add private methods |
Abstract class does not support multiple inheritance | Interface supports multiple inheritance |
Abstract class can have final, non-final, static and non-static variables | Interface has only static final variables |
The abstract keyword is used to declare an abstract class | The interface keyword is used to declare Interface |
Use Abstract class when we can only complete a few standard functions (method/function) of the system, some of the remaining functions extend classes have to complete. These finished features are still usable as usual, these are general features. | Use Interface when you want to build a standard framework of functions (method/function) that all modules/projects need. Modules must implement all defined functionality. |
- What is the main purpose of interface?
- Interface helps us get abtraction and especially, it can be used to lose coupling between modules. It’s related to a principle from SOLID principles (Dependecy Inversion). The high-level module shouldn’t depend on low level module, but both should be dependent on share abstraction and its And with Spring Boot framework, there are two mechanisms created to do that. This’s denpendency injection and Inversion of controller
- Can we create objects from abstract class and interface?
- We can not create objects from abstract class or interface directly, but we can create an instance of class implement that interface or extend that abstract And because, we have polymorphism pillar of OOP, so we can create reference variable has data type of that interface or abstract class and create an instance for that variable is an instance of class implement interface or extends from abstract method.
- Enum in Java?
- Enum is like a special class in java, and it’s represented for a group of
- Acess modifier in Java?
- There are four access modifiers in Java
+ Private: We can only access private modifier within a class, not outside the class
+ Default: We can access default modifier within the same package
+ Protected: We can access protected modifier within the same package and different package but it’s subclass
+ Public: We can access public modifier any where
- When should we use a private constructor?
- It allows to restrict instantiation of That means, we can prevent creating an instance of a class any place other than class itsself.
- There are some scenarios that we often use private contructor
+ Singletton Pattern
+ Delegate Constructor: allow us to pass parameter through several different constructor but the constructor is private, and it only can be use in class itsself
+ Create uninstantiable class or util class: it’s a class containing a collection of static methods and we can’t create an instance with this class.
+ Builder Pattern: It allow us to create an instance of complex object step by step rather than having public contructor to create instance
- Advantage of builder pattern:
+ Easy to read and understand
+ Prevent missing information with class has constructor with many parameters
+ Check constraint of field or validate information of the class
+ Create immutable class: We don’t have any setter method in the class, we can only create instances of a class through static class builder inside that class.
- Where are static member stores?
- Static member store in method Method area stores all the class level data like the name and the data type of field, methods and byte code that have been compiled. It aslo store the data of static member
- Method area is a part of heap memories which is share among all the threads
- Static member store in method Method area stores all the class level data like the name and the data type of field, methods and byte code that have been compiled. It aslo store the data of static member
- Can place static variables inside a non-static method?
- Yes, of We can place static variables inside static method or non-static method but inside a static method, we only can use static member, we can not use non-static method.
- What is the relationship between static storage and mutiple thread?
- Static members are stored in the method area or in other words, static members stored in main So other threads want to get the static data will go to the main thread and method area to get the data. So, because static members are shared among all the threads so it’s not thread-safe. We can use sychoronization mechanisms to protect the static member.
- When should we use static block?
- A class can have multiple static blocks
- We can use the static block to initialize the value for static member in a Static block always executes one time at the class loading time and before the main method is execute.
- We also can use static blocks for building singleton patterns or read the configuration
- When is static data loaded?
- Static data is loaded at the time of class loading and it will be loaded by Class Loader
- Is it possible to call the static member through object?
- Yes, of We can call static member through object but it’s not recommened and instead of that, we can call static member through class name because about definition, static data belong to class, not bleong to any instance of that class
- How to check an object is an instance of class?
- We can use instaneof keyword to check that whether an object is an instance of class
- Can we overload static method?
- Yes, of we can overload static method, but we can not override static method.
- What is nested class, static class and inner class?
- Java allows declare a class inside another Class inside another class is called nested class and class contain another class is called outer class. Nested class declare with static keyword will be static class other it will be inner class.
- There is different point between static class and inner class:
+ Static class can initialize without instance of outer class, but inner class only exist if it was wrapper by an outer class
+ Inner class can access both static and non static member from the outer class, but static class only can access the static member from outer class.
- When we should use static class:
+ Nested class help program more readable, reusible and easy to maintain
+ We can model a part of a system or outer class into a nested class, or we can create some data structure inside outer class
- Talk about private keywords in Java?
- Final keyword in Java is used to restrict user action
- With final keywords, we have final variable, final method and final class
- Final variable: In Java, a final variable is declared with final keyword and then you won’t be able to change that variable. Or in a simple word, it’s constant
- Final method: A final method is declared with final keyword so that subclass will not be able to overridde that method
- Final class: when a class is declared with final keyword, it can not be inherited
- How many ways to initialize for final variable?
- There are three ways to initialize value for final variable
+ We can initialize values for final variable at the declared time. And if you don’t initialize for final variable at the declared time, it will be blank final variable. And we can initialize for blank final variable in constructor or static block. And if you have many constructors you have to initialize for final variable at all the constructor otherwise, it’ll be throwing an exception
- How to create an immutable class in Java?
- An object is immutable if it cannot be change after initializing
- Because immutable objects can not be changed so every time we try to update the information in that class, actually, we have create another But immutable objects also have some advantages:
+ An immutable object is good for caching purpose, because you don’t worry about the value change
+ Immutable class support thread safe in mutiple thread
- There are some conditions if we want to an immutable class:
+ Keep class is private so it can not be inherited
+ Make all the field of class is private so it can not be access directly
+ Don’t provide setter method for variable
+ Initialize all the field in a constructor performing deep copy
+ when you manipulate with the object, you return a copy object using construct rather than return the actual object reference
- More convinent, you can use builder pattern to create immutable
- What’s the purpose of equal method?
- In Java, equal method is used to compare two objects based on some specific condition like the value of field.
- How about equal operator?
- With equal operator, you compare two objects through their reference
- Relationship between equal method and hashCode method?
- The relationship between equal method and hashCode method is like a
+ If two objects are equal, they must have the same hashCode
+ If two objects have the same hashCode, it can equal or not equal.
- What is the purpose of the overriden method and when we can use the override method?
- In OOP, method overriding can understand as a subclass can provide specific implementation of a method and that method already provide the implementation by parent class.
- The condions of method overriding
+ Two methods must have the same name, the same return data type and data type of parameter and it’s can not be final method or static method
- When we log an instance of a class, it will return a The meaning of that hashCode and if we want to write the content of Object. How can you do that?
- The string return when we log an instance of a class is the name of class and hashcode of that instance
- If you want to wirte the content of that instance, you must override the toString method
- What is exception and exception handling?
- An exception is an event that disrupts the nomarl follow of the
- Exception handling is a mechnism that by which the normar follow of program will be maintained if exeption happens
- What is the difference between error and exception?
- Error in a program is irrecoverable. That means, when an error occurs, the program will terminate There are several common errors like OutOfMemmories error and StackOverFollow error.
- Exceptions are on the other That mean we can recover them by exception handling
- What are different types of exception?
- There are two types of exception:
+ Checked Exception: All the exceptions other than Runtime exceptions and error are knowns as checked exception. It will be checked by compiler and thrown at the compiler time. There are some common checked exceptions like SQL exception, FileNotFoundException and IOException
+ Unchecked exception or Runtime exception: Unchecked exception won’t be checked by compiler, and it will be thrown at the runtime. There are some common runtime exceptions like NullPointerException, ArrayIndexOutOfBoundException or ArithmethicException
- How is exception handling done in Java?
- Try catch block is used for exception handling. If you think a block code can throw an exception, you can surround them with a try block, and catch block will catch them and handle exception. Therefore, the normal follow of program will be maintained
- How to handle mutiple exception together?
- We can write mutiple catch block and each catch block for one exception or you can
write single catch block with multiple exception and separate exception by pipe symbol.
- When we write multiple catch block, we must follow bellow rules:
+ Handle the most specific exception at the first and move down for the most generic exception
- Try with resource?
- Try with resource is the short form of try block and finally It will close all the resources automatically when the trial block is done.
- What is different between throw and throws keywords
- Throw is a keyword which is used to explicitly throw an exception in the program inside a method or inside a block code whereas throws keyword is used to with methd signature to declare an exception may be occur in that And when we use throws keyword, we notify for the caller method have to handler that exception or transfer that exception down to previous caller
- Throw keyword follow by an instance of exception class while throws keyword folow by Exception class.
- You can only throw one exception at a time, but you can declare mutiple exception with throws keywords.
- Using throw keyword, only unchecked exception can be propagated whereas using throws keywords, both checked and unchecked exception can be propagated.
- What is the advantage of throws keywords:
+ It helps the code more clearly and help the developers can handler exception without missing the exception
+ It supports checked exception propagation and throw don’t support checked exception propagation
- Tell about exception handling method overriding?
- Exception handling method overriding must follow by some rules:
+ If the parent class method does not declare any exception, the child class override that method can’t not declared checked exception. It only can declare uncheked exception.
+ If the parent class method declared an exception, the child class override from that can do some following action like:
- Can declared no exception
- Can declared same exception
- Can declared narrower exception than parent class method
- How to make your own custom exception?
- In Java, you can easily create your own custom exception class which extends from Exception class and if you want to create your own custom runtime exception class, you can extend from RuntimeException class.
- What happens when you throw exception from finally block?
- When an exception is thrown from finally block, it will take precedence over exception thrown from try catch block
- How to compare two String object?
- If you want to compare two String object based on some specific attributes, you have to override the equal () method.
- If you compare two objects by the equal operator, it will compare by reference
- Why String is immutable?
- String is immutable because of somes below reasons
+ String Pool: String pool is possible if only String is immutable.
If String is mutable, changing the String with one reference will lead to change with all references
+ Security: Spring parameter often used in network connection, database URL, username and password. Because String is immutable, this value cannot be changed, otherwise hackers can’t change the important information like username and password, they will take the
program permission.
+ Multithread: Because String is immutable, it’s safe for multiple thread.
+ Caching: String is often used for caching purposes and beacause String is immutable, we don’t worry ablout that value can be changed.
- What is String pool?
- String pool is a special storage area in heap memories. It is used to improve the performance of the It like a cache memory contains all the String literals. When
we create a String Object with String literal. First, it will be check in the string pool whether that String literal have existed in String pool or not. If it has existed, it will be return that String literal otherwise it will be creating a new one and return it.
- What is String Builder and String Buffer?
- Both String Builder and String Buffer are That mean use can change the value of String object.
- The difference between String Buffer and String Builder is String Builder using asynchronous mechanisms, so it has a faster speed but not safe for multiple On the other hand, String Buffer using synchronous mechanism, so it has slower speed compared to Spring Builder, but it is thread safe
- String and String builder, which is faster?
- String Builder is faster because it changes the value of its own object while String is immutable and when we manipulate with String object, we create another String object
- Tell me about ArrayList?
- ArrayList in Java is used as a dynamic array to store
- Can contain duplicate elements
- Maintain the orders of elements added
- Asynchornous mechanisms
- Speed of accessing elements is very fast because it’s stored data by index
- The operator of adding or removing elements is very slow because a lots of shiffing is required
- Tell me about properties of LinkedList?
- It uses Double LinkedList Data Structure to store elements
- Can contain duplicate elements
- Maintain the order of elements added
- Asynchronous mechanisms
- The speed of accessing elements is slower than ArrayList because it must traverse through all the elements of linkedlist.
- What is the difference between ArrayList and Array?
- Array has fixed size, so the size of array can not be changed after initializing. On the other hand, array list has dynamic size, so it will be automatically increase when we add an element and exceed the size of that ArrayList.
- Array can hold both primitive data type and reference data type, but ArrayList only can hold reference data type and if you want to store primitive data type in ArrayList, you must use wrapper class
- ArrayList provide many utilities method to help manipulating with collection easier
- Compare ArrayList and Linked List
ArrayList | Linked List |
ArrayList uses dynamic array to store elements. | LinkedList uses a linked list (Doubly Linked List) to store elements. |
ArrayList is an index-based data structure, where each element is associated with an index. | The elements in the LinkedList are called nodes, each node needs to store three pieces of information: the reference of the previous element, the value of the element, and a reference to the next element. |
Adding and removing elements with ArrayList is slow because it uses arrays internally. Because after adding or removing elements need reordering. | Adding and removing elements with LinkedList is faster than ArrayList. Because it doesn’t need to rearrange the elements after adding or removing. It simply updates the reference to the element before and after it. |
Retrieving elements in ArrayList is faster than LinkedList. Because the elements in the ArrayList are stored based on the index (index). | Retrieving elements in LinkedList is much slower than in ArrayList. Because, it has to iterate through the elements from first to last. |
ArrayList can only act as a list because it only implements the List interface. | LinkedList can act as an ArrayList, stack (queue), queue, Singly Linked List and Doubly Linked List because it implements List and Deque interfaces. |
ArrayList is better at storing and retrieving data (get). | LinkedList is better at data manipulation (add/remove). |
- Tell me about vectors?
- Can contain duplicated elements
- It maintains the ordered of elements added
- The most different between vector and arrayList is vector is synchornous and thread-safe while ArrayList is asynchornous and is not thread safe in multiple thread
- Talk about Queue Interface?
- There are two class implementations Queue interface: LinkedList and Priority Queue
- Priority Queue using Heap data structure to store elementsand it sorts all the elements through Comparable or Comparator interface
- There are two class implementations Queue interface: LinkedList and Priority Queue
- Java support pass by value or pass by reference?
- Java only supports pass by value C++ programming language supports both pass by value, pass by reference, and pass by pointer.
- In Java, when use pass a reference variable into a method, you pass the value of that
variable to the method, and inside the method, a copy of that variable is created, and it’s point to the same object in heap memories.
- What is the difference between pass by variable and pass by pointer in C++
- With pass by reference, another variable is created inside the method, and it points to the same memory as original variable, but we can’t point that variable into another memory during method operation.
- With pass by pointer, it is like passing a reference variable in Java, it passes the memory addess of variable into a method, at in that method we have changed the value of that
- What is the difference between List and Set?
- There are two main point different between Set and List
+ List can contain duplicate elements, but Set can not contain duplicate elements
+ Lists maintain the orders of elements added but Set don’t maintain the orders of elements added except LinkedHashSet.
- Why HashSet can’t contain duplicated elements and can’t main the order of elements?
- HashSet can’t contain duplicated elements because inside HashSet, it uses HashMap to store the elements and the elements of HashSet are the key of HashMap in key, value pair, and the value of that key is a dumpy And because the key is unique, therefore HashSet only contains unique elements.
- Hash Set can not maintain the orders of elements because it uses the hash algorithm to implement and in the hash Map, the key will be caculate by hash function and it returns the hashCode, and it store element in a bucket base on the hash code. So, it can not maintain the order of elements added.
- Compare Hash Set, LinkedHashSet and TreeSet
HashSet | LinkedHashSet | TreeSet | |
How to work? | uses HashMap internally to store elements. | uses LinkedHashMap internally to store elements. | uses TreeMap internally to store elements. |
Order Of Elements | HashSet does not maintain any order in which elements were added. | LinkedHashSet maintains the insertion order of the elements. Elements are stored in the correct order in which they were inserted. | TreeSet maintains the order of elements according to the provided comparator (Comparator). If no comparator is provided, the elements will be placed in their natural ascending order. |
Performance | HashSet gives better performance than LinkedHashSet and TreeSet. | LinkedHashSet falls between HashSet and TreeSet. Its performance is almost similar to HashSet. But slightly slower as it | TreeSet gives lower performance than HashSet and LinkedHashSet because it has to sort the elements |
also maintains an | after each insertion and | ||
internal LinkedList to | removal. | ||
maintain the insertion | |||
sequence of the | |||
elements. | |||
Insertion, | O(1) performance | LinkedHashSet also | TreeSet gives O(log(n)) |
Removal and | for inserting, | offers O(1) | performance for insert, |
Retrieval | removing, and | performance for | remove, and retrieve |
element | retrieving | inserting, removing, | elements. |
operations | elements. | and retrieving | |
elements. | |||
Compare | HashSet uses | LinkedHashSet also | TreeSet uses compare() or |
elements | equals() and | uses equals() and | compareTo() methods to |
hashCode() | hashCode() methods to | compare elements and thus | |
methods to | compare elements. | remove possible duplicates. | |
compare elements | |||
and thus remove | |||
possible | |||
duplicates. |
Null element | HashSet allows up to one null element. | LinkedHashSet also allows up to one null element. | TreeSet does not allow null elements. If you try to insert null into the TreeSet element, it throws NullPointerException. |
- You add an element already exist in How did JVM do that? Equal () method and HashCode () method, which one call first.
- When you add an element into SET, first, it will hashCode () the value and hashCode () value is the bucket identifier. If there is no bucket exist with the same hashCode, it will create new one and store elements in that, otherwise it will traverse through that bucket to check whether there is no one element with the same key exist in that bucket by equal method or not, if no one exist, it will create a new one otherwise, it will ignore that element
- What is the difference between HashMap, TreeMap, LinkedHashMap
- Compare to HashMap and ConcurrentHashMap
- HashMap use asynchronous mechanism and it’s not thread safe
- ConcurrentHashMap use synchonous mechansm and it’s safe for multiple thread
- HashMap allow store one null key and many null values, but the ConcurrentHashMap don’t support store null key or null value
- Compare Hashtable and HashMap
- It supports synchronization mechanism, and it’s safe for multiple thread unlike the HashMap
- HashTable don’t support stored any null key and null value while the HashMap supports store one null key and multiple null value
- About performance, ConcurrentHashMap will better than HashTable beacause ConcurrentHashMap using multiple lock for each bucket while Hashtable only use one lock for all buckets inside it
- What is a thread pool?
- Thread pool is a software design And it uses a collection of worker threads to execute asynchronous tasks. It helps save the resourece and improvement of program.
- When a thread completes a task, it’ll return to thread pool and thread pool will assign it for another task. We must do that because opening and closing a thread take a lot of
resuorce and it make program slower. We must take advantage of existing thread instead of creating a new one
- Compare Comparable and Comparator Inteface?
- For object type, if you want to sort the elements in a collection, you need to provide a comparator. There are two ways to provide comparator for collection: Comparable and Comparator interface.
- Here is some different point between Comparable and Comparator interface:
Comparable |
Comparator |
Comparable provides only one way of comparison. That is, we can only compare by id or name, or age, … | Comparable provides a variety of comparisons. That is, we can sort based on many factors such as id, name, age, … |
Comparable modifies the original class, that is, the comparable object’s class must modify and implement the Comparable Interface to implement. | Comparator does not change the original class. We can create a new class that implements the Comparator Interface to implement. |
Comparable provides compareTo () method to compare two elements. | Comparator provides compare () method to compare two elements. |
Any list can be sorted using the
Collections.sort(List) method. |
Any list can be sorted using the Collections.sort(List, Comparator) method |
- Which Java version, you often use? Why do you use it?
- I often use Java 8. Java 8 is recommended by many people beacause it has many
important improvements of Java programming language and it also have very large user community.
- Tell me about some improvement of Java 8 compared to previous version?
- There are many improvements of Java 8 compared to previous version such as:
+ Default method, static method
+ Fuctional Interface
+ Lamda Expression
+ Method Reference
+ Optional
+ Stream API
- What is default method and static method?
- Default method
- The problem before Java 8 version: Class implement interface must provide implementaion for all the method defined in that interface even though it doesn’t need to
use all of them. You can imagine, a very large interface with hundred of methods, this problem can become very big challenge
- The default method is created to overcome this Default method is a method that has default implementaion define in the interface. And class implement implement that interface don’t have to provide their own implementaiton if it is’n necessary
- Static method
- Static method is the same with dafault method and it can’t be overriden, from the class implement the interface.
- It is used to create utility methods inside an interface instead of create another utility
- What is functional programming?
- Functional programming is a programming style based on perform function and it doesn’t change the value of variable. With functional programming, a function can become the input for another dunction. It increases the usablitiy and it paralel programming because the value of variable can not be change
- Compare OOP and funtional programming?
- With the functional programming, funtion is the main unit of operation while with OOP, it’s object
- Fucntion programming support both data and behavior abstraction while OOP only support data abstraction
- Funcitonal Programming have the better performance than OOP on processing big data
- Functional programming does not change the value of outside variable but with OOP, it changes the value of variable
- With functional programming, we can pass a function as a argument into another function but with OOP, it don’t support that.
- What is a functional interface?
- It’s created in Java 8 to support functional programming
- A functional Interface is an interface with only one abstract method, but it can have multiple static methods or default methods.
- We can use lamda expression to create an instance of
- There are some predefined functional iterface in Java 8:
- Predicate<T>:
+ Represent predicate of a one argument
+ It has one abstract method name Test have one parameter and return a boolean value.
+ It’s used in filter or removeIf method in Stream API
- Supplier<T>
+ It represents for supplier of result
+ It has one abstract method named get (). That method doesn’t have any parameter, but it returns a generic value.
+ It’s used in generate metho in Stream API or apply for factory design pattern
- Fucntion<T, R>
+ It represents of a function that accepts one argument and produces a result
+ It has one abstract method name apply. That method has one parameter and it returns a value.
+ It’s used in map () method in Stream API
- Consumer<T>
+ It represents for an operation that acept single input and return no value
+ It has one abstract method named accept have one parameter but return no value
+ It’s often used in the ForEach method in Stream API.
- What is lamda expression and purpose of lamda expression
- Lamda expression is a function with no name, no class, no scope and no return type declaration. Lamda expression can be defined as an anonymous function, it can be passed like argument for onother function.
- Why do we use lamda expression?
+ It provides an implementation of functional interface and support functional programming.
+ Help developer write less code and the code can be more readable
+ It’s used in Stream API
- There is a noticable point in lamda expression is that lamda expression cannot change the value of outside variable
- What is method reference?
- Method reference is a spectial type of lamda expression, it’s short form of lamda expression and it’s used to create lamda expression by referencing to existing
- There are some types of method reference:
+ Reference to static method
+ Reference to instance method of object
+ Reference to instance method of an arbitrary object of a particular type.
+ Refernce to constructor of a Class
- Tell me about ForEach loop in Java 8?
- ForEach Loop provide for programmer with a new, concise and interesting way to iterator over collecction
- It will use Consumer interface with a lamda expression to implement abstract method to do some action with each element for iterator loop.
- With the Map, forEach loop will use BiConsumer to iterate over collection
- Tell me about Stream API?
- In java 8, Stream API is released to help programmer caculate with collection more quickly, concise and have better performance with parallel.
- Stream is not data structure; stream is an immutable All the aggregation operation that we perform with collection we don’t change the data source. It only returns a new stream.
- All the operations in Stream API are That means it only performs when necessary or in other words, it only performs when it reach terminate operation like collect (), forEach (),..
- We can not use index to access the element in
- What is Stream Pipeline?
- To perform a sequence of operation over the elements of data source, the Stream API needs to three parts: source, intermidiate operation and terminal operation.
- What is lazy invocation in Stream API?
- Lazy invocation in Stream API can understand as all the immediate operation will not be perfrom until the stream don’t reach to one terminal operation yet. It helps improve performance of program
- Compare map () and platMap () method in Stream API?
- Map is used to transform an element of a Stream API into a new element by applying a function into it.
- The return of map function is a new Stream have the number of elements is the same with original element
- FlatMap is used to transform an element of a Stream into new Stream and merge all the sub stream into a Single Stream
- The retun of flat map is a new stream have the number of element greater than original Stream
- Tell about Optional in Java 8?
- Optional in Java 8 is a container class which is used to contain a single value and that value may be null or not null
- NullPointerException is one of the most common exceptions that programmers take so optional will remind the developer that that variable may be null or not, please be
- Compare finalize object and finalize system?
- Finalize () method of object is used to do some action before that object is collected by garbage collector
- Finallization () method of system is used to required JVM rull all the finallize () method that haven’t been called in the class have finallize () method
- But finallize method don’t recommend and instead of that, we can use try with resoure or implments AutoClosable interface to dispose resource safely
- Tell me about ACID pillar in OOP?
- Automicity: It state that all the operation in a transaciton have to execute successfully, and all the the change will be committed and synchronize with database otherwise, if there is only one operation execute failure, all the change will be ignored, and it will roll back at the state before starting transaction
- Consistency: All the operation in a transaction must guarantee all the contraint or unique with the database
- Isolataion: With isolation pillar, we can have multiple transactions executed concurrently but all of them are independent of each other. That means a transaction can does not see the change of another transaction util that transaction is commit
- Durability: It indicates that when a transaction is committed, all the changes will be apply to the database even though the system is failure like we loose the power. When the server is restart, it will recover and apply all the change for database
- Tell me about isolation level in transaction?
- There are four levels of isolation in a transaction:
+ Read uncommited: It states that a transaction cannot read data from another transaction even though that transaction is not commited
+ Read committed: It states that a transaction can read data from another transaction only if that transaction is committed but, in this level, a transaction can still read or write data from a record that is updated because of another transaction. It’s a phantom problem.
+ Repeatable read: It almost the same with read commited but in this level, a transaction can read or write data into a record in the case that record is updating by another transaction.
Beacause, when a transaction updates a record, it will hold a write lock for that record and
another transaction wants to read or write data into that record have to wait until that write lock is released.
+ Serializable: With this level, when a transaction reads or writes a record, it will be locking that record. It more safely but it can lead to performance problems.
- Tell me about modules in Spring Boot?
- I know some modules in Spring Boot like Starter, Boot AutoConfigure, Actuaror, Test, …
+ Starter is a very important module in Spring Boot. It helps simply the development process by providing a set of default dependencies, configuration for each type of application. For example, in the pom.xml file. I have dependencies springboot-starter-data-jpa, it will container all the dependencies related to JPA and Hibernate, we don’t have to import it
separately.
+ Boot AutoConfigure is also a very important module in Spring Boot architecture. It supports creating a bean automatically. With Spring Boot, we can create a bean through annotations like @Component, @Bean. It helps speed up the development process of application.
+ Actuator: Actuator is a module that help manage and monitor the state of Spring Boot application. With the Actuator module, we can get some information about applications like healths, end point mapping or about the beans.
+ Test Module provide many annotations support testing purpose in Java Spring Boot application
- Compare to stack memory and heap
Heap |
Stack |
Java Heap Memory is the memory used at runtime to store Objects. Whenever anywhere in your program when you create an Object it will be stored in the Heap (execute the new operator) | Stack Memory is memory to store local variables in functions and function calls at runtime in a java Thread. Local variables include: primitive types,
reference types to objects in the heap (reference), declarations in functions, or arguments passed to the function. |
Objects stored in the heap are globally accessible | Stack memory is used only by one thread of execution. |
Heap’s management mechanism is more complex. Heap is divided into 2 types Young-Generation, Old-
Generation. (Garbage Collection) |
The operating mechanism is LIFO (Last-In-First- Out) |
Heap memory lives from the start till the end of application execution. | Stack memory is short-lived. |
Leave a Reply