Java 11 Interview Questions and Answers

Java 11 Interview Questions and Answers

  1. Why Java 11 so crucial?
  2. What is difference between Oracle JDK and OpenJDK?
  3. Which commercial features are available as open source in Java 11?
  4. What is Flight Recorder in Java 11?
  5. What is Java Mission Control in Java 11?
  6. How can I download the free version of Java 11?
  7. What are Java 11 Features?

Q: Why Java 11 so crucial ?
Ans:

Java 11 is the second release of the long-term support (LTS) after Java 8. Since Java 11, Oracle JDK is no longer free for commercial use. You can use it in the development stages, but you need to buy a license to use it commercially. After Java 11, Oracle will not provide free long-term (LTS) support for any single Java version.

Q: What is difference between Oracle JDK and OpenJDK?
Ans:

Ever since Java 7, Java has been developed out in the open in the OpenJDK project. It’s open source, but it’s mainly driven by committers from Oracle, the owners of Java. But there are also many outside contributions from the likes of Red Hat, Twitter, and IBM. When you want to run Java, you have a choice to either use the OpenJDK releases, or to use the Oracle JDK release. The Oracle JDK release used to be a slightly extended and amended version of OpenJDK. The ultimate goal here is to have no differences between the Oracle JDK builds and the OpenJDK builds.

The main difference between Oracle JDK and OpenJDK is that Oracle JDK incorporates some commercial features. Rather than stripping these features to get conversions between Oracle JDK and OpenJDK, Oracle has committed to open source these commercial features into OpenJDK. This process already started with Java 9 and 10 and is continued with Java 11.

With Java 11, the goal of a convergence between the Oracle JDK and OpenJDK code bases have been achieved. there’s some pretty big differences in licensing. OpenJDK is GPL 2 licensed, so it has a true open source license. Oracle JDK, on the other hand, has a proprietary license called the Oracle Binary Code License Agreement. Up until Java 10, you could use both OpenJDK and Oracle JDK in production free of charge. For Oracle JDK, you could buy optional support from Oracle. That’s changing with Java 11. For OpenJDK there are no changes, you can still use the GPL 2 license builds. However, you can no longer use Oracle JDK free of charge in production.

Q: Which commercial features are available as open source in Java 11?
Ans:

One of the Oracle JDK commercial features that has been open sourced is Java Flight Recorder. In addition to Java Flight Recorder, Java Mission Control has also been open sourced.

Q: What is Flight Recorder in Java 11?
Ans:

Java Flight Recorder is an always-on, low-overhead, data collection framework that you can use to get metrics on your JVMs. It’s implemented as a bounded circular buffer, which buffers internal JVM metrics for a configurable amount of minutes. The great thing about this feature is that you can leave it enabled on your prediction systems because it’s so low overhead.
about:blank

Q: What is Java Mission Control in Java 11?
Ans:

Java Mission Control is an application that can analyze the dumps that come from Java Flight Recorder, and give you a graphical overview of what’s happening inside of a JVM.

Q: How can I download the free version of Java 11?
Ans:

You can download from Java 11. Download tar/zip, unzip them, install and set the environment variables to use java 11.

Q: What are Java 11 Features?
Ans:

Below is a list of the main features included in Java 11 :

  • 181: Nest-Based Access Control
  • 309: Dynamic Class-File Constants
  • 315: Improve Aarch64 Intrinsics
  • 318: Epsilon: A No-Op Garbage Collector
  • 320: Remove the Java EE and CORBA Modules
  • 321: HTTP Client (Standard)
  • 323: Local-Variable Syntax for Lambda Parameters
  • 324: Key Agreement with Curve25519 and Curve448
  • 327: Unicode 10
  • 328: Flight Recorder
  • 329: ChaCha20 and Poly1305 Cryptographic Algorithms
  • 330: Launch Single-File Source-Code Programs
  • 331: Low-Overhead Heap Profiling
  • 332: Transport Layer Security (TLS) 1.3
  • 333: ZGC: A Scalable Low-Latency Garbage Collector(Experimental)
  • 335: Deprecate the Nashorn JavaScript Engine
  • 336: Deprecate the Pack200 Tools and API

