Wednesday, 18 October 2017

How to Find Common Elements in Two Arrays - Java Program

This post is about writing a Java program to find common elements in the given arrays. It is a common interview question where it is asked with a condition not to use any inbuilt method or any inbuilt data structure like list or set.

Steps for solution

A simple solution is to loop through an array in the outer loop and then traverse through the other array in an inner loop and compare the element of the outer array with all the elements of the inner array.

If similar element is found print it and break from the inner loop.

Java program with array of numbers

 
public class FindCommonElement {

 public static void main(String[] args) {
  int[] numArray1 = {1, 4, 5};
  int[] numArray2 = {6, 1, 8, 34, 5};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i] == numArray2[j]){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
  
 }

}

Output

1
5

Java program with array of strings

Logic remains same in case of array of Strings. Only thing that changes is how you compare, with Strings you will have to use .equals method.
 
public class FindCommonElement {

 public static void main(String[] args) {
  String[] numArray1 = {"Java", "Scala", "Python"};
  String[] numArray2 = {".Net", "Scala", "Clojure", "Java", 
    "Java Script", "Python"};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i].equals(numArray2[j])){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
  
 }

}

Output

Java
Scala
Python

That's all for this topic How to Find Common Elements in Two Arrays - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to remove duplicate elements from an array - Java Program
  2. How to remove elements from an array - Java Program
  3. Array in Java
  4. Matrix Addition - Java Program
  5. If Given String Sub-Sequence of Another String - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 16 October 2017

Just In Time Compiler (JIT) in Java

When we start studying Java we get to know one of the prominent feature of Java is that Java is platform independent.

How platform independence is achieved

In a short sentence, Java is platform independent because of the fact it is both compiled and interpreted.

To explain it further; first when we compile our JAVA code .class files are generated having the platform independent byte code which is interpreted to machine native code at run time by the JVM.

Where does JIT compiler fit

This two step process, though makes Java platform independent, where you are not worried about the OS or processor while writing your code, but at the same time execution is slow because byte code is interpreted to the native code at the run time.

Because of this interpretation of the byte code to the host CPU's native instruction set there is an overhead of processor and memory usage which results in slow execution of the code.

That’s where JustInTime (JIT) compiler comes into the picture. In simple terms you can say JIT compiler compiles the already compiled code to the native code as per the processor. Since this compilation of the compiled byte code to the native machine code is done at the run time (Just in time) thus the name Just in Time compiler (JIT).

How does JIT compiler work

While the code is executed JVM automatically monitors which methods are being executed frequently and start marking the methods that are “hot”. Note that JIT compiler initially itself doesn’t compile all the code at once, initially methods are interpreted from byte code.

Marked "hot" methods are scheduled for compilation into machine code. This compilation into machine code happens on a separate JVM thread without interrupting the execution of the program. While the hot method is compiled by the JIT compiler, the JVM will keep using the interpreted version of the method and switch over to the compiled method once it is ready.

Initial compilation of the method is quick but the resulting code may not be as efficient as it could be. If a method is used quite frequently the system can get a performance boost if the code for that particular method is regenerated in a more efficient way. That is why same method may get compiled more than once and more optimizations may get applied while the code is compiled.

Once the method is marked for compilation and compiled, its count is set to zero. If method call again reaches the call count threshold the method is recompiled and more optimizations are applied to the method to make it more efficient.

That recompilation and more optimization happens because the optimization techniques are often layered and once the compiler has applied one optimization then only it may be able to see other optimizations that can be applied.

JIT compiler

How does JIT complier optimize code

Some of the optimization techniques used by JIT complier are -

  1. Inlining methods – One of the most common technique for optimizing code is method inlining. In method inlining the method call is substituted by the method body in the places where method is called. By replacing the method body in the method call the call to the method, resultant creation of stack frames is saved.

    Example code

    class A {
      B b;
      public void doProcessing() {
        x = b.getValue();
        ...
        ...
        y = b.getValue();
        ………………………….
    
      }
    }
    
    class B {
       int value;
       final int getValue() {
          return value;
       }
    }
    

    Inlining final method

    Notice in Class A method calls (getValue) are eliminated.

    class A {
      B b;
      public void doProcessing() {
        x = b.value;
        ...
        ...
        y = b.value;
        ………………………….
    
      }
    }
    

    Removing redundant loads

    y = b.value; is replaced with y = x so that local value itself can be used.
    class A {
      B b;
      public void doProcessing() {
        x = b.value;
        ...
        ...
        ...
        y = x;
        ………………………….
    
      }
    }
    
  2. Monomorphic dispatch

    Java being an object-oriented language uses subtyping/polymorphism which means most of the method invocations are virtual method lookup. The JVM checks how many different implementations of the method are there –

    • If there is only one implementation it is a monomorphic dispatch.
    • If there are 2 then it is bimorphic dispatch, in case of more than 2 it is megamorphic dispatch.

    In the monomorphic case, path-dependent types (sub type or super type) does not happen. So, we know the exact method definitions that will be called when methods are called on the passed object, because we don’t need to check which override is actually being used. This means we can eliminate the overhead of doing virtual method lookup.

  3. Removing unwanted synchronization – Overhead of obtaining locks to enter a monitor can be eliminated by removing the synchronization, if synchronized block can only be accessed by a single thread.

    As example

    public void methodA{
     B b = new B()
      Synchronized(b){
       …..
       ……
      }
    }
    

    Here new object is created with in the method so every thread will have its own object thus the synchronized block has no effect here. JVM will notice that and the method will be optimized by JIT compiler.

  4. Merging adjacent synchronized block with same object – If there are adjacent synchronized block on the same object those will be merged as an optimization.
    Public void testMethod{
      synchronized(Test.class){
       ……
       …
      }
      synchronized(Test.class){
       ……
       …
      }
    }
    
    Here these 2 synchronized blocks can be merged to create a single synchronized block.

There are many other optimizations applied like loop optimization, dead code elimination.

Reference -

http://www.oracle.com/technetwork/articles/java/architect-evans-pt1-2266278.html
https://docs.oracle.com/cd/E15289_01/doc.40/e15058/underst_jit.htm

That's all for this topic Just In Time Compiler (JIT) in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Synchronization in Java multithreading
  2. Race condition in Java multi-threading
  3. How to compile Java program at runtime
  4. How to run javap programmatically from Java Program

You may also like -

>>>Go to Java advance topics page

Wednesday, 11 October 2017

If Given String Sub-Sequence of Another String - Java Program

I recently remembered one interview 6-7 years back where I was asked to write a Java program to find if given string is the subsequence of another string. I started writing the program but my approach was wrong as I was getting confused between subsequence and substring.

