Here in this section we will see Java Interview Questions and answers which will be valuable for any type of interview in Java Programming Language. I am sure that you will find some unique questions that you may rarely see in other sources. Moreover, you will find clear explanations of the answers to each question. When you go through the answers you will find that while answering the questions related new terms are also explained. If you need any other question to be added here, donโt hesitate toย put your comment in the comment section.
Why are the Java primitive data types not objects? Why is Java not a pure Object-Oriented programming Language?
Objects always consume more memory than primitives. If we can solve our purpose without creating more number of objects, the performance will always be better. Java Wrapper Classes were introduced after primitives to make a programmer feel Java as pure Object Oriented Programming language. But still because of the existence of primitives only Java is not a pure Object Oriented Programming Language.
What is the difference between Access Specifier & Access Modifiers in java? Do we have Access Specifiers in java?
Ans: First of all we should know that there is no term called Access Specifiers in java. Other languages like C, C++ etc. may have defined this term, but java doesnโt. Some of the books & websites refer private, public, protected, default as Access Specifier but Java compiler considers them as Access Modifiers. If we declare any class as private or protected we can check the compiler error by mouse hover on it. The compiler will show โIllegal modifier for the class Test; only public, abstract & final are permittedโ as shown below in the snippet. Therefore, all the related keywords like static, abstract, final, synchronized etc. including private, public, protected are Access modifiers in java.

