Saturday, 30 September 2017

Java Exception Handling And Method Overriding

OOPS concepts like inheritance are an integral part of Java as it is an obejct oriented language. When a class extends a super class it can also override methods of the super class.

But what about the exceptions thrown by a super class method? Should the overridden method in the child class also need to throw the same exceptions or it can change it. To address these scenarios there are some rules laid out. In this post Exception Handling and Method Overriding in Java we'll talk about those restrictions.

Broadly there are two rules for exception handling with method overriding in Java -

  • If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception with the throws clause.
  • If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.
    1. sub-class can declare the same exception as declared in the super-class method.
    2. subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    3. subclass method can choose not to declare any exception at all.

Examples of Exception handling and method overrriding in Java

Let's see examples of the scenarios listed above to make it clear.

If superclass method has not declared any exception

If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.

Example

Java Exception handing and method overriding

It can be noted here that parent class' displayMsg() method deosn't have any throws clause whereas overridden method in the subclass declares IOException in its throws clause which is a checked exception. That's why the compile time error.

If we change the throws clause in subclass method to any unchecked exception then it won't result in compiler error.

public void displayMsg() throws ArrayIndexOutOfBoundsException{
}

If superclass method has declared an exception

  1. If superclass method has declared an exception then sub class can declare the same exception as declared in the superclass method.
    class Parent{
        public void displayMsg() throws IOException{
            System.out.println("In Parent displayMsg()");
        }
    }
    public class ExceptionOverrideDemo extends Parent{
        public void displayMsg() throws IOException{  
            System.out.println("In ExceptionOverrideDemo displayMsg()"); 
        }  
    }  
    
  2. subclass can declare the subtype exception of the exception declared in the superclass method.
    class Parent{
     public void displayMsg() throws IOException{
      System.out.println("In Parent displayMsg()");
     }
    }
    public class ExceptionOverrideDemo extends Parent{
     public void displayMsg() throws FileNotFoundException{  
      System.out.println("In ExceptionOverrideDemo displayMsg()"); 
     }  
    
    }
    

    Here in super class displayMsg() method throws IOException where as in subclass overridden displayMsg() method throws FileNotFoundException. Since FileNotFoundException is the subtype (Child class) of IOException so no problem here.

  3. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    Exception & method overriding in Java
    Here parent class method is throwing IOException whereas in the subclass overridden method is throwing Exception, it will result in compiler error as IOException is the child class of Exception class, thus Exception is up in the hierarchy.
  4. Subclass overridden method declares no exception. Subclass overridden method can choose to not throw any exception at all even if super class method throws an exception.
    class Parent{
        public void displayMsg() throws IOException{
            System.out.println("In Parent displayMsg()");
        }
    }
    public class ExceptionOverrideDemo extends Parent{
        public void displayMsg(){  
            System.out.println("In ExceptionOverrideDemo displayMsg()"); 
        }  
    
    }
    

That's all for this topic Java Exception Handling And Method Overriding. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Method Overriding in Java
  2. throw Statement in Java Exception Handling
  3. Multi-Catch Statement in Java Exception Handling
  4. Java Exception Handling Interview Questions

You may also like -

Friday, 29 September 2017

BlockingQueue in Java Concurrency

BlockingQueue, an interface is added in Java 5 with in the java.util.concurrent package which provides many other concurrent utilities like CyclicBarrier, Phaser, ConcurrentHashMap, ReentranctLock etc.

BlockingQueue in Java, as the name suggests is a queue that can block the operations. Which means BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

For that BlockingQueue interface in Java has two specific methods -

  1. put(E e) - Inserts the specified element into this queue, waiting if necessary for space to become available.
  2. take() - Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Java BlockingQueue Methods

BlockingQueue methods come in four forms -

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable
  1. Methods in first column throw exception if the operation cannot be executed immediately i.e. these methods won't block.
  2. Methods in second column return a special value (either null or false, depending on the operation) if operation cannot be performed immediately.
  3. Methods in third column will block the current thread indefinitely until the operation can succeed.
  4. Methods in fourth column block for only a given maximum time limit before giving up.

No nulls in BlockingQueue