Java 8 Interview Questions and Answers

Q: What’s new features added in Java 8?
Ans:

  • Lambda Expressions
  • Functional Interfaces
  • Stream API
  • Date and Time API
  • Interface Default Methods and Static Methods
  • Spliterator
  • Method and Constructor References
  • Collections API Enhancements
  • Concurrency Utils Enhancements
  • Fork/Join Framework Enhancements
  • Internal Iteration
  • Parallel Array and Parallel Collection Operations
  • Optional
  • Type Annotations and Repeatable Annotations
  • javac Enhancements
  • JVM Changes
  • Java 8 Compact Profiles: compact1,compact2,compact3
  • JDBC 4.2
  • JAXP 1.6
  • Java DB 10.10
  • Networking
  • Security Changes
  • Method Parameter Reflection
  • Base64 Encoding and Decoding
  • IO and NIO2 Enhancements
  • Nashorn JavaScript Engine

Q: What is Method Reference in Java 8?
Ans:

A Method Reference is used to reference a method without invoking, it is used as Lambda Expressions for treating methods.
A reference method can be defined by a double colon separating the name of a class or object and the method name. It has various variations, such as the reference constructor
EXAMPLE

(o) -> o.toString(); // without Method Reference
Object::toString();  //with Method Reference

Q: What is Lambda Expression?
Ans:

Lambda expression is an important feature introduced in Java SE 8. Lambda Expression is an anonymous function that accepts a set of input parameters and returns results.
The Lambda expression provides the implementation of an interface which has functional interface, which reduce lots of code.
EXAMPLE
Without Lambda Expression

interface Paint{
    public void color();
}
public class Example {
    public static void main(String[] args) {
        String color="red";

        //without lambda, Paint implementation using anonymous class  
        Paint p=new Paint(){
            public void color(){System.out.println("coloring "+red);}
        };
        p.color();
    }
}

With Lambda Expression

@FunctionalInterface
interface Paint{
    public void color();
}

public class Example {
    public static void main(String[] args) {
        String color="red";

        //with lambda expression 
        Paint p=()->{
            System.out.println("Coloring "+color);
        };
        p.color();
    }
}  

Q: What is Java Lambda Expression Syntax?
Ans:

(parameter-list) -> {Lambda Expression Body}  

It has 3 parts:

  1. Parameter List – It’s optional, can have zero or more parameters.
  2. Lambda Arrow Operator – “->” it’s called Arrow Token, used to link parameter-list and body.
  3. Lambda Expression Body – It contains expressions and statements.

EXAMPLE

//It's "java.lang.Runnable" Functional Interface, as it doesn't have any parameter and return result.
() -> System.out.println("Hello");

Q: Can it be possible to define our own Functional Interface?
Ans:

Yes, we can define our own Functional Interface by using @FunctionalInterface annotation.

Q: What is Functional Interface? Why there is a need to have Functional Interface?
Ans:

Functional Interface is an interface with one and only one abstract method. If we define an Interface as Functional Interface with @FunctionalInterface annotation, it becomes mandatory to have one and only one abstract method. It’s not necessary to have Functional Interface, however if we are using Lambda expression , it means we are using Functional Interface.

Q: What are the rules of Functional Interface?
Ans:

Below are the rules to define Functional Interface.

  • Only one abstract method is allowed to define in Functional Interface.
  • Use @FunctionalInterface annotation to declare Functional Interface.
  • The functional interface defines an abstract method that overrides one of the public methods from java.lang.Object already considered to be a functional interface. The purpose is that every implementation class on this interface can be implemented for this abstract method either from a superclass or specified by the implementation class itself..
  • Can have any number of methods default methods

Q: What are Functional Interfaces present in the Standard Library?
Ans:

The java.util.function package contains a lot of functional interfaces, the more common are but not limited to.

  1. FunctionIt takes one parameter and returns a result
  2. ConsumerIt takes one parameter and returns no result
  3. PredicateIt takes one parameter and returns a boolean
  4. SupplierIt takes no parameter and returns a result
  5. BiFunctionIt takes two parameters and returns a result
  6. BinaryOperatorSame as BiFunction, it takes two parameters and returns result. The two parameters and the result are all of the same types
  7. UnaryOperatorSame as Function, it takes single parameter and returns result of the same type

Q: What is Optional and how to use?
Ans:

Java 8 has launched a new Optional class in java.util package, used to indicate a value that is present or absent.
Advantages of using Optional:

  1. Null checks not required.
  2. It avoids NullPointerException at run-time.
  3. Can develop clean code without boiler plate code.

Optional.ofNullable() – if value is present in the given object, it returns a non-empty Optional else returns empty Optional.
Optional.empty() method is useful to create an empty Optional object.
EXAMPLE

Optional<String> color = Optional.of("BLUE");
System.out.println("non empty Optional object: " + color);
System.out.println("non empty Optional object value: " + color.get());
color.ifPresent(c -> System.out.println("Color is available."));

--------------------------------------------------------
Output
--------------------------------------------------------
non empty Optional object: Optional[BLUE]
non empty Optional object value: BLUE
Color is available.

Q: What is Default Method?
Ans:

Java 8 introduces the Default Method are also known as Defender Methods or Virtual Extension Methods feature that allows developers to add new methods to the interfaces without breaking their existing implementation.

interface DefaultInterfaceExample
{
    // abstract method 
    public void add(int a);

    // default method 
    default void display()
    {
      System.out.println("Default Method");
    }
}

class CalculationClass implements DefaultInterfaceExample
{
    // implementation of add abstract method 
    public void add(int a)
    {
        System.out.println(a+a);
    }

    public static void main(String args[])
    {
        CalculationClass c = new CalculationClass();
        c.add(6);

        // call default method 
        c.display();
    }
}


-------------------------------------------------------
OUTPUT
-------------------------------------------------------
12
Default Method

Q: Can Interface have Static Methods same as static method of classes?
Ans:

Yes, interface can have Static Methods same as static method of classes.
EXAMPLE

interface StaticInterfaceExample
{
    // abstract method 
    public void add(int a);

    // static method 
    static void display()
    {
      System.out.println("Static Method");
    }
}

class CalculationClass implements StaticInterfaceExample
{
    // implementation of add abstract method 
    public void add(int a)
    {
        System.out.println(a+a);
    }

    public static void main(String args[])
    {
        CalculationClass c = new CalculationClass();
        c.add(6);

        // call static method 
        d.display();
    }
}


-------------------------------------------------------
OUTPUT
-------------------------------------------------------
12
Static Method

Java 8 Programming Interview Questions and Answers

I have covered Java 8 programming questions that were asked during the interview.

  1. What are different ways of iterating collection list in Java 8?
  2. How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?
  3. How to sort Collection in Java 8?
  4. How to use map to convert object into Uppercase in Java 8?
  5. How to convert a List of objects to a Map in Java 8 by handling duplicate keys?
  6. How to convert a List of objects to a Map by considering duplicated keys and store them in sorted order?
  7. What is the best way to convert a primitive Array to a List in Java 8?
  8. How to sort arrays of primitive types in descending order in Java 8?
  9. How to concatenate List of String/Integer Objects using some separator in Java8?
  10. How to count each element/word from the String ArrayList in Java8?
  11. How to find only duplicate elements with its count from the String ArrayList in Java8?

What are different ways of iterating collection list in Java 8?
Ans:

public void iterateList() {
    List<String> notes = new ArrayList<>();
    notes.add("note1");
    notes.add("note2");
    notes.add("note3");
    notes.add("note4");
    notes.add("note5");
    
    //Using lambda expression
    //Output : note1,note2,note3,note4,note5
    notes.forEach(note->System.out.println(note));
    
    //Output : note3
    notes.forEach(note -> {
        if ("note3".equals(note)) {
            System.out.println(note);
        }
    });
    
    //Using Stream and filter
    //Output : note2
    notes.stream()
        .filter(s -> s.contains("note2"))
        .forEach(System.out::println);
    
    //Using method reference
    //Output : note1,note2,note3,note4,note5
    notes.forEach(System.out::println);
}