What I wrote was to ensure that given string is the substring of another string and my assumption was that the characters should come continuously. As example if I have to find "net" exists in "netjs", then it is true as all the characters n, e, t are coming continuously in netjs.

But that’s not what subsequence means so before writing the program to ensure that given string is the subsequence of another string first let’s have a proper definition of what subsequence means.

A subsequence is a sequence where all the characters of the subsequence are present in another sequence, are in order but may not be continuous. As example – If our subsequence is “net” and we have to find if that subsequence exists in the string “npeght” then it should return true as all the characters of the subsequence (n, e, t) are present in the given string and characters are in the same order. If we delete the extra elements in the second string (p, g, h) then we get the same string.

Approach for the Java program

We can have both iterative and recursive logic for this program. Approach remains same for both if we have to find that String-1 is subsequence of String-2 then we start from one end of the string, it can be leftmost or rightmost (In the program here I started from the leftmost character of the strings). If character of String-1 is found in String-2 then we increment the index by 1 for both strings, if character of String-1 is not found in String-2 then we increment the index by 1 only for String-2.

Java code to find subsequence

This code has both iterative and recursive solutions.

  • Method isStringSequenceFound(String str1, String str2, int i, int j)is for recursive solution.
  • Method isStringSequenceFound(String str1, String str2) is for iterative solution.
public class SubSequenceFinder {

 public static void main(String[] args) {
        // Iterative method call
        String str1 = "abc";
        String str2 = "asc";
        boolean flag = isStringSequenceFound(str1, str2);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
        
        // Recursive method call
        str1 = "java";
        str2 = "javelina";
        flag = isStringSequenceFound(str1, str2, 0, 0);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);
        
        // Iterative method call
        str1 = "abc";
        str2 = "asbbdfc";
        flag = isStringSequenceFound(str1, str2);
        System.out.println(str1 + " is subsequence of " + str2 + " - " + flag);

 }
 
 // Recursive method to find sub-sequence
 static boolean isStringSequenceFound(String str1, String str2, int i, int j){
  // Exit condition - if i becomes equal to length 
  // of string-1 that means all the characters are found in the second string
  if(str1.length() == i){
   return true;
  }
  //if length of String-2 becomes equal to j that means string 2 is completely
  // traversed and all the characters of string-1 are not found
  if(str2.length() == j){
   System.out.println();
   return false;
  }
  //
  if(str1.charAt(i) == str2.charAt(j)){
   // increase both i and j by 1, if char is found
   return isStringSequenceFound(str1, str2, ++i, ++j);
  }else{
   return isStringSequenceFound(str1, str2, i, ++j);
  }
 }
 
 // iterative method to find sub-sequence
 static boolean isStringSequenceFound(String str1, String str2){
  int j = 0;
  for(int i = 0; i < str2.length(); i++){
   if(str1.charAt(j) == str2.charAt(i)){
    ++j;
   }
   // All the characters of String-1 are found in String-2
   if(j == str1.length()){
    return true;
   }
  }
  // If it comes here that means all the characters of String-1
  // are not found in string-2
  return false;
 }

}

Output

abc is subsequence of asc - false
java is subsequence of javelina - true
abc is subsequence of asbbdfc - true

That's all for this topic If Given String Sub-Sequence of Another String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Count total number of times each character appears in a String
  2. Check whether a given String/Number is a palindrome or not
  3. How to find all the permutations of the given String
  4. How to reverse a string in Java
  5. Lambda Expression Callable example

You may also like -

>>>Go to Java Programs page

Thursday, 5 October 2017

How to Format Time in AM-PM Format - Java Program

In this post I’ll show how you can format time in AM-PM format.

In order to get time in AM-PM format, in the format you are creating using SimpleDateFormat (if you are not using Java 8) or DateFormatter (if you are using Java 8) just add the pattern letter ‘a’ which denotes AM-PM of the day.

Example Code using SimpleDateFormat

If you are using the java.util.Date and SimpleDateFormat

Date date = new Date();
// Pattern 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
System.out.println("TIME - " + sdf.format(date));

Output

TIME - 13:09:55 PM

Example code using DateFormatter

If you are using the new Date and Time API in Java 8, then you can use the DateFormatter class, pattern remains the same.
//Getting time
LocalTime t2 = LocalTime.now();
// Pattern
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t2.format(df);
System.out.println("Time - " + text);

Output

Time - 13:11:15 PM

Another example – Showing AM

LocalTime t1 = LocalTime.of(5, 30, 56);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss a");
String text = t1.format(df);
System.out.println("Time - " + text);

Output

Time - 05:30:56 AM

That's all for this topic How to format time in AM-PM format. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to format date in Java using SimpleDateFormat
  2. How to convert String to Date in Java
  3. How to convert date and time between different time-zones in Java
  4. How to find last modified date of a file in Java
  5. Converting int to string - Java Program

You may also like -

>>>Go to Java Programs page

Tuesday, 3 October 2017

How to Create Your Own BlockingQueue - Java Program

This post shows how you can create your own BlockingQueue using ReentrantLock and Condition interface. Condition interface provides method await and signal which work the same way as wait and notify.

Example code

Here we have a class called BufferClass which has an array of type Object, whose length is 5. So, 5 is the bound for buffer, if 5 values are already added to the array it will be blocked until at least one value is retrieved from the array.

put() and take() method are used to add value to an array and retrieve value from an array respectively.

BufferClass

 
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BufferClass {
 final Lock lock = new ReentrantLock();
 // Conditions
 final Condition produce  = lock.newCondition(); 
 final Condition consume = lock.newCondition(); 

 final Object[] valueArr = new Object[5];
 int putIndex, takeIndex;
 int count;

 public void put(Object x) throws InterruptedException {
  //System.out.println("count -- " + count);
  //System.out.println("Array length -- " + valueArr.length);
  lock.lock();
  try {
   while (count == valueArr.length){
    
    produce.await();
    //System.out.println("Awaiting");
      }
   
   valueArr[putIndex] = x;
   System.out.println("Adding - " + x);
       if (++putIndex == valueArr.length){
        putIndex = 0;
       }
       // increment count
       ++count;
       consume.signal();
     } finally {
      lock.unlock();
  }
 }

    public Object take() throws InterruptedException {
      lock.lock();
      try {
        while (count == 0){
         consume.await();
        }
        Object x = valueArr[takeIndex];
        System.out.println("Retrieving - " + x);
        if (++takeIndex == valueArr.length){
         takeIndex = 0;
        }
        // reduce the count
        --count;
        // signal producer
        produce.signal();
        return x;
      } finally {
        lock.unlock();
      }
    }
}

