You are here
Home > Interview >

Java Interview Questions and Answers

Java Interview Questions and AnswersHere 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 notes in the comment section.

Table of Contents

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.

Java Interview Questions
No Access specifiers 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 a Java Interview. Sometimes, some interviewers target the area that people ignore, but these concepts come under the category of basics.

Let’s check 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.

abstract class Employment {

abstract void applyforJob();

abstract void pepareForInterview();

abstract void getOfferLetter();

abstract void joinCompany();

final void becomeEmployee() {
applyforJob();
pepareForInterview();
getOfferLetter();
joinCompany();
}
}

class JavaEmployment extends Employment {

@Override
void applyforJob() {
System.out.println("I had applied for Java Developer in XYZ company");
}

@Override
void pepareForInterview() {
System.out.println("Then I prepared for the interviews");
}

@Override
void getOfferLetter() {
System.out.println("I got the offer letter from XYZ company for Java developer with handsome salary");
}

@Override
void joinCompany() {
System.out.println("I am going to join the XYZ company in next month");
}
}

public class Test {
public static void main(String[] args) {

Employment employment = new JavaEmployment();
employment.becomeEmployee();
}
}

Output:

I had applied for Java Developer in XYZ company
Then I prepared for the interviews
I got the offer letter from XYZ company for Java developer with handsome salary
I am going to join the XYZ company in next month

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.

overloading vs Overriding
Method Overloading vs Method Overriding

Is the following code valid override ?

class Base {
Number m1() {
return 24;
}
}

class child extends Base{
Short m1() {
return 2;
}
}

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.

Use of 'var' type
var a;               //not allowed
var b =5; // allowed
var c ="Hi"; // allowed
var d = true; // allowed
var e = new int[]{}; // allowed
var f = new String(); // allowed
var g = new Test(); // allowed
var h = null; //not allowed
var var = 10; //allowed second var will be infered as just a variable name
int var = 24; // allowed
void var(){} // allowed
class var {} // not Allowed is a restrited type name and cant be defined as a type
class Var () // allowed as var is case sensitive identifier

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.

Sealed modifier of JDK 15 feature
@SuppressWarnings("preview")
sealed class Parent
permits Child1, Child2 { }

class Child3 extends Parent{} // not allowed

@SuppressWarnings("preview")
non-sealed class Child1 extends Parent{ } // allowed

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

MyCustomAnnotation.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface MyCustomAnnotation {

int studentAge() default 18;
String studentName();
String stuAddress();
String stuStream() default "CSE";
}

 

Now Lets apply this custom annotation in a class ‘MyClass’. Below is the code.

MyClass.java
@MyCustomAnnotation(studentName="Elbert" stuAddress="California")
public class MyClass{

}

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.

interface  Java8 {

void m1(); //abstract by default as it has no body

default void m2() {
//introduced in java 8 with body
}

static void m3() {
//introduced in java 8 with body
}
}

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:

Interfaces vs Abstract class in Java 8
Interfaces vs Abstract class w.r.t Java 8

 

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 need to 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……….

 

 

 

 

 

 

 

 

Leave a Reply


Top