What all access modifiers are allowed in a top level class & in an inner class?
Ans : Most of the times we work with public classes. So there is a high probability that you find this question in the list of Java Interview Questions of the interviewer. Generally they target the area that people ignore, but these concepts come under the category of basic concepts. Letโs see below the list of allowed access modifiers to each one.
Top level classes โ default, public, abstract, final, strictfp Inner classesย ย ย ย โ default, public, abstract, final, strictfp, private, protected, static
What is strictfp modifier? Where is it applied ?
Ans:ย strictfp modifier was introduced in jdk 1.2. The full form of strictfp is the strict floating point. It is applicable for classes, methods, but not for variables. The arithmetic of floating point numbers generally varies from platform to platform ie. Platform dependent. Suppose we have three platforms where we want to test the value ofย an arithmetic 20.0/3 as shown below.
1) for Windows => value may be 6.6666666665
2) for Linux => value may be 6.6666666
3) for MAC => value may be 6.666666667
If we want platform independent results for floating point arithmetic, we should use strictfp modifier by declaring it before method. When a method is declared as strictfp then all floating point calculations in that method will follow IEEE 754 standard and we will get platform independent results. If a class is declared as strictfp, all concrete methods of the class will follow the IEEE 754 standard in the arithmetic calculations.
โฅ strictfp can only be applied with concrete method. Therefore abstract+strictfp combination is illegal for methods. โฅ abstract+strictfp is a legal combination for classes as strictfp is applied only to concrete methods.
How many types of variables are possible in java? What all access modifiers are allowed with variables?
Ans: Variables are placeholders in java. They are of 4 types in Java:
1. Instance Variables (Non-Static Fields)
2. Class Variables (Static Fields)
3. Local Variables
4. Parameters
โฅ Some people donโt consider parameters as a variable, but it comes under the type of variable as per Oracle java documentation. Only static, final, transient & volatile modifiers are applicable to variables.
How many types of Interfaces are there in Java ?
Ans. Typically we have three types of Interfaces till now.
1) Normal Interface
2) Marker Interface
3) Functional Interface
Normal Interface is an interface which has either one or multiple number of abstract methods.
However, Marker Interface is an interface with no abstract method.ย (Because till JDK8 an interface can have only abstract methods, no normal methods). We use it to provide a type to its sub-classes for executing some logic from other classes.
Additionally, Functional Interface is an interface which has only one abstract method. Further, it can have any number of static, default methods and even public methods of java.lang.Object class. In fact, we use it to define Lambda Expressions & Method References by directly providing logic to an argument of a method.
How can you decide the jdk version of a compiled .class file?
Ans: Use below command to get Major & Minor version of the file:
javap -verbose ClassNameWithDirectoryPath | find โversionโ
On executing this command you will get results something like: minor version: 0 major version: 52 Match your Major.minor version(52.0) from below table. Checking major version will also solve our purpose. In this case this file has been compiled using JDK 1.8
ย ย JDKย ย ย Major.minor versions ย ย ย ย ย ย ย ย 1.4ย ย ย ย ย ย 48.0 ย ย ย ย ย ย ย ย 5 (1.5)ย ย ย 49.0 ย ย ย ย ย ย ย ย 6 (1.6)ย ย ย 50.0 ย ย ย ย ย ย ย ย 7 (1.7)ย ย ย 51.0 ย ย ย ย ย ย ย ย 8 (1.8)ย ย ย 52.0 ย ย ย ย ย ย ย ย 9ย ย ย ย ย ย ย 53.0 ย ย ย ย ย ย ย 10ย ย ย ย ย ย ย 54.0 ย ย ย ย ย ย ย 11ย ย ย ย ย ย ย 55.0 ย ย ย ย ย ย ย 12ย ย ย ย ย ย ย 56.0 ย ย ย ย ย ย ย 13ย ย ย ย ย ย ย 57.0 ย ย ย ย ย ย ย 14ย ย ย ย ย ย ย 58.0 15 59.0
What is a local block in java ?
Ans : A nameless block { } that is created inside a method is called a local block. We use it for decreasing the scope of a local variable. We can write any statement inside it what all are applicable to a method. A variable declared inside a local block canโt be accessed after the closing curly bracket of this local block.
What is the role of a class loader in java ?
Class Loaderโs role is to load classes into the JRE in order to make them available for the JVM(Java Virtual Machine). Moreover, Class Loader is a part of the JRE. Java Virtual Machine requests class loader to load the class. Further, class loader tries to find out it in the class path, and if it is not there, it loads the same accordingly. In order to have in-depth knowledge of JVM architecture and Class Loaders, kindly visit our article on JVM architecture and Class Loaders Java.
Is the following main method valid in java ?
public class MainMethodValidity {
synchronized final public strictfp static void main(String... str) {
System.out.println("Am I valid ?");
}
}
Ans: Yes, this is valid main() method in java. Here, place of an Access modifier doesnโt matter. If we want only one thread can access the main method we can use synchronized keyword in it. If we donโt want another class to extend from this class we can declare it as final. In order to know more about strictfp, check the answer of this question. Starting from JDK 1.5 we can declare varargs as โStringโฆ strโ in place of โString[ ] argsโ.
Why can an abstract method not be declared as private ? Can we use private keyword with abstract keyword ?
Ans: An abstract method can reside either in an abstract class or in an interface. The purpose of declaring an abstract method is to force implementing/child classes to provide a concrete implementation of it. If we want implementing/child classes to provide concrete implementation of it, they should have access to that abstract method. If we declare the method as private, no other classes can access it as private access modifier is limited to the same class. In this case abstract method will never be implemented. So if we use abstract we want to implement it in one side where in other side using private keyword restricts us to access it. Hence, we canโt use abstract & private together.
Can an Abstract class contain final method ? What is the benefit of having a final method in an abstract class?
Ans: Yes. An abstract class can contain final methods. It is a valid combination, the compiler will not complain. When we donโt need the child class to override a method of itโs parent class, we declare the method as final. In general, we observe this scenario in the Template Method pattern of Java Design patterns. Template method design pattern is to define an algorithm as the skeleton of operations and leave the details to be implemented by the child classes. Parent abstract class contains complete implementation a method and used in the algorithm. This method in base class should be restricted so that the subclasses does not override it. So it is declared as final.
In Template Method pattern, Parent class is known as Template class & a final method as Template method. Letโs make it clear with an example. Suppose we have to implement an algorithm to become an Employee of a company. In this process, there are many small steps to be followed like applying for the job, preparing for the interview, getting an offer letter, joining the company, then someone becomes the employee of the company.
Output:
Can a Final class contain abstract method ?ย
Ans: No. A final class canโt contain an abstract method because a final class canโt be subclassed and without subclassing we canโt implement the abstract method. Therefore it is totally useless to keep an abstract method inside any final class. Moreover, if we declare a method as abstract in any class, compiler will suggest to make the class abstract to remove compile time errors. If the class is abstract this canโt be declared final as abstract-final combination is illegal in java which is explained in the next question.
Can we use final & abstract both access modifiers in a method? Can we declare a method as abstract & final both.
Ans: No. Itโs illegal contract in java. Abstract will force method to get overridden by child classes whereas final will not allow method to be overridden by child classes. So both are contradictory situation which will not solve the purpose of the method at all. Therefore we canโt declare a method as abstract & final both. These questions on combination of multiple access modifiers are very important. They can be part of Java Interview Questions.
Is below line a valid class declarationย ?ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย
class C implements A extends B {.........}
Ans: No. Its not a valid declaration. The valid declaration is :
class C extends B implements A {......}ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย
extends keyword always comes before implements keyword. When we use extends it means we can have methods which are inherited by sub class by default while in case of implements it tells us to override methods forcefully. So we always write first which we already have, then others.
What is the difference between final, finally & finalize() keyword in java ?
Ans: Below is the explanation of all three keywords with complete clarity.ย Keep your special attention on finally & finalize.
Final : Final is a keyword that we use with variable, methods & classes. final variable means itโs value is constant and we canโt reassign a value for that variable. A final method canโt be overridden by a child class. Hence, we canโt create a sub class of a final class.
Finally : It is used in context of exception handling with try-catch block to release the resources that we opened in the try block.
Finalize : It is a method defined in Object class. Garbage collector calls this method to perform clean up activities before destroying the object from the memory.
*โฅย Finally meant for cleanup activities related to try block whereas finalize() meant for cleanup activities related to object.
What is the difference between fully checked & partially checked Exceptions?
Ans: A checked Exception is said to be fully checked if and only if all its sub classes are also checked exceptions. eg : IOException, InteruptedException.ย A checked Exception is said to be partially checked if and only if some of its sub classes are unchecked exceptions. eg : Exception, Throwable. The only possible partially checked Exceptions in java are Exception & Throwable. All other exceptions are either fully checked exceptions or unchecked exceptions.
What are the different useful commands to manage jar files?
We have different commands to create jar file based on some parameters.
1) jarย -cvfย test.jar Test.classย โ To create jar file of only one class
2) jarย -cvfย test.jar Test1.class Test2.class Test3.classย โย To create jar file of multiple classes
3) jarย -cvfย test.jar *.classย โย To create jar file of all the classes in current path
4) jarย -cvfย test.jar *.*ย โย To create jar file of all type of files in current path
5) jarย -xvfย test.jarย โย To extract(unzip) a jar file
6) jarย -tvfย ย test.jar โย To display name of all the files inside the jar
What is difference between creating object of a class using new() & newInstance() ?
Ans: When we already know the name of the class whom object to be created we use new operator. When we donโt already know the class name & it is to be decided dynamically at runtime we use newInstance(). Furthermore, we can pass the arguments with the class name using new but in case of newInstance() only no-arg constructor will be called. Syntax for creating objects are as below:
TestClass tc= new TestClass(); TestClass tc= new TestClass("test"); Class c=Class.forName("com.dev.SampleClass"); SampleClass s=(SampleClass)c.newInstance();
What is the difference between ClassNotFoundException & NoClassDefFoundError?
Ans: ClassNotFoundException is a checked Exception. We face this when we try to load class at runtime using Class.forName or the class is not found in the class path. Most of the time, this exception occurs when you try to run an application without updating the class path with required JAR files.
NoClassDefFoundError is an unchecked exception. We face this when we create a hard coded class by using new operator. It occurs when required class definition is missing at runtime while it was available at compile time. For example, if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then Java Virtual Machine will throw NoClassDefFoundError.
What is covariant return type in java?
Ans: The concept of covariant return type was introduced in jdk 1.5. Before jdk 1.5 in method overriding the overriding method must have the same return type as itโs parent class method has. In this case, overriding method was said to be invariant with respect to return type. But jdk 1.5 onward, the overriding methodโs return type can be the sub-type of itโs parent class methodโs return type. This is called covariant return type. Theย covariant return type always works only for non-primitive return types. In order to understand with an example, click here.
What is difference between Method hiding & Method Overriding? What is the purpose of overriding a method?
Ans: Re-defining parent class non-static method in child class is called method overriding. Re-defining parent class static method in child class is called method hiding. This is because we canโt override parentโs class static methods. If parentโs class method doesnโt solve our purpose, we redefine it in child class. We do it using overriding or hiding technique. For example, below code snippet shows the clear difference.
class P {
static void m1();
void m2();
void m3();
}
class C extends P{
static void m1(); // method hiding
void m2(); // method overriding
void m4();
}
What is Method Overloading & Method Overriding in java ?
Ans: This question might appear to be a bit easy question to answer but sometimes some people get confused between them. Even they do not remember the rules on when to use which one.
Method Overloading :
Method overloading provides two separate methods in a class with the same name but different arguments, while the method return type may or may not be different, which allows us to reuse the same method name with different arguments. There are some rules to follow while overloading a method. Some of them are mandatory while some are optional as below.
Mandatory Rules: Two methods will be treated as overloaded if both follow the mandatory rules below:
1. Both must have the same method name.
2. Both must have different argument lists. If they have same types of arguments but their order of occurrence is different, they will be treated as different arguments.
Optional Rules: If both methods follow the above mandatory rules, then they may or may not:
1. Have different access modifiers.
2. Have different return types.
3. Throw different checked or unchecked exceptions.
In general, method overloading happens in the same class. However, a method can also be treated as overloaded in the subclass of that class. This happens because the subclass inherits one version of the method from the parent class and then it can have another overloaded version in itโs definition.
Method Overriding:ย
Whenever we extend a child class, the child class automatically gets all the methods defined in the super class. We call them derived methods. But in some cases, we do not want some derived methods to work in the same manner as they do in the parent class. Then we override them in the child class.
Mandatory Rules: The overriding method must follow the following rules:
1) It must have the same method name.
2) It must have the same arguments.
3) It must have the same return type. From Java 5 onward, if overriding methodโs return type is subclass of overridden methodโs return type, it is valid. This type of relationship is called covariant return types. Both types must be an Object to be a valid override.
4) It must not have a more restrictive access modifier. if parent is public then child as private is not allowed. Access modifiers visibility sequence is : private < default < protected < public which means private is the most restrictive & public is the least restrictive modifier.
5) It must not throw newer or broader checked exceptions.
6) It must be in the child class. Methods can be overridden only in child classes not in the same class.
Optional Rules: If both methods follow the above mandatory rules, then they :
1. May have a less restrictive access modifier. if parent is protected then child as public is allowed.
2. May throw narrower(below in class hierarchy) checked exceptions or any unchecked exception.
What is difference between Method Overloading & Method Overriding ?
Ans: Please go through the below table to see clear difference between both. This question has high probability in the list of Java Interview Questions in the interview room.