A BlockingQueue does not accept null elements. Implementations (like LinkedBlockingQueue or ArrayBlockingQueue) throw NullPointerException on attempts to add, put or offer a null.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BQDemo {
    public static void main(String[] args) {
        BlockingQueue<String> arrayBlockingQ = new ArrayBlockingQueue<String>(2);
        try {
            arrayBlockingQ.put(null);
        } catch (InterruptedException e) {
            System.out.println("Exception occurred" + e);
        }
    }
}

Output

Exception in thread "main" java.lang.NullPointerException
 at java.util.concurrent.ArrayBlockingQueue.checkNotNull(Unknown Source)
 at java.util.concurrent.ArrayBlockingQueue.put(Unknown Source)
 at org.netjs.prgrm.BQDemo.main(BQDemo.java:10)

BlockingQueue Superinterfaces

BlockingQueue extends Collection, Queue and Iterable interfaces so it inherits all Collection and Queue methods.

As exp. add(E e), remove(Object o) from the Collection interface which are different from the other two methods put() and take() in the way that add() and remove() don't block, they throw exception if the operation cannot be executed immediately.

poll() and peek() operations from Queue interface where

  • poll() - Retrieves and removes the head of this queue, or returns null if this queue is empty.
  • peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

BlockingQueue implementations are thread-safe

BlockingQueue implementations like ArrayBlockingQueue, LinkedBlockingQueue are thread-safe. All queuing methods use internal locks or other forms of concurrency control to achieve their effects atomically.

Since BlockingQueue interface also extends Collection interface so it inherits operations from Collection interface also. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

BlockingQueue capacity

A BlockingQueue may be capacity bounded or unbounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking.

For a bounded BlockingQueue implementation we have to create the BlockingQueue with the given (fixed) capacity.

As exp. ArrayBlockingQueue for which capacity has to be specified.

BlockingQueue<String> arrayBlockingQ = new ArrayBlockingQueue<String>(2);

In case of LinkedBlockingQueue or PriorityBlockingQueue both can be bounded or unbounded.

BlockingQueue<String> linkedBlockingQ = new LinkedBlockingQueue<String>(2);
        
Queue<String> linkedBlockingQ = new LinkedBlockingQueue<String>();
So both are ok.

Note that a BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE.

BlockingQueue Usage in Java

BlockingQueue implementations are designed to be used primarily for producer-consumer queues because of the blocking methods put() and take() which facilitates inter-thread communication.

It can also be used as a bounded buffer. Let's say you have a ArrayBlockingQueue of capacity 10. So one thread can keep putting values in it and another thread can read from it once the buffer is full thus creating a bounded buffer.

At any time if all 10 slots are filled put() will block and same way for take() if there are no elements to read it will block.

BlockingQueue Java example Code

public static void main(String[] args) {
    BlockingQueue<String> arrayBlockingQ = new ArrayBlockingQueue<String>(2);
    try {
              arrayBlockingQ.put("A");
              arrayBlockingQ.put("B");
              System.out.println("------ 1 -------");
              arrayBlockingQ.forEach(a->System.out.println(a));
              arrayBlockingQ.take();
              arrayBlockingQ.put("C");
              System.out.println("------ 2 -------");
              
              arrayBlockingQ.forEach(a->System.out.println(a));
          } catch (InterruptedException e) {
              System.out.println("Exception occurred" + e);
          }
}

Output

------ 1 -------
A
B
------ 2 -------
B
C

Here it can be seen how elements are added at the end, while taking it is retrieved from the head of the queue.

Implementing classes of the BlockingQueue

Classes implementing BlockingQueue interface in Java are-

Source : https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html

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


Related Topics

  1. CopyOnWriteArrayList in Java
  2. Difference Between CountDownLatch And CyclicBarrier in Java
  3. Phaser in Java concurrency
  4. Executor And ExecutorService in Java Concurrency
  5. Java Concurrency Interview Questions

You may also like -

Thursday, 28 September 2017

Multiple Catch Blocks in Java Exception Handling

There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, multiple catch blocks can be specified where each catch clause catches a different type of exception. When an exception is thrown, every catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed.

After one of the catch statement, out of the multiple catch blocks, executes the others are bypassed and execution continues after the try-catch block.

Notice that with Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code.

Multiple catch blocks Java example