Q: How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?
Ans:

public void checkListEmpty() {
    List<Notes> noteLst = new ArrayList<>();
    noteLst.add(null);
    noteLst.add(new Notes(3, "cc", 33));
    noteLst.add(new Notes(4, "bb", 44));
    noteLst.add(null);
    noteLst.add(new Notes(5, "zz", 32));
    
    System.out.println("Note List Size:" + noteLst.size());
    
    Optional.ofNullable(noteLst)
    .orElseGet(Collections::emptyList) // creates empty immutable list: [] in case noteLst is null
    .stream().filter(Objects::nonNull) //loop throgh each object and consider non null objects
    .map(Notes::getTagName) // method reference, consider only tag name
    .forEach(System.out::println); // it will print tag names
}

Q: How to sort Collection in Java 8?
Ans:

Prior to Java 8:
//Older way to sort, before java 8
noteLst.sort(new Comparator<Notes>() {
    @Override
    public int compare(Notes n1, Notes n2) {
        return n1.getId()-n2.getId();
    }
});
In Java 8:
public void doSorting() {
    List<Notes> noteLst = new ArrayList<>();
    noteLst.add(new Notes(1, "aa", 11));
    noteLst.add(new Notes(3, "cc", 33));
    noteLst.add(new Notes(4, "bb", 44));
    noteLst.add(new Notes(2, "dd", 34));
    noteLst.add(new Notes(5, "zz", 32));

    // java 8 sort according to id 1,2,3,4,5
    noteLst.sort((n1, n2)->n1.getId()-n2.getId());
    
    //java 8 print the notes using lamda
      noteLst.forEach((note)->System.out.println(note));
}
//Output 

Notes [id=1, tagName=aa, tagId=11]
Notes [id=2, tagName=dd, tagId=34]
Notes [id=3, tagName=cc, tagId=33]
Notes [id=4, tagName=bb, tagId=44]
Notes [id=5, tagName=zz, tagId=32]

Q: How to use map to convert object into Uppercase in Java 8?
Ans:

//Older way to convert object to uppercase
List<String> names = Arrays.asList("aa", "bb", "cc", "dd");

List<String> uppercaseNames = new ArrayList<>();
for (String name : names) {
    uppercaseNames.add(name.toUpperCase());
}
public void useMapToConvertUppercase() {
    List<String> names = Arrays.asList("aa", "bb", "cc", "dd");
    // In Java 8
    List<String> nameLst = names.stream().map(String::toUpperCase).collect(Collectors.toList());
    System.out.println(nameLst); //output- [AA, BB, CC, DD]
}

Q: How to convert a list of objects to a Map in Java 8 by handling duplicate keys?
Ans:

public class Notes {

    private int id;
    private String tagName;
    private long tagId;

    public Notes(int id, String tagName, long tagId) {
        this.id = id;
        this.tagName = tagName;
        this.tagId = tagId;
    }

    // getters and setters
    public int getId() {
    	return this.id;
    }
    public void setId(int id) {
    	this.id = id;
    }
    
    public String getTagName() {
    	return this.tagName;
    }
    public void setTagName(String tagName) {
    	this.tagName = tagName;
    }
    
    public long getTagId() {
    	return this.tagId;
    }
    public void setTagId(long tagId) {
    	this.tagId = tagId;
    }
    
    @Override
    public String toString() {    	
    	return this.id + "::" + this.tagId +"::" + this.tagName;
    }
}
public class TestNotes {