Is the following code valid override ?
Ans: This code is valid starting from jdk 1.5 on the basis of new feature covariant return types. Till jdk 1.4 the code was invalid as child class methodโs return type doesnโt match with base class methodโs return type.
โฅ Note : Below is the command to check the code in different versions of java. If you have higher version of java, then also you can test the code in lower versions using below command from command prompt. Here I have used jdk 1.4 version as an example.
javac -source 1.4 Test.java
Have you ever faced โjava.lang.UnsupportedClassVersionErrorโ while running your java application?
Ans: This runtime error comes when you compiled your java file in higher version of JDK & tried to run this file in lower version of JDK. In contrast, Lower version compiler generated .class files can be run by higher version JVM. But higher version compiler generated .class files canโt be run by lower version JVMs. If we try to run, we will get runtime exception saying โjava.lang.UnsupportedClassVersionErrorโ. Major & minor versions represent .class file version. Java Virtual Machine will use these versions to identify which version of compiler generated the current .class file.
M.m => 'M' stands for major version, 'm' stands for minor version. Below is the versions to identify respective jdk.
1) java 1.5ย ->ย 49.0
2) java 1.6ย ->ย 50.0
3) java 1.7ย ->ย 51.0 and so onโฆ
You will find these version numbers in stack-trace of your error to take further action. For complete list of all versions visit here.
What is Magic Value in Java?
Ans : This is a predefined value used by Java Virtual Machine to identify that .class file is generated by valid compiler or not. The first 4 bytes of the class file is magic number. This value should be โ0xCAFEBABโ. Whenever we execute a java class, if Java Virtual Machine is unable to find valid magic number then we will get runtime exception saying [Exception in thread โmainโ java.lang.ClassFormatError : Incompatible Magic Value].
What is โvarโ identifier introduced in Java 10 ?
Ans : โvarโ is a case sensitive type identifier that helps java compiler to infer the values, introduced in Java 10 version. However, it is not a keyword. We can only use them in case of local variables. Moreover, we can use var anywhere in java except in class name. For example, below is the list of some valid and invalid var declarations.
How many ways are there to store string data inside a java program ?
Ans : There are four ways to store a string data in java program:
โ char[]ย :ย Using Character Array
โฆ Stringย :ย Using String class
โฆ StringBufferย : Using StringBuffer
โ class StringBuilder : Using StringBuilder class
What is โstreamโ in Java ? What was the purpose of introducing it ? How does it differ from a collection?
Ans: java.util.stream is a package introduced in jdk 1.8. It has several interfaces & classes to work on streams(flow of data). Classes under stream package introduced to support functional-style operations on the stream of elements. However, please note that Stream is not a collection rather it is a technique to make processing of collectionโs data easy by supporting functional-style operations. Furthermore, Streams differs from a collection in several ways.
โ A stream is not a data structure that stores elements.
โฆ An operation on a stream produces a result, but does not modify its source.
โฅ While collections have a finite size, streams need not.
โฃ The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.
What is a referenced variable in Java ? How many types of reference variables are possible?
Ans: When we create a variable by using Objects (as a Datatype), we call them referenced variables. However, we create them by using Array, Class, Interface or Enum. Moreover, referenced variables store reference of the object while primitive variables store the values directly. Types of possible referenced variables are : Local Static Non-Static Final Volatile Transient
How can we restrict a class or interface to be subclassed without using final keyword?ย
Ans : We can use sealed modifier(a preview feature of JDK 15) in the declaration of class or interface. In the below code snippet Class Child3 is not allowed to extend from class Parent. Only Child1 & Child2 can extend from Parent as they are part of โpermitsโ of the super class Parent. For example, observe the below code. In order to get more detail on the sealed feature of JDK 15, kindly visit the JDK 15 Features page.
Is below statement syntactically correct?
// A final resource
final Resource resource1 = new Resource("resource1");
// An effectively final resource
Resource resource2 = new Resource("resource2");
try (resource1; resource2) {
...
}
Ans : From this question the interviewer wants to check your knowledge on JDK enhancementsย in deferent versions. Now the answer of this question is โ Syntax is correct if we are using JDK 9 + version whereas it is incorrect if we are using JDK 8 and below versions. If you already have a resource as a final or effectively final variable, you can use that variable in a try-with-resources statement without declaring a new variable. An โeffectively finalโ variable is one whose value never changed after it is initialized. ย ย
What is a Java Bean?
Ans : Java Bean is a simple java helper class, used to transfer data between classes or applications. It never acts as a main class, but like postman or a delivery boy between two classes. It doesnโt contain any logic. In order to pass more than 3 values from one class to another or from one project to another, we should take support of Java beans. If less than 3 values, we should use method arguments to transfer the data. However a good design in java doesnโt recommend us to have more than 3 method parameters. You can check java library(java doc), you will not find more than 3 parameters in a methods, very rarely it may have 4 but not more than that.
There are some standard guidelines to develop a Java Bean class :
1. We must declare Java Bean as a public class.
2. It is a recommendation to implement java.io.Serializable (used to sent data across network as we can easily send serializable data over the network). It is optional if you donโt want to send data over network.
3. All member variables(bean properties) should be private & non-static (if we want to send data of 20 employees, 20 values will be sent. if its static only one value will be sent, so declaring non-static becomes mandatory to get full benefit of Java Bean)
4. Also Every bean property should have one setter and one getter method (Accessor Methods).
How to create custom annotations in Java?
Ans: We need to create an interface with โ@โ as shown in the following code snap
ย
Now Lets apply this custom annotation in a class โMyClassโ. Below is the code.
Further to learn complete annotations and how to create custom annotations, kindly visit Annotations In Java tutorial.
What is an Interface in Java 8?
Ans: Interfaces form an agreement between the class and the outside world, and this agreement is enforced at build time by the compiler. In object-oriented programming, it is sometimes helpful to define what a class must do but not how it will do it. Then we use Interfaces. It specifies what must be done, but not how. Once an interface defined, any number of classes can implement it. Also, one class can implement any number of interfaces.
From Java 8 onward, An interface can have abstract or default or static methods or any combination of two of them or all of them. To implement an interface, a class must provide implementations for the abstract methods described by the interface. Each class is free to determine the details of its own implementation. Thus, two classes might implement the same interface in different ways, but each class still supports the same set of methods. For example, observe the below code.
As shown in the code snippet & unlike to interfaces till java 7, from Java 8 onward apart from abstract methods now an interface can have default & static methods with method bodies.
What is difference between Abstract class & Interface in Java 8?
Ans: After learning Interfaces in context of Java 8, one doubt may arise in your mind that what is difference between interface & abstract classes after introduction of default & static methods. Letโs clear the doubt from the table below:

ย
How many ways are there to implement Functional Interface in java?
Ans : There are five ways to implement Functional Interface in Java.
1. By Explicit Outer class
2. By Explicit Inner class
3. By Anonymous Inner class
4. By Lambda expression
5. By Method Reference
How to convert Map to List of Objects or POJO ?
Ans : This question is not only important in your day by day programming but also in Java Interview Questions point of view. We will solve this problem using two ways. Letโs first write a POJO class to create objects as below. For example, letโs assume we have an Employee class as below.
public class Employee {
private Integer empId;
private String empName;
private String empDept;
public Employee( Integer empId, String empName, String empDept) {
ย ย ย ย super();ย ย
this.empId=empId;
this.empName= empName;
this.empDept=empDept;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", empDept=" + empDept + "]";
}
}
Method #1 : Using ArrayList() Constructor
We will use mapโs keySet() method to get all the keys and create an ArrayList to get keyList from them. Likewise, we will use the mapโs values() method to get all the values and create an ArrayList to get valueList from them.
import java.util.*;
public class MapToList{
public static void main(String[] args){
Map<Integer, Employee> map = new HashMap<>();
map.put(101, new Employee(101,"Robert","IT");
map.put(102, new Employee(102,"Mary","HR");
map.put(103, new Employee(103,"Johnson","Admin");
map.put(104, new Employee(104,"William","QA");
map.put(105, new Employee(105,"Smith","IT");
List<Integer> keyList = new ArrayList<Integer>(map.keySet());
List<Employee> valueList = new ArrayList<Employee>(map.values());
System.out.println("Key List : " + keyList);
System.out.println("Value List : " + valueList);
}
}
Method #2 : Using Stream of JDK 8
In the below program, instead of using ArrayList constructor, weโve used stream() to convert the map to a list. Further, Weโve converted the keys and values to stream. Finally, converted it to a list using collect() method by passing Collectorsโ toList() as a parameter.
import java.util.*;
import java.util.stream.Collectors;
public class MapToListUsingStream {
public static void main(String[] args) {
Map<Integer, Employee> map = new HashMap<>();
map.put(101, new Employee(101,"Robert","IT"));
map.put(102, new Employee(102,"Mary","HR"));
map.put(103, new Employee(103,"Johnson","Admin"));
map.put(104, new Employee(104,"William","QA"));
map.put(105, new Employee(105,"Smith","IT"));
List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());
List<Employee> valueList = map.values().stream().collect(Collectors.toList());
System.out.println("Key List : " + keyList);
System.out.println("Value List : " + valueList);
}
}
The output of both the programs will be the same.
How to convert List<Object[ ]> to Map<Integer, String> ?
For Example, below code demonstrates the two ways of doing it.
public class Test { public static void main(String[] args) { // Using JDK 9 way to create a List List<Object[]> list = List.of( new Object[] {10,"AAA"}, new Object[] {11,"BBB"}, new Object[] {12,"CCC"}, new Object[] {13,"DDD"}, new Object[] {14,"EEE"} ); // Using Java 8 Streams Map<Integer,String> map = list .stream() .collect(Collectors.toMap( ob->Integer.valueOf(ob[0].toString()), ob->ob[1].toString())); // Using for Each Map<Integer,String> map2 = new HashMap<>(); for(Object[] ob: list) { map2.put( Integer.valueOf(ob[0].toString()), ob[1].toString()
); } } }
What are the three usages of static keyword?
This question may be a part of โJava Interview Questionsโ to check in-depth knowledge of the static keyword. However, most of the people immediately tell the purpose of static keyword something like โto restrict a class to share the same values of member variables among all instancesโ. Everyone knows the three usage but sometimes it slips from the mind. Below are the three usages.
1) When you want to store data thatโs common to all instances.
2) When you need to access class members without creating an object of the class.
3) When you want to execute a block of code before calling any method of the class ie. Static block.
What do you think โIs Optional the Same as null?โ
Optional is a new class under package java.util. The purpose of this call is to address the infamous NullPointerException.ย Before Java 8, programmers would return null instead of Optional. There were a few drawbacks with this approach. One was that there wasnโt a clear way to express that null might be a special value. By contrast, returning an Optional is a clear statement in the API that there might not be a value in there.
Another advantage of Optional is that you can use a functional programming style with ifPresent() and the other methods rather than needing an if statement.ย
Why do we have a Marker/Tag/Empty Interface in Java?
A marker interface in java doesnโt have fields and methods. In other words, we can also say it as an interface without any body, because fields & methods make a body of the interface. Hence it is also called empty interface. Sometimes people in the industry, even call it Tag interface. For example: java.lang.Cloneable, java.lang.Serializable are the examples of marker interface.
As the name suggests, Marker interface is used to mark a class as having certain property. Suppose that we have a to clone an object, the first process is to mark the class as Cloneable. Programmatically, we can do it by implementing a Cloneable interface, which is a marker interface. Here, making clone of an object is the certain property. Similarly, if we want to make a class Serializable, we first mark it as Serializable by implementing the Serializable interface.
Updates are coming regularlyโฆโฆโฆ.
ย