To test this BufferClass we have another class BufferClassDemo where two threads are created, one will add values to the buffer and another will retrieve values from the buffer. Here 10 values are added, BufferClass should ensure if 5 values are already added any attempt to add any further value should be blocked. Same way if the buffer is empty any attempt to retrieve value should be blocked.

 
public class BufferClassDemo {
 
 public static void main(String[] args) {
  BufferClass bufferClass = new BufferClass();
  // Creating two threads
  Thread producer = new Thread(new Producer(bufferClass));
  Thread consumer = new Thread(new Consumer(bufferClass)); 
  // starting threads
  producer.start();
  consumer.start();
 }
}

class Producer implements Runnable {

    private BufferClass bufferClass;
    
    public Producer(BufferClass bufferClass){
        this.bufferClass = bufferClass;
    }
    @Override
    public void run() {
      for (int i = 1; i <= 10; i++) {
            try {
                //Thread.sleep(10);                            
             bufferClass.put(i);                            
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable {
 private BufferClass bufferClass;
    
    public Consumer(BufferClass bufferClass){
        this.bufferClass = bufferClass;
    }
    @Override
    public void run() {
      for (int i = 1; i <= 10; i++) {
            try {
               // Thread.sleep(500);
             bufferClass.take();               
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

Output

Output from one of the run. Note that output may vary but the condition of not having more than 5 elements and blocking any attempt to add should hold.

Adding - 1
Adding - 2
Adding - 3
Adding - 4
Adding - 5
Retrieving - 1
Retrieving - 2
Retrieving - 3
Retrieving - 4
Retrieving - 5
Adding - 6
Adding - 7
Adding - 8
Retrieving - 6
Retrieving - 7
Retrieving - 8
Adding - 9
Retrieving - 9
Adding - 10
Retrieving - 10

That's all for this topic How to Create Your Own BlockingQueue - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ArrayBlockingQueue in Java Concurrency
  2. How to run threads in sequence - Java Program
  3. How to create deadlock in Java multi-threading - Java Program
  4. Print odd-even numbers using threads and wait-notify
  5. Producer-Consumer Java program using ArrayBlockingQueue

You may also like -

>>>Go to Java Programs page

Wednesday, 13 September 2017

Java Stream API Interview Questions

  1. What is Stream API in Java?

    Stream API is added in Java 8 and works very well in conjunction with lambda expressions. You can create a pipeline of stream operations to manipulate data by performing operations like search, filter, sort, count, map etc.

    Read more about Stream API in Java here.

  2. What is stream in Stream API?

    A stream can be visualized as a pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc.), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

    Read more about Stream API in Java here.

  3. Explain stream operations with an example?

    In this example let's take an ArrayList as an input. There are two operations - take only those elements of the list which are greater than 5 and then sort the result. After that print the elements of the list.

    // Creating the list
    List<Integer> numList = Arrays.asList(34, 6, 3, 12, 65, 1, 8);
    numList.stream().filter((n) -> n > 5).sorted().forEach(System.out::println); 
    
    Here ArrayList is the data source for the stream and there are two intermediate operations –
    • filter - Filter condition here is; take only those elements of the list which are greater than 5.
    • sorted - sort that filtered output of the last stream.
    Terminal operation here is forEach statement (provided in Java 8) which iterates the sorted result and displays them. Read more about forEach statement in Java 8 here.

  4. How many types of Stream operations are there?

    Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines.

    • Intermediate operations return a new stream. They are always lazy; executing an intermediate operation does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
    • Terminal operations such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
    See some Stream API examples here.

  5. What are Stateless and Stateful operations in Java stream?

    Intermediate operations are further divided into stateless and stateful operations.

    • Stateless operations, such as filter and map, retain no state from previously seen element when processing a new element, each element can be processed independently of operations on other elements.
    • Stateful operations, such as distinct and sorted, may incorporate state from previously seen elements when processing new elements. Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
    See some Stream API examples here.

  6. What is Parallel Stream in Java Stream API?

    You can execute streams in serial or in parallel. When a stream executes in parallel, the Java runtime partitions the stream into multiple sub-streams.

    As example - Collection has methods Collection.stream() and Collection.parallelStream(), which produce sequential and parallel streams respectively.

    Read more about parallel stream here.

  7. What is the benefit of using parallel stream?

    When parallel stream is used the Java runtime partitions the stream into multiple sub-streams. This parallel execution of data, with each sub-stream running in a separate thread, will result in increase in performance.

    Read more about parallel stream here.

  8. Can you use streams with primitives?

    Streams work only on object references. They can’t work on primitive types so you have two options to use primitives.

    • You can wrap primitive types into a wrapper object. As example Stream<Integer>, Stream<Long> or Stream<Double>.
    • Second and better option is to use primitive specializations of Stream like IntStream, LongStream, and DoubleStream that can store primitive values.
    • As example - IntStream is = IntStream.of(3, 4, 5, 6);

    Read more about Primitive type streams in Java here.

  9. How can you transform Stream to primitive type Stream?

    Stream interface provides methods mapToInt, mapToDouble and mapToLong that can be used to transform stream of objects to a stream of primitive types.

    As example - If you have a list of employee objects and you want to get the maximum salary. In that case you can take the salary field and use mapToInt method to get a stream of primitive types. Then you can use max method on that primmitive type stream.

    OptionalInt maxSalary = empList.parallelStream().mapToInt(e -> e.getSalary()).max();
    
    Read more about Primitive type streams in Java Stream API here.

  10. What are Reduction Operations in Java Stream API?

    Stream API contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations because these operations reduce the stream to a single non-stream value.

    Read more about Reduction Operations in Java Stream API here.

  11. What are Map operation in Java Stream API?

    Map operations are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.

    Since new stream is returned map operation is an intermediate operation.

    Read more about Map operation in Java Stream API here.

  12. What is a mutable reduction operation?

    A mutable reduction operation can be defined as an operation that accumulates input elements into a mutable result container, such as a Collection or StringBuilder.

    Read more about Reduction operation in Java Stream API here.

  13. What is a collect method in Java stream?

    Using collect method you can store the result of the stream operation into a collection. This is a terminal operation.

    As example - If you have employee objects and you want a list having names of all the employees you can use the toList method of the Collectors class.

    List<String> nameList = empList.stream().map(Employee::getName).collect(Collectors.toList());
    
    Read more about Collecting in Java Stream API here.

  14. What is FlatMap in Java?

    In mapping operation the given function is applied to all the elements of the stream. Where as flattening a structure, means bringing all the nested structures at the same level.

    As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this -

    [“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”]
    
    Read more about FlatMap in Java here.

  15. What is FlatMap in Java?

    In mapping operation the given function is applied to all the elements of the stream. Where as flattening a structure, means bringing all the nested structures at the same level.

    As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this -

    [“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”]
    

    flatMap() method means you are bringing both of them together, function will be applied to all the elements of the stream and then it will be flatten to have a single level structure.

    Read more about FlatMap in Java here.

  16. What is Spliterator in Java??

    Spliterators, like iterators, are for traversing the elements of a source. Spliterator can split the source and iterate the splitted parts in parallel. That way a huge data source can be divided into small sized units that can be traversed and processed parallely.

    You can also use spliterator even if you are not using parallel execution.

    Read more about Spliterator in Java here.

Related Topics

  1. Java Exception Handling interview questions
  2. Java Multi-threading interview questions
  3. Java Collections interview questions
  4. Java Concurrency interview questions
  5. Java Lambda Expressions Interview Questions

Monday, 4 September 2017

How to read Properties file in Java

If you have any configurable data in your application like DB configuration, user settings its better to keep it in a properties file. A properties store data in a form of key/value pair.

In this tutorial you will see how to read a properties file.

Project structure

For this example we’ll have a properties file named app.properties file in a folder called resource. The resource folder is at the same level at the src folder in the Java project.

Steps

  1. Create an instance of Properties class.
  2. Read the properties file.
  3. Load the file to the instance of Properties class using the load method.

Content of the properties file

Here the properties file used is named app.properties file with it’s content as -

user=TestUser
url=https://netjs.blogspot.com

Loading properties file from the file system

One way to read properties file is to load it from the file system.

Example code

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropDemo {
 private Properties appProp = new Properties();
 public static void main(String[] args) {
  PropDemo pDemo = new PropDemo();
  pDemo.loadPropertiesFile();
  pDemo.readProperties();
  
  
 }
 
  // This method is used to load the properties file
  private void loadPropertiesFile(){
      InputStream iStream = null;
      try {
   // Loading properties file from the path (relative path given here)
   iStream = new FileInputStream("resource/app.properties");   
   appProp.load(iStream);
      } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
      }finally {
    try {
     if(iStream != null){
      iStream.close();
     }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
     }
  }
 
  /**
   * Method to read the properties from a
   * loaded property file
  */
  private void readProperties(){
    System.out.println("User name - " + appProp.getProperty("user"));
    System.out.println("URL - " + appProp.getProperty("url"));
    // reading property which is not there
    System.out.println("City - " + appProp.getProperty("city"));
   
  }

}

Output

User name - TestUser
URL - https://netjs.blogspot.coms
City - null

Here you can see that in the code there is an attempt to read the property “city” which doesn’t exist in the app.properties file that’s why it is retrieved as null.

Loading properties file from classpath

If you have properties file in the project classpath then you can load it by using the getResourceAsStream method.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropDemo {
 private Properties appProp = new Properties();
 public static void main(String[] args) {
   PropDemo pDemo = new PropDemo();
   pDemo.loadProperties();
   pDemo.readProperties();
 }
 
 // This method is used to load the properties file
 private void loadProperties(){
   InputStream iStream = null;
   try {
    // Loading properties file from the classpath
    iStream = this.getClass().getClassLoader().
                            getResourceAsStream("app.properties");
    if(iStream == null){
     throw new IOException("File not found");
    }
    appProp.load(iStream);
   } catch (IOException e) {
    e.printStackTrace();
   }finally {
    try {
     if(iStream != null){
      iStream.close();
     }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
 }
  
 /**
  * Method to read the properties from a
  * loaded property file
 */
 private void readProperties(){
   System.out.println("User name - " + appProp.getProperty("user"));
   System.out.println("URL - " + appProp.getProperty("url"));
 }
}

Output

User name - TestUser
URL - https://netjs.blogspot.com

That's all for this topic How to read Properties file in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to read file from the last line in Java
  2. Unzipping files in Java
  3. Reading file in Java 8
  4. Writing file in Java
  5. How to read properties file in Spring Framework

You may also like -

>>>Go to Java Programs page

Monday, 28 August 2017

New Date and Time API in Java 8

In Java 8 along with some new features like lambda expressions and stream API there is one more very important addition – A new Date and Time API which addresses the shortcomings of the old java.util.Date and java.util.calendar.

The classes for the new Java date and time API resides in java.time package and use the calendar system defined in ISO-8601 (based on the Gregorian calendar system) as the default calendar. Other non-ISO calendar systems can be represented using the java.time.chrono package.

Features of the new Date and Time API

As already mentioned the new API does address the shortcomings of the old APIs, so let’s see what are some of the most important features of the new API.

  1. Immutable classes – In the new API all the core classes are immutable thus thread safe. That is an improvement over the old API where thread safety was an issue, as example if you were providing a format using the SimpleDateFormat class, then you had to ensure thread safety using synchronization or ThreadLocal class as SimpleDateFormat class is not thread safe.
  2. More intuitive and comprehensive - The classes in the new API relates closely with the different Date and Time use cases. There are many more utility methods provided.
  3. Better support for time zones – If you have worked in an application where you had to deal with dates and times in different time zones and day light savings then you would really appreciate the support provided for these operations in the new Date and Time API.

One trivia here - The project to design new Date and Time API has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310.

LocalDate, LocalTime and LocalDateTime

These are the classes which you will use most of the time. These classes represent the date, time or both of the day, based on the class used. Note that these classes won’t have associated time zone information. These classes cannot represent an instant on the time-line without additional information such as an offset or time-zone.

Some of the examples where you will use these classes are birthdays, holidays.

LocalDate

LocalDate is a date in the ISO-8601 format, yyyy-MM-dd. LocalDate does not store or represent a time or time-zone. Instead, it is just a description of the date.

Examples using LocalDate class

Let’s have a look at some of the methods provided by the LocalDate class.

  1. If you want to obtain an instance of the current date from the system clock in the default time-zone.
    LocalDate curDate = LocalDate.now();
    System.out.println("Current Date - " + curDate); //Current Date – 2017-08-20
    
  2. If you want to obtain an instance of LocalDate from a year, month and day.
    LocalDate date = LocalDate.of(2016, 04, 3);
    System.out.println("Date - " + date); // Date – 2016-04-03
    
    Month value can be provided using Month enum which resides in java.time package.
    LocalDate date = LocalDate.of(2016, Month.APRIL, 3);
    

    Providing wrong value like LocalDate date = LocalDate.of(2016, Month.APRIL, 32); will result in DateTimeException.

    Exception in thread "main" java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 32
    
  3. If you want to know whether the year is a leap year or not -
    System.out.println("Leap year - " + date.isLeapYear()); // Leap year – true
    
  4. Many a times you need to go back/forward by a few days, months or years, there are utility methods for that like minusDays, minusMonths, plusYears, plusWeeks.
    • If you want to go back by 50 days from the given LocalDate.
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.minusDays(50)); 
      //New Date – 2016-03-09
      
    • If you want to go back by 2 weeks -
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.minusWeeks(2))
      //New Date – 2016-04-14
      
    • If you want to add 1 year to the date -
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.plusYears(1));
      //New Date – 2017-04-28
      
    • If you want to add 3 months to the date -
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.plusMonths(3));
      //New Date – 2016-07-28
      
  5. There are methods like getDayOfWeek, getMonth, getDayOfYear to give you the value you are looking for.

    Example using getMonth() -

    LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
    System.out.println("Date - " + date);
      
    Month month = date.getMonth();
    if(month.equals(Month.APRIL)){
     System.out.println("It's April");
    }//It's April
    

LocalTime

LocalTime is a time in the ISO-8601 format, like HH:mm:ss.SSS.

LocalTime class does not store or represent a date or time-zone. It is a description of the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

Time is represented to nanosecond precision. For example, the value "14:32.30.123456789" can be stored in a LocalTime.

Examples using LocalTime class

  1. If you want to Obtain an instance of the current time from the system clock in the default time-zone.
    LocalTime curTime = LocalTime.now();
    System.out.println("Current Time - " + curTime); //Current Time – 18:46:11.659
    
  2. If you want to obtain an instance of LocalTime from an hour and minute or from an hour, minute and second or from an hour, minute, second and nanosecond you can use the correct of method to do that -

    While giving values for these parameters keep in mind the ranges for the same -

    • hour - the hour-of-day to represent, from 0 to 23
    • minute - the minute-of-hour to represent, from 0 to 59
    • second - the second-of-minute to represent, from 0 to 59
    • nanoOfSecond - the nano-of-second to represent, from 0 to 999,999,999
    LocalTime time = LocalTime.of(16, 45, 34);
    System.out.println("Time - " + time);//Time - 16:45:34
    
  3. If you want to subtract from the given time or add to the given time you can use methods minusHours(), minuMinutes(), plusNanos(), plusSeconds().
    • If you want to subtract 40 minutes from the given time.
      LocalTime time = LocalTime.of(16, 45, 34);
      System.out.println("Time - " + time);
        
      System.out.println("New Time - " + time.minusMinutes(40));
      //New Time – 16:05:34
      
    • If you want to add 12 Hours to the given time
      LocalTime time = LocalTime.of(16, 45, 34);
      System.out.println("Time - " + time);
        
      System.out.println("New Time - " + time.plusHours(12));
      //New Time – 04:45:34
      
  4. There are methods like getHour(), getMinute(), getNano(), getSecond() to give you the value you are looking for.

    If you want to get hour value of the given LocalTime -

    LocalTime time = LocalTime.of(16, 45, 34);
    System.out.println("Time - " + time.getHour());
    //Hour – 16
    

LocalDateTime

LocalDateTime is a date-time in the ISO-8601 calendar format, such as yyyy-MM-ddTHH:mm:ss.SSS. LocalDateTime class does not store or represent a time-zone. It is a description of the date combined with the local time. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

Examples using LocalDateTime

Since LocalDateTime represents both date and time so most of the methods in this class are similar to what you have already seen for LocalDate and LocalTime.

  1. If you want to obtain an instance of the current date-time from the system clock in the default time-zone.
    LocalDateTime curDateTime = LocalDateTime.now();
    System.out.println("Current Date Time - " + curDateTime);
    // Current Date Time – 2017-08-20T19:31:55.001
    
  2. If you want to obtain an instance of LocalDateTime from year, month, day, hour and minute you can use of method. There are overloaded of methods where you can also provide second and nanosecond.
    LocalDateTime dateTime = LocalDateTime.of(2017, 8, 15, 14, 15, 56);
    System.out.println("Date Time - " + dateTime);
    // Date Time – 2017-08-15T14:15:56
    
  3. If you want to get the LocalTime part of this date-time.
    LocalDateTime curDateTime = LocalDateTime.now();
    System.out.println("Current Date Time - " + curDateTime);//Current Date Time - 2017-08-25T11:41:49.570
        
    LocalTime localTime = curDateTime.toLocalTime(); 
    System.out.println("localTime - " + localTime);//localTime - 11:41:49.570
    
  4. If you want to get the LocalDate part of this date-time.
    LocalDate localDate = curDateTime.toLocalDate(); 
    System.out.println("localDate - " + localDate); //localDate – 2017-08-25
    

TemporalAdjusters class

TemporalAdjusters class provides static methods for common adjustments of date and time. For using TemporalAdjusters convenient way is to use the Temporal.with(TemporalAdjuster); method. Here note that Temporal is an interface which is implemented by LocalDate/Time classes.

Examples using TemporalAdjusters class

  1. Finding the first or last day of the month
    LocalDateTime curDateTime = LocalDateTime.now();
    System.out.println("Last day of the month - " + curDateTime.with(TemporalAdjusters.lastDayOfMonth())); 
    //Last day of the month – 2017-08-31T12:01:03.207
    
  2. Finding the first or last day-of-week within a month.

    As example if you want to find the first Sunday of the given month -

    LocalDate curDate = LocalDate.now();
    System.out.println("Current Date - " + curDate);//Current Date - 2017-08-25
      
    System.out.println("First Sunday of the month - " + curDate.with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.SUNDAY)));
    //First Sunday of the month – 2017-08-06
    

Instant

Instant class as the name suggests models a point on the time-line. This class can be used to provide time-stamps in an application. Instant class even has methods like equals, compareTo, isAfter, isBefore to compare two instants that helps when Instant is used as a timestamp.

Examples using Instant class

  1. If you want to obtain the current instant from the system clock.
    Instant ist = Instant.now();
    System.out.println("instant " + ist); 
    // instant 2017-08-25T13:58:13.286Z
    
  2. if you want to add/subtract mili seconds, nano seconds or seconds to a given instant there are plus and minus methods to do that. As example if you add 20 seconds to an instant.
    Instant ist = Instant.now();
    System.out.println("instant " + ist); // instant 2017-08-25T14:22:26.592Z
    System.out.println("instant + 20 -  " + ist.plusSeconds(20));] 
    // instant + 20 -  2017-08-25T14:22:46.592Z
    

Duration and Period

Duration measures an amount of time using time-based values like seconds, nanoseconds.

A Period measures an amount of time using date-based values like years, months, days.

Note that a Duration is not connected to the timeline. Adding a Duration equivalent to 1 day to a ZonedDateTime results in exactly 24 hours being added, regardless of daylight saving time or other time differences that might result.

Where as when you add a Period to a ZonedDateTime, the time differences are observed.

Examples using Duration

  1. If you want to find duration between two LocalTime objects
    LocalTime t1 = LocalTime.of(5, 30, 56);
    LocalTime t2 = LocalTime.now();
    System.out.println("From time - " + t1 +  " To time - " + t2);
      
    // Duration
    Duration dr = Duration.between(t1, t2);
    System.out.println("Hours between " + dr.toHours());
    System.out.println("Minutes between " + dr.toMinutes());
    

    Output

    From time - 05:30:56 To time - 20:07:31.713
    Hours between 14
    Minutes between 876
    
  2. If you want to add/subtract hours, minutes or seconds to the given time. As example if you want to subtract 10 minutes from the given time.
    LocalTime t2 = LocalTime.now();
    System.out.println("t2-10mins " + t2.minus(Duration.ofMinutes(10)));
    

Examples using Period

  1. If you want to find difference between two LocalDate objects.
    LocalDate dt1 = LocalDate.of(2016, 4, 23);
    LocalDate dt2 = LocalDate.now();
    System.out.println("From Date - " + dt1 +  " To Date - " + dt2);
    // Period
    Period pr = Period.between(dt1, dt2);
    System.out.println("Difference - " + pr.getYears() + " Year(s) " + pr.getMonths()+ " Month(s) " + pr.getDays() + " Day(s)");
    

    Output

    Output
    From Date - 2016-04-23 To Date – 2017-08-25
    Difference - 1 Year(s) 4 Month(s) 2 Day(s)
    
  2. If you want to add/subtract days, weeks, months or year to the given date. As example if you want to subtract 2 months from the given date.
    LocalDate dt2 = LocalDate.now(); // 2017-08-25
    System.out.println("dt2-2 Months " + dt2.minus(Period.ofMonths(2))); 
    //dt2-2 Months 2017-06-25
    

ChronoUnit.between

The ChronoUnit enum defines the units used to measure time. The ChronoUnit.between method is useful when you want to measure difference in a single unit of time only, such as days or seconds. The between method works with all temporal-based objects, but it returns the amount in a single unit only.

Examples using ChronoUnit.between

  1. To get hours or minutes between two LocalTime objects.
    LocalTime t1 = LocalTime.of(5, 30, 56);
    LocalTime t2 = LocalTime.now();
    long hrs = ChronoUnit.HOURS.between(t1, t2);
    System.out.println("Hours between " + hrs); //Hours between 14
      
    long mins = ChronoUnit.MINUTES.between(t1, t2);
    System.out.println("Minutes between " + mins);//Minutes between 897
    
  2. To get days between two LocalDate objects.
    LocalDate dt1 = LocalDate.of(2016, 4, 23);
    LocalDate dt2 = LocalDate.now(); //2017-08-25
    
    // ChronoUnit.between
    long days = ChronoUnit.DAYS.between(dt1, dt2);
    System.out.println("Days between " + days);//Days between 489
    

ZonedDateTime

ZonedDateTime represents date-time with a time-zone in the ISO-8601 calendar system, such as 2017-08-26T10:15:04.035+05:30[Asia/Calcutta].

ZonedDateTime is an immutable representation of a date-time with a time-zone. ZonedDateTime class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset.

Examples using ZonedDateTime

  1. If you want to obtain the current date-time from the system clock in the default time-zone.
    ZonedDateTime zdt = ZonedDateTime.now();
    System.out.println("Zoned time - " + zdt); 
    // Zoned time – 2017-08-26T10:42:36.796+05:30[Asia/Calcutta]
    
  2. If you want to obtain the current date-time from the system clock in the specified time-zone.
    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
    System.out.println("Zoned time - " + zdt);
    //Zoned time – 2017-08-26T01:14:39.538-04:00[America/New_York]
    
  3. If you want to obtain an instance of ZonedDateTime using LocalDate, LocalDateTime, Instant or providing year, month, day, hour, minute, second yourself you can use one of the of() method. As example if you want to obtain an instance of ZonedDateTime using LocalDateTime and ZoneID as Paris.
    ZonedDateTime zdt1 = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Europe/Paris"));
    System.out.println("Zoned time - " + zdt1); 
    // Zoned time - 2017-08-26T10:50:09.528+02:00[Europe/Paris]
    
  4. Just like LocalDatetime there are methods to add/subtract year, month, week, day, hour, minute, second, nanosecond. As example if you want to add 3 months to the given ZonedDateTime object.
    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
    System.out.println("Zoned time - " + zdt); 
    //Zoned time - 2017-08-26T01:31:23.901-04:00[America/New_York]
     
    System.out.println("Zoned time + 3 Months - " + zdt.plusMonths(3));
    //Zoned time + 3 Months – 2017-11-26T01:31:23.901-05:00[America/New_York]
    
    Notice the difference in offset (changed from -4 to -5) it is because of the daylight saving.
  5. There are also get methods to get the year, month, week, day, hour, minute, second, nanosecond, offset part of the given ZonedDateTime. As example if you want to get the offset part -
    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
    System.out.println("Zoned time - " + zdt); // Zoned time - 2017-08-26T01:36:37.930-04:00[America/New_York]
    System.out.println("Zoned time offset : " + zdt.getOffset()); // Zoned time offset : -04:00
    

Formatting and Conversion in new Date & Time API

That's all for this topic New Date and Time API in Java 8. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to format date in Java using SimpleDateFormat
  2. How to convert date and time between different time-zones in Java
  3. Method reference in Java 8
  4. Optional class in Java 8
  5. effectively final in Java 8

You may also like -

>>>Go to Java advance topics page

Wednesday, 23 August 2017

How to convert date and time between different time-zones in Java

You may come across a scenario where you need to convert date & time between different time zones.

As example - In a flight application if you need to derive the arrival time of the flight in a different time zone.

In this post we’ll see how it can be done using the new Java 8 Data and Time API which has classes like ZoneId and ZonedDateTime for that purpose.

If you are using Java 6 or 7 you can have a look at ThreeTen Backport http://www.threeten.org/threetenbp/ which provides a backport of the Java SE 8 date-time classes to Java SE 6 and 7.

Example Code

For this example, I am taking a scenario where flight departs from NewArk (USA) and arrives at New Delhi (India). Departure time is 14:15 PM and date is Aug 28th, 2017. Total flight time is 19 Hrs. 25 Minutes. Using that information, you need to get the arrival time in New Delhi.

If you go by total flight time and the departure time then the arrival time would be 09:40 AM on Aug 29th, 2017. But you’ll need to consider the time zone and time difference between these zones too.

What you need to do is -

  • Create Zone Ids for the two time-zones.
  • Then create a LocalDateTime object with the departure date and time information.
  • Using that create a ZonedDateTime for the departing ZoneId.
  • Then get the ZonedDateTime for the arriving ZoneID for the same instant (New_York) in the different time-zone. This gives you the departure time in the arriving ZoneId (Delhi).
  • Now just add the total flight time to it in order to get the arrival time.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDate {

 public static void main(String[] args) {
  //Getting zone Ids
  ZoneId newArk = ZoneId.of("America/New_York");
  ZoneId delhi = ZoneId.of("Asia/Kolkata");
  
  LocalDateTime dateTime = LocalDateTime.of(2017, 8, 28, 14, 15);
  System.out.println("Date time " + dateTime);

  ZonedDateTime newArkDateTime = ZonedDateTime.of(dateTime, newArk);
  System.out.println("Date time - NewArk " + newArkDateTime);
  
  // Getting same time in different time zone
  ZonedDateTime delhiDateTime = newArkDateTime.withZoneSameInstant(delhi);
  System.out.println("Date time - India " + delhiDateTime);
   
  // Total flight time - 19 Hrs. 25 Mins. converted to mins.
  ZonedDateTime arrivalTime = delhiDateTime.plusMinutes(1165);
  
  System.out.println("Arrival Date time - Delhi " + arrivalTime);
 }
}

Output

Date time 2017-08-28T14:15
Date time - NewArk 2017-08-28T14:15-04:00[America/New_York]
Date time - India 2017-08-28T23:45+05:30[Asia/Kolkata]
Arrival Date time - Delhi 2017-08-29T19:10+05:30[Asia/Kolkata]

Day light saving

The above code will take care of the day light saving too. You can change the month to November to verify (Day light saving ends on November 5).

LocalDateTime dateTime = LocalDateTime.of(2017, 11, 28, 14, 15);

With that date if we execute the code output is –

Output

Date time 2017-11-28T14:15
Date time - NewArk 2017-11-28T14:15-05:00[America/New_York]
Date time - India 2017-11-29T00:45+05:30[Asia/Kolkata]
Arrival Date time - Delhi 2017-11-29T20:10+05:30[Asia/Kolkata]

You can see the one hour difference in arrival now as day light saving is not observed in India.

That's all for this topic How to convert date and time between different time-zones in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to format date in Java using SimpleDateFormat
  2. How to convert Date to String in Java
  3. How to convert String to Date in Java
  4. How to find last modified date of a file in Java
  5. Converting int to string - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 21 August 2017

Java Lambda Expressions Interview Questions

  1. What is lambda expression?

    Lambda expression in itself is an anonymous method i.e. a method with no name which is used to provide implementation of the method defined by a functional interface.

    A new syntax and operator has been introduced in Java for Lambda expressions.

    General form of lambda expression

    (optional) (Arguments) -> body
    

    Here you can see a new arrow operator or lambda operator which divides the lambda expression into two parts. Left side specifies parameters required by the lambda expression. Parameters are optional, if no parameters are needed an empty parenthesis can be given. Right side known as lambda body specifies the logic of the lambda expression.

    Read more about lambda expressions in Java here.

  2. Give some examples of lambda expressions.

    A very simple example of lambda expression would be -
    () -> 5
    

    This lambda expression takes no parameter (that's why empty parenthesis) and returns the constant value 5.

    The above lambda expression is equivalent to the following Java code -

    int getValue(){
        return 5;
    }
    

    Another example which has 2 parameters -

    // concatenating two strings, it has 2 string parameters and they are concatenated in lambda body
    (String s1, String s2) -> s1+s2;
    
    See more lambda expressions examples here.

  3. What is a functional interface?

    A functional interface is an interface with only one abstract method. A functional interface is also known as SAM type where SAM stands for (Single Abstract Method).

    An example of functional interface with in Java would be Runnable interface which has only one method run().

    public interface Runnable {
      public void run();
    }
    
    Read more about functional interface in Java here.

  4. How do you use lambda expression with functional interface?

    Lambda expression provides implementation of the abstract method defined by the functional interface.

    Read more about functional interface in Java here.

  5. How target type is inferred for the lambda expression?

    Lambda expression doesn't have a type of its own. A lambda expression provides implementation of the abstract method defined by the functional interface. Thus the functional interface specifies its target type.

    Lambda supports "target typing" which infers the object type from the context in which it is used.

    To infer that object type from the context -

    • The parameter type of the abstract method and the parameter type of the lambda expression must be compatible. For Example, if the abstract method in the functional interface specifies one int parameter, then the lambda should also have one int parameter explicitly defined or implicitly inferred as int by the context.
    • Its return type must be compatible with the method's type.
    • Lambda expression can throw only those exceptions which are acceptable to the method.
    Read more about lambda expressions in Java here.

  6. Explain target typing with an example.

    Let's say there is a functional interface IMyFunc

    interface IMyFunc {
        int getValue(int num);
    }
    

    And a class LambdaDemo with a lambda expression which implements this functional interface.

    public class LambdaDemo {
    
        public static void main(String[] args) {
        // lambda expression
            IMyFunc myFactorialFunc = (num) -> {
                int fact = 1;
                for(int i = 1; i <= num; i++){
                    fact = i * fact;
                }
                return fact;
            };
            System.out.println("Factorial of 7 is " + myFactorialFunc.getValue(7));
        }
    }
    

    Here you can see that the lambda expression is assigned to the variable of type IMyFunc(functional interface). Now when the method myFactorialFunc.getValue(7) is called it will know that the lambda expression is providing the implementation of the method getValue() because -

    • The parameter type of the abstract method and the parameter type of the lambda expression are compatible.
    • getValue() method's return type is compatible with the return type of the lambda expression.

    So you can see in this example how target type of the lambda expression is inferred from the context.

    See more lambda expressions examples here.

  7. (int x, int y) -> x+y; or (x, y) -> x + y; which one of these is a valid lambda expression?

    Both of them are valid lambda expressions if used in a correct context.

    With the first one (int x, int y) -> x+y; we know that the parameters must be of type int.

    In case of (x, y) -> x + y; if used in a correct context type can be inferred from the context in which the lambda expression is executed.

    See more lambda expressions examples here.

  8. (int x, y) -> x + y; is this a valid lambda expression?

    You can't have lambda expression where type for only one of the parameter is explicitly declared so this lambda expression is invalid.

    See more lambda expressions examples here.

  9. What is block lambda expression?

    A block lambda is the lambda expression where the right side of the lambda expression is a block of code.

    As example -

    IMyFunc myFactorialFunc = (num) -> {
                int fact = 1;
                for(int i = 1; i <= num; i++){
                    fact = i * fact;
                }
                return fact;
            };
    
    Where as (String s1, String s2) -> s1+s2; is a single expression lambda.

  10. Why lambda expression is called a poly expression?

    The type of a lambda expression is inferred from the target type thus the same lambda expression could have different types in different contexts.

    As example -

    If there is a functional interface IMyInterface

    interface IMyInterface {
        int getValue();
    }
    

    Then both of the following lambda expressions can be of type IMyInterface.

    // Lambda expression
    objRef = () -> 7;
    
    // Another lambda expression using the same interface reference 
    objRef = () -> 7 * 5;
    

    Another example -

    Let’s say there are these 2 functional interfaces.

    @FunctionalInterface
    interface TestInterface {
      int addValues(int val1, int val2);
    }
    
    @FunctionalInterface
    interface StrInterface {
      String concat(String str1, String str2);
    }
    

    Then you can write a lambda expression as follows -

    TestInterface obj1;
    obj1 = (x, y) -> x + y;
    System.out.println("" + obj1.addValues(2, 3));
        
    StrInterface obj2;
    obj2 = (x, y) -> x + y;
    System.out.println("" + obj2.concat("Hello", "Lambda"));
    

    If you notice here same lambda expression (x, y) -> x + y; is used both of the times but the type of the parameters and the return type determines which functional interface should be referred.

    Read more about functional interface in Java here.

  11. Can we have a generic functional interface?

    Since lambda expression doesn't have type parameters of its own so it can't be generic. But the functional interface that specifies the target type for the lambda expression can be generic.

    As example -

    A generic functional interface -

    @FunctionalInterface
    interface GenInterface<T, U, R> {
      R addValues(T t, U u);
    }
    

    Lambda expression implementing the given functional interface with Integer types.

    GenInterface<Integer, Integer, Integer> obj1;
    obj1 = (x, y) -> x + y;
    System.out.println("" + obj1.addValues(2, 3));
    
    Lambda expression implementing the given functional interface with String types.
    GenInterface<String, String, String> obj2;
    obj2 = (x, y) -> x + y;
    System.out.println("" + obj2.addValues("Hello", "Lambda")); 
    
    Read more about functional interface in Java here.

  12. What about inbuilt functional interfaces?

    With Java 8 many new functional interfaces are being defined, in fact there is a whole new package java.util.function added with many functional interfaces. The interfaces in this package are general purpose functional interfaces used by the JDK, and are available to be used by user code as well.

    Some of the inbuilt functional interfaces -
    public interface Consumer<T> {
      void accept(T t);
    }
     
    public interface Supplier {
      T get();
    }
    
    public interface Function {
      R apply(T t);
    }
    
    Read more about functional interface in Java here.

  13. Comparator method is a functional interface but I see a lot of other methods in Comparator method then how is it a Single Abstract method interface?

    From Java 8 it is possible for an interface to have default methods and static methods so, in a functional interface there may be other default and static methods but there must be only one abstract method.

    A functional interface can specify Object class public methods too in addition to the abstract method. That interface will still be a valid functional interface. The public Object methods are considered implicit members of a functional interface as they are automatically implemented by an instance of functional interface.

    Read more about functional interface in Java here.

  14. What is functional interface annotation?

    Java 8 also introduces an annotation @FunctionalInterface to be used with functional interface. Annotating an interface with @FunctionalInterface indicates that an interface type declaration is intended to be a functional interface.

    Read more about functional interface annotation in Java here.

  15. Is it mandatory to mark functional interface with @FunctionalInterface annotation?

    It is not mandatory to mark functional interface with @FunctionalInterface annotation, it is more of a best practice to do that and also gives a surety that no other abstract method will be added accidentally to the functional interface. Because it will result in compiler error if any other abstract method is added to a functional interface which is annotated with @FunctionalInterface annotation.

    Read more about functional interface annotation in Java here.

  16. How can we write runnable as lambda expression?

    Refer Lambda Expression Runnable example to see how to write runnable as lambda expression.
  17. How can we write comparator as lambda expression?

    Refer Lambda Expression Comparator example to see how to write comparator as lambda expression.
  18. How can we write callable as lambda expression?

    Refer Lambda Expression Callable example to see how to write runnable as lambda expression.
  19. What is effective final in Java? What is variable capture?

    When a lambda expression uses an assigned local variable from its enclosing space there is an important restriction. A lambda expression may only use local variable whose value doesn't change. That restriction is referred as "variable capture".

    The local variables that a lambda expression may use are known as "effectively final". An effectively final variable is one whose value does not change after it is first assigned.

    Refer effectively final in Java 8 to know more about effectively final in Java.
  20. Can lambda expression throw exception? Is there any restriction in lambda expression exception handling?

    A lambda expression can throw an exception but lambda expression must throw exception compatible with those specified in the throws clause of the functional interface method.

    If a lambda expression body throws an exception, the throws clause of the functional interface method must declare the same exception type or its supertype.

    Refer Lambda expression and exception handling to know more about exception handling in lambda expressions in Java.
  21. What is method reference in Java 8?

    Lambda expressions can be used to call an existing method. Java 8 provides another feature called method reference that provides a clearer alternative to refer to the existing method by name.

    General form of Method reference - ClassName (or object)::methodName

    class name or instance is separated from the method name by a double colon. The :: is a new separator (known as double colon operator) that has been added in Java 8.

    Refer Method reference in Java 8 to know more about Method Reference in Java 8.
  22. Give an example of method reference.

    A very simple example of method reference would be how we call System.out.println.

    Suppose you are using a forEach statement to print all the elements of the list then the lambda expression for the same would be written as -

    myList.forEach(x -> System.out.println(x))
    

    Using method reference it can be written as -

    list.forEach(System.out::println);
    
    Refer Method reference in Java 8 to know more about Method Reference in Java 8.
  23. What are the types of method reference?

    There are four kinds of method references:

    Kind Example Syntax
    Reference to a static method ContainingClass::staticMethodName ClassName::methodName
    Reference to an instance method of a particular object containingObject::instanceMethodName objRef::methodName
    Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName ClassName::instanceMethodName
    Reference to a constructor ClassName::new classname::new

Related Topics

  1. Core Java basics interview questions
  2. Java String interview questions
  3. Java Exception Handling interview questions
  4. Java Multi-threading interview questions
  5. Java Collections interview questions
  6. Java Concurrency interview questions