In this program there is an array with only one element which is zero. From main method when calculateValue method is called a parameter is passed which is used as an index of the array.

First time 0 is sent which will mean divide by a[0]. Since the value at that index is 0 thus it will result in divide by 0 and ArithmeticException will be thrown.

Next time 2 is sent but array has only one element so trying to access a[2] will result in ArrayIndexOutOfBoundsException.

In the code there are multiple catch blocks and both of these exceptions will be caught by separate catch blocks.

public class MultipleCatchDemo {
    private void calculateValue(int i){
        int a[] = {0};
        try{
            int b = 7/a[i];
        }catch(ArithmeticException aExp){
            aExp.printStackTrace();
        }catch(ArrayIndexOutOfBoundsException aiExp){
            aiExp.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MultipleCatchDemo mcDemo = new MultipleCatchDemo();
        mcDemo.calculateValue(0);
        mcDemo.calculateValue(2);
    }
}

Output

java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:21)
java.lang.ArrayIndexOutOfBoundsException: 2
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:22)

Restriction with Multiple catch blocks in Java

When multiple catch blocks are used in Java, it is important to follow the order where the exception sub type is caught before any of their super type. Which means a catch block that catches an exception subclass must come before the catch clause that catches an exception super class.

As example – With in the Java excpetion handling hierarchy Exception class is super class and ArithmeticException is the child class so catch block for Exception class will catch an ArithmeticException too. Thus placing the catch block for Exception class before the catch block for ArithmeticException would mean that the catch block for ArithmeticException is never reached.

Note that in Java, unreachable code is an error so this situation will result in a compiler error.

Example

In the same code as used above if one more catch block for Exception is added as the first one, that will result in compiler error.

multiple catch blocks

That's all for this topic Multiple Catch Blocks in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Best Practices For Exception Handling in Java
  2. Creating Custom Exception Class in Java
  3. throws Keyword in Java Exception Handling
  4. Try-With-Resources in Java Exception Handling

You may also like -

How to Join Lists in Java

Sometimes we do have a need to join the lists constructed through different queries or received through different sources. This post shows different ways to join lists in Java.

Though the first thing that comes to mind in this scenario is loop the second list, retrieve the elements from the second list and add them to the first list thus creating a combined list.

Some thing like this -
List<String> cityList = new ArrayList<String>();
cityList.add("Delhi");
cityList.add("Mumbai");
cityList.add("Kolkata");
List<String> anotherCityList = new ArrayList<String>();
anotherCityList.add("Hyderabad");
anotherCityList.add("Bangalore");
anotherCityList.add("Mumbai");    
for(int i = 0; i < anotherCityList.size() ; i++){
    cityList.add(anotherCityList.get(i));
}
for(String cityName : cityList){
    System.out.println("City Name " + cityName);
}

But why even write a loop and add elements one by one when List provides a method addAll to join lists in Java.

According to Java Docs

addAll method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

General form of addAll

addAll(Collection<? extends E> c)

Using Apache Commons Collections

There is another way to join lists using Apache Commons Collections. Only thing we need is to add commons-collections jar to our project. It provides a ListUtils class which has a static method union to merge two lists.

According to the description of this method -

Returns a new list containing the second list appended to the first list. The List.addAll(Collection) operation is used to append the two given lists into a new list.

General form of union method

public static java.util.List union(java.util.List list1, java.util.List list2)

Though the name "union" may suggest otherwise please note that it will retain the duplicate elements in both the lists.

Let's see some example code using the above two options to merge two (or more) lists -

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.ListUtils;

public class JoinListDemo {
    public static void main(String[] args) {
        List<String> cityList = new ArrayList<String>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Kolkata");
        List<String> anotherCityList = new ArrayList<String>();
        anotherCityList.add("Hyderabad");
        anotherCityList.add("Bangalore");
        anotherCityList.add("Mumbai");
        
        // Using ListUtils.union
        System.out.println("Using ListUtils.union");
        List<String> newCityList = ListUtils.union(cityList, anotherCityList);
        for(String cityName : newCityList){
            System.out.println("City Name " + cityName);
        }
        
        // Using addAll method, here adding with in the first list
        // we can create a new list and use addAll method to 
        // add both lists to the new List
        System.out.println("Using addAll method");
        cityList.addAll(anotherCityList);
        for(String cityName : cityList){
            System.out.println("City Name " + cityName);
        }
    }
}

