Java Skills Flashcards
What are the important features of Java 8 release?
The important features of Java 8 release are:
1. Interface can have default and static methods
2. Functional interfaces(Predicate, Consumer, Supplier, Function) and Lambda Expressions
3. Java Stream API for collection classes
4. Java Date Time API
What are Collection related features in Java 8?
Java 8 has brought major changes in the Collection API. Some of the changes are:
1. Java Stream API for collection classes for supporting sequential as well as parallel processing
2. Iterable interface is extended with forEach() default method that we can use to iterate over a collection. It is very helpful when used with lambda expressions because it’s argument Consumer is a function interface.
3. Miscellaneous Collection API improvements such as forEachRemaining(Consumer action) method in Iterator interface, Map replaceAll(), compute(), merge() methods.
What is overloading and overriding in java?
When we have more than one method with same name in a single class but the arguments are different, then it is called as method overloading.
Overriding concept comes in picture with inheritance when we have two methods with same signature, one in parent class and another in child class. We can use @Override annotation in the child class overridden method to make sure if parent class method is changed, so as child class
What is an interface?
Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.
A java class can implement multiple interfaces.
What is an abstract class?
Abstract classes are used in java to create a class with some default method implementation for subclasses. An abstract class can have abstract method without body and it can have methods with implementation also.
Abstract classes can’t be instantiated and mostly used to provide base for sub-classes to extend and implement the abstract methods and override or use the implemented methods in abstract class.
What is the difference between abstract class and interface?
abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.
Abstract classes can have method implementations whereas interfaces can’t.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run abstract class if it has main() method whereas we can’t run an interface.
What is static keyword?
The static keyword can be used with class level variables to make it global so all the objects will share the same variable.
The static keyword can be used with methods also. A static method can access only static variables of the class and invoke only static methods of the class.
What is static block?
Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class and is executed before main method at the time of classloading. Mostly it’s used to create static resources when class is loaded.
What is try-with-resources in java?
One of the Java 7 features is try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished.
What is multi-catch block in java?
Java 7 one of the improvement was multi-catch block where we can catch multiple exceptions in a single catch block. This makes are code shorter and cleaner when every catch block has similar code.
If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it.
What is Enum in Java?
Enum is a type in Java. Its fields consists of fixed set of constants. For example, in Java we can create Direction as enum with fixed fields as EAST, WEST, NORTH, SOUTH.
enum is the keyword to create an enum type and similar to class. Enum constants are implicitly static and final.
What is composition in java?
Composition is the design technique to implement has-a relationship in classes. We can use Object composition for code reuse.
Java composition is achieved by using instance variables that refers to other objects. Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.
What is ternary operator in java?
Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators.
What is Garbage Collection?
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc().
Types : Serial, Parallel, CMS(Concurrent Mark Sweep), G1
What is difference between Heap and Stack Memory?
Major difference between Heap and Stack memory are as follows:
* Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
* Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
* Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.
What is an Iterator?
Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.
What is the importance of hashCode() and equals() methods?
HashMap uses Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce same hashCode() and equals() output and in that case rather than storing it at different location, HashMap will consider them same and overwrite them.
Similarly all the collection classes that doesn’t store duplicate data use hashCode() and equals() to find duplicates, so it’s very important to implement them correctly. The implementation of equals() and hashCode() should follow these rules.
* If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.
* If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.
What is Comparable and Comparator interface?
Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.
But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Comparator interface because Comparable.compareTo(Object o) method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.
Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.
What is Java PriorityQueue?
PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation. PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueuing and dequeuing operations.
SOLID Class Design Principles
- Single Responsibility Principles(SRP) : One class should have one and only one reasonability.
ex) If we have to implement customers logic, we can make Customer and Account class. Both have single responsibility to store their specific information. If we want to change state of Person then we do not need to modify the class Account and vice-versa. - Open Closed Principle(OCP) : Software components should be open for extension, but closed modification.
ex) Spring framework has class DispatcherServlet. This class acts as front controller for String based web applications. To use this class, we are not required to modify this class. All we need is to pass initialization parameters and we can extend it’s functionality the way we want. Decorator pattern. - Liskov’s Substitution Principle(LSP) : Derived types must be completely substitutable for their base types.
Interface Segregation Principle(ISP) : Clients should not be forced to implement unnecessary methods which they will not use. - Dependency Inversion Principle(DIP) : Depend on abstraction, not on concretions.
Singleton
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
* The singleton class must provide a global access point to get the instance of the class.
* Singleton pattern is used for logging, drivers objects, caching and thread pool.
* Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
* Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.
Implementation of Singleton Pattern.
* Private constructor to restrict instantiation of the class from other classes.
* Private static variable of the same class that is the only instance of the class.
* Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of a singleton class is created.
Below code snippet provides the double-checked locking implementation.
package net.glenn.singleton; public class ThreadSafeSingleton { private static ThreadSafeSingleton instance; private ThreadSafeSingleton(){} public static ThreadSafeSingleton getInstanceUsingDoubleLocking() { if(instance == null){ synchronized (ThreadSafeSingleton.class) { if(instance == null){ instance = new ThreadSafeSingleton(); } } } return instance; } }
Strategy Pattern
Strategy pattern in quite useful for implementing set of related algorithms e.g. compression algorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes, which uses Strategy implementation classes for applying business rules. This pattern follows open closed design principle and quite useful in Java.
One of a good example of Strategy pattern from JDK itself is a Collections.sort() method and Comparator interface, which is a strategy interface and defines a strategy for comparing objects. Because of this pattern, we don’t need to modify sort() method (closed for modification) to compare any object, at the same time we can implement Comparator interface to define new comparing strategy (open for extension).
Observer Pattern
Observer pattern is based upon notification, there are two kinds of object Subject and Observer. Whenever there is change on subject’s state observer will receive notification.
For example, The ApplicationEvent class and ApplicationListener interface of Spring enables event handling in Spring ApplicationContext. When you deploy a bean that implements the ApplicationListener interface, it will receive an ApplicationEvent every time the ApplicationEvent is published by an event publisher. Here, the event publisher is the subject and the bean that implements ApplicationListener is the observer.
Factory Pattern
Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.
ex) java.util.Calendar, ResourceBundle and NumberFormat :: getInstance(), valueOf() method in wrapper classes like Boolean, Integer etc.
Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes.
ex) java.sql.Connection::createStatement()