    public static void main(String[] args) {

        List<Notes> noteLst = new ArrayList<>();
        noteLst.add(new Notes(1, "note1", 11));
        noteLst.add(new Notes(2, "note2", 22));
        noteLst.add(new Notes(3, "note3", 33));
        noteLst.add(new Notes(4, "note4", 44));
        noteLst.add(new Notes(5, "note5", 55));

        noteLst.add(new Notes(6, "note4", 66));

//use third mergeFunction argument (oldValue, newValue) -> oldValue solved the duplicated key issue by considering old value
        Map<String, Long> notesRecords = noteLst.stream().collect(
                Collectors.toMap(Notes::getTagName, Notes::getTagId,
                        (oldValue, newValue) -> oldValue
                )
        );

        System.out.println("Notes : " + notesRecords);
    }
}
//Output - for (oldValue, newValue) -> oldValue, it took old value note4=44
Notes : {note1=11, note2=22, note3=33, note4=44, note5=55}
//Output - for (oldValue, newValue) -> newValue, it took new value note4=66
Notes : {note1=11, note2=22, note3=33, note4=66, note5=55}

Q: How to convert a List of objects into a Map by considering duplicated keys and store them in sorted order?
Ans:

Consider above Example with Notes object and TestNotes Main class.

public class TestNotes {

    public static void main(String[] args) {

        List<Notes> noteLst = new ArrayList<>();
        noteLst.add(new Notes(1, "note1", 11));
        noteLst.add(new Notes(2, "note2", 22));
        noteLst.add(new Notes(3, "note3", 33));
        noteLst.add(new Notes(4, "note4", 44));
        noteLst.add(new Notes(5, "note5", 55));

        noteLst.add(new Notes(6, "note4", 66));


        Map<String, Long> notesRecords = noteLst.stream()
		 .sorted(Comparator.comparingLong(Notes::getTagId).reversed()) // sorting is based on TagId 55,44,33,22,11
		.collect(
                Collectors.toMap(Notes::getTagName, Notes::getTagId,
                        (oldValue, newValue) -> oldValue, // consider old value 44 for dupilcate key
						LinkedHashMap::new           // it keeps order           
                )
        );

        System.out.println("Notes : " + notesRecords);
    }
}
//Output - for (oldValue, newValue) -> oldValue, it took old value note4=44
Notes : {note5=55, note4=44, note3=33, note2=22, note1=11}

Q: What is the best way to convert a primitive Array to a List in Java 8?
Ans:

Prior to Java 8:
int[] nums = {1, 2, 3, 4, 5, 6, 7};

List<Integer> numLst = new ArrayList<>();
for (int n : nums)
{
 numLst.add(n);
}
In Java 8:

In Java 8, we could do the conversion of the Stream using boxing.

//using Arrays.stream() sequential stream with boxed
List<Integer> numsLst = Arrays.stream(nums).boxed().collect(Collectors.toList());

//OR
//By using IntStream.boxed(), convert each element of the stream to an Integer ().
List<Integer> numsLst = IntStream.of(nums).boxed().collect(Collectors.toList());

Q: How to sort int arrays of primitive types in descending order in Java 8?
Ans:

int numArr = new int[]{1,2,3,4,5};

int[] sortedNumArr = Arrays.stream(numArr).boxed().sorted(Collections.reverseOrder())
.mapToInt(Integer::intValue).toArray();

Q: How to concatenate List of String/Integer Objects using some separator in Java8?
Ans:

//input
List<String> str = Arrays.asList("Welcome", "to", "TechGeekNext");

String jonStr = str.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(" - "));
//output
System.out.println(jonStr);
Output:
Welcome - to - TechGeekNext

Q: How to count each element/word from the String ArrayList in Java8?
Ans:

List<String> names = Arrays.asList("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
                          .stream()
                          .collect(
                           Collectors.groupingBy(
                             Function.identity()
                           , Collectors.counting()
                           ));
System.out.println(namesCount);
Output:
{CC=1, BB=1, AA=2}

Q: How to find only duplicate elements with its count from the String ArrayList in Java8?
Ans:

List<String> names = Arrays.asList("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
                             .stream()
				             .filter(x->Collections.frequency(names, x)>1)
				             .collect(Collectors.groupingBy
				             (Function.identity(), Collectors.counting()));
System.out.println(namesCount);
Output:
{AA=2}

Leave a Reply

Your email address will not be published. Required fields are marked *