Output

Using ListUtils.union
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai
Using addAll method
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

You can see that duplicates are retained when the union method is used, union is a bit misleading as generally it suggests that duplicates will be counted once.
addAll method is used to append second list to the first list, if there is a requirement that original lists should not be altered then you can create a new list and use addAll method to add both the lists to a new list.

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


Related Topics

  1. How ArrayList Works Internally in Java
  2. How LinkedList Class Works Internally in Java
  3. How and Why to Synchronize ArrayList in Java
  4. How to Remove Duplicate Elements From an ArrayList in Java
  5. How to Sort ArrayList in Java

You may also like -

Exception Propagation in Java Exception Handling

When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.

The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.

If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. This process of going through the method stack is known as Exception propagation in Java.

Exception propagation example with unchecked Exception

In this example code there are three methods method1, method2 and method3. From method1, method2 is called which in turn calls method3. In method3 there is an operation which will result in an exception. You can see how exception propagates all the way to method1 where it is eventually caught.

public class ExceptionPropagation {

 public static void main(String[] args) {
  ExceptionPropagation exObj = new ExceptionPropagation();
  exObj.method1();
  System.out.println("After handling exception...");
 }
 
 void method3(){
  System.out.println("In method3");
  // This will result in Arithmetic Exception
  // as an attempt is made to divide by zero
  int result = 7/0;  
 }
 
 // This method will forward the exception
 void method2(){
  System.out.println("In method2");
  method3();
 }
 
 // Exception will be handled here
 void method1(){
  try{
   method2();
  } catch(Exception e){
   System.out.println("Exception caught");
  }
 }
}

Output

In method2
In method3
Exception caught
After handling exception
exception propagation in Java exception handling
Searching the stack for appropriate Exception Handler

Exception propagation with checked exception

In case of checked exception compiler forces you to put try-catch block so exception has to be handled where it is thrown. If you don't want to do that then you have to declare it in throws clause. Then exception will propagate to the calling method and it should be caught there or it should be declared in throws clause of that method signature too.

public class ExceptionPropagation {

 public static void main(String[] args) {
  ExceptionPropagation exObj = new ExceptionPropagation();
  exObj.method1();
  System.out.println("After handling exception");
 }
 
 // This method declares the exception in throws clause
 void method3() throws FileNotFoundException{
  System.out.println("In method3");
  // throwing exception
  throw new FileNotFoundException();  
 }
 
 // This method also declares the exception in throws clause
 void method2() throws FileNotFoundException{
  System.out.println("In method2");
  method3();
 }
 
 // Exception will be handled here
 void method1(){
  try{
   method2();
  } catch(FileNotFoundException ex){
   System.out.println("FileNotFoundException caught");
  }
 }
}

That's all for this topic Exception Propagation in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. finally Block in Java Exception Handling
  2. Difference Between throw And throws in Java Exception Handling
  3. Try-With-Resources in Java Exception Handling
  4. Best Practices For Exception Handling in Java

You may also like -

Wednesday, 27 September 2017

finalize Method in Java

There may be a situation when an object will need to perform some action just before it is getting garbage collected.

For example if an object is holding some non-java resources like file handle then it is better to make sure that these resources are closed before an object is destroyed because simply reclaiming the memory used by an object would not guarantee that the resources it held would be released.

For that purpose Java provides a mechanism called finalization through finalize() method. In finalize method we can provide the actions to release the resources before the object is destroyed.

When is finalize() method called in Java

As we know that in Java object memory deallocation happens automatically through garbage collection. In Java, garbage collector is run by the run time environment periodically and it looks for the objects for which there are no existing references. finalize method for an object is executed just before it is garbage collected. But here lies the caveat According to Java language specification - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.6 The Java programming language does not specify how soon a finalizer will be invoked that's one reason why we should not rely solely on finalize() method to release resources.

According to Joshua Bloch in his book Effective Java, Item 7: Avoid Finalizers
"The promptness with which finalizers are executed is primarily a function of the garbage collection algorithm, which varies widely from JVM implementation to JVM implementation. The behavior of a program that depends on the promptness of finalizer execution may likewise vary. It is entirely possible that such a program will run perfectly on the JVM on which you test it and then fail miserably on the JVM favored by your most important customer."

General form of finalize method in Java

finalize method is provided as a protected method in the Object class.

protected void finalize() throws Throwable

Just as a reminder the protected access modifier means - Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Since all the classes have Object class as the super class either directly or indirectly so this method would be accessible to each and every class anyway so it makes sense to keep the access as protected.

How to use finalize method in Java

The finalize method of class Object performs no special action; it simply returns normally. Any class which needs some functionality to be provided in finalize() method has to override this definition and provide the functionality.

According to Java docs - The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded.

How to properly write a finalize() method

Like constructor chaining in Java there is no finalizer chaining so super class finalize method would not be called automatically. As example If there is a class A which provides a finalize method and Class A is extended by class B. Then only Class B's finalize method will be called if child class B overrides the finalize method. Parent Class A's finalize method would not be called automatically. It has to be explicitly called using super. In that case class B's finalize method will look like -

protected void finalize() throws Throwable {
     try {
         // clean up
     } finally {
         super.finalize(); // call parent class’ finalize
     }
}

Java example code for finalize method

Here is a simple example where I have created an object then setting that object reference as null. Also called System.gc() explicitly to run garbage collector. That should mean a call to finalize() method before the object is garbage collected. Note you may not get the output in some of the runs as System.gc() is more of a suggestion to the Java virtual machine to reclaim memory from unused objects, it may not run as soon as System.gc() is called and the program may terminate without calling the finalize method.

public class FinalizeDemo {
    int i;
    FinalizeDemo(int num){
        this.i = num;
    }
    public static void main(String[] args) {
        // creating object
        FinalizeDemo finalizeDemo = new FinalizeDemo(10);
        Temp temp = new Temp();
        // setting object reference as null so it is 
        // eligible for garabge collection
        finalizeDemo = null;
        temp.doCalcualtion();
        // setting object reference as null so it is 
        // eligible for garabge collection
        temp = null;
        // Calling System.gc() to run garbage collector
        System.gc();        
    }
    
    @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("finalize method called for FinalizeDemo");
        }finally{        
            super.finalize();
        }
    } 
}

class Temp{    
    public void doCalcualtion(){
        int i = 5;
        System.out.println("value of i is " + i);
    }
    @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("finalize method called for Temp");
        }finally{
            super.finalize();
        }
    }
}

Output

value of i is 5
finalize method called for Temp
finalize method called for FinalizeDemo

Though I have used System.gc here to some how make sure that finalize() method is indeed called but don't rely on it. To quote Joshua Bloch again "Don't be seduced by the methods System.gc and System.runFinalization. They may increase the odds of finalizers getting executed, but they don't guarantee it. The only methods that claim to guarantee finalization are System.runFinalizersOnExit and its evil twin, Runtime.runFinalizersOnExit. These methods are fatally flawed and have been deprecated."

When can we use finalize method

Though there are other better alternatives to clean up resources like a finally block or try-with-resources(ARM) available from Java 7. But to make sure, just as an extra safety measure, that resources are indeed closed before the object is destroyed finalize() method may be used. But be forewarned it does comes with a hit on performance.

Finalize method and exception handling

Any exception thrown by the finalize method while finalize method is executing causes the finalization of this object to be halted, but is otherwise ignored.

Points to Note

  1. Every class in Java inherits the finalize() method from java.lang.Object.
  2. The finalize method is called by the garbage collector when it determines no more references to the object exist
  3. The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.
  4. If overridding finalize() it is a good programming practice to use a try-catch-finally statement and to always call super.finalize() as there is no concept of finalizer chaining.
  5. The finalize method is never invoked more than once by a Java virtual machine for any given object.
  6. finalize method is deperecated from Java 9.

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


Related Topics

  1. final Vs finally Vs finalize in Java
  2. Constructor chaining in Java
  3. Association, Aggregation And Composition in Java
  4. super in Java
  5. Core Java Basics Interview Questions

You may also like -

>>>Go to Java Basics 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 and read it from there. A properties store data in a form of key/value pair.

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

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 in Java 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. That is another way to read properties file in Java.

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