Saturday, February 6, 2021

Effectively Final in Java 8

In Java 8 with the addition of lambda expressions, a new concept effectively final variable has been added, which closely relates to lambda expressions. Prior to Java 8, inner classes had an important restriction that inner classes could only use variable from enclosing scope if it's final, that restriction hs been eased starting Java 8.

Let's see an example where we have an interface IFunc, with one method display(). That interface is implemented as an anonymous inner class in Test class. In the implementation of display() method it tries to access the variable i from the enclosing scope which is not declared as final variable. Note that this code is compiled and executed using Java 6.

interface IFunc{
  void display();
}

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  int i =7;
  // Anonymous inner class
  new IFunc() {
   @Override
   public void display() {
    System.out.println("Value is " + i); 
   }
  };
 }
}

There will be a compile time error-

Cannot refer to a non-final variable i inside an inner class defined in a different method

Friday, February 5, 2021

forEach Statement in Java 8

Undoubtedly, the most important addition in Java 8 are lambda expressions and stream API. Along with these features came the new forEach statement in Java to loop the collections like List and Set. Of course you can also use it with Map but with a little difference as Map doesn’t implement either the Iterable or the Collection interface.

Using forEach() statement in Java

  1. Iterable interface provides forEach method as an interface default method
    default void forEach(Consumer<? super T> action)
    

    Where Consumer is the functional interface which implements the action to be performed on each iteration. If you see the default implementation of forEach in Iterable interface it is like-

    for (T t : this) {
     action.accept(t);
    }
    

    Collections like list and set implement Iterable interface so they can use forEach() directly. As example if there is a list called numList and you want to iterate it using forEach() method it can be done like-

    numList.forEach(System.out::println);
    

    Here note that method reference is used to call println method.

Thursday, February 4, 2021

How to Remove Elements From an Array Java Program

Writing a Java program to remove element from an array may look like a simple task but it comes with its own set of problems. Those problems stem from the fact that array in Java is fixed in length. Which means you can't just remove an element from the given index in an array, you will need to shift all the elements that are after the element that has to be removed, to the left to fill the gap left by the removed element.

Once the element are shifted to fill the gap that leaves space at the end of the array (remember array size is fixed). Array size will not reduce after removing the element and the element that is at the end will be repeated to fill the empty space.

Let's try to clarify it with an example-

Here the array removal is done without using any third party tool (like Apache common utils) or any data structure provided by the Java language (Like Collection classes).

So the steps followed to remove element from an array are-

  1. Ask the user to enter the element to be removed.
  2. Search in the array for the given element.
  3. If found shift all the element after that index to the left by one element. As example if element to be deleted is at index i then remove all the elements from index i+1 to array.length by one element which means element at i+1 will come at index i.

Java program to remove element from an array

 
import java.util.Scanner;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
    
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        // shifting elements
        for(int j = i; j < intArr.length - 1; j++){
            intArr[j] = intArr[j+1];
        }
        break;
      }
    }
      
    System.out.println("Elements -- " );
    for(int i = 0; i < intArr.length; i++){
      System.out.print(" " + intArr[i]);
    }                
  }
}

Output

Enter Element to be deleted : 5
Elements -- 
 1 2 12 7 3 8 8

If you notice last element 8 is repeated to fill the space that is left after shifting the elements.

Now when you have basic idea about the scenarios that you need to take care of while removing element from an array let's see what all alternatives are there to do that.


Using new array

When you remove an element from an array, you can fill the empty space with 0, space or null depending on whether it is a primitive array, string array or an Object array.

Other alternative is to create a new array and copy the elements in that array. New array should have size of old array’s size – 1.

Let’s see an example where new array is used-

 
import java.util.Scanner;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
    int[] newArr = null;
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
        
    /*for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){          
        for(int j = i; j < intArr.length - 1; j++){
          intArr[j] = intArr[j+1];
        }
        break;
      }
    }*/
        
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        newArr = new int[intArr.length - 1];
        for(int index = 0; index < i; index++){
          newArr[index] = intArr[index];
        }
        for(int j = i; j < intArr.length - 1; j++){
          newArr[j] = intArr[j+1];
        }
        break;
      }
    }
    System.out.println("Elements -- " );      
    for(int i = 0; i < newArr.length; i++){
      System.out.print(" " + newArr[i]);
    }                
  }
}

Output

Enter Element to be deleted : 
5
Elements -- 
 1 2 12 7 3 8

Enter Element to be deleted : 8
Elements -- 
 1 2 5 12 7 3

With copying the element to the new array problem of empty space is solved.

Using ArrayUtils to remove element from an array

If you can use Apache commons in your application then there is a utility class ArrayUtils that can be used to remove elements from an array.

 
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        // Using ArrayUtils
        intArr = ArrayUtils.remove(intArr, i);
        break;
      }
    }
        
    System.out.println("Elements -- " );
    for(int i = 0; i < intArr.length; i++){
      System.out.print(" " + intArr[i]);
    }
  }
}

Output

Enter Element to be deleted : 2
Elements -- 
 1 5 12 7 3 8

Using System.arraycopy() method to remove element from an array

Description of the System.arraycopy method

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) - Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

If you use the same array as source and destination you will have the same issue of repeating element as discussed in the first program as the array length is fixed. In the example code new array is used as destination.

 
import java.util.Arrays;
import java.util.Scanner;

public class ElemRemoval {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        removeElement(intArr, i);
        break;
      }
    }       
  }
    
  public static void removeElement( int [] arr, int index ){
    // Destination array
    int[] arrOut = new int[arr.length - 1];
    int remainingElements = arr.length - ( index + 1 );
    // copying elements that come before the index that has to be removed
    System.arraycopy(arr, 0, arrOut, 0, index);
    // copying elements that come after the index that has to be removed
    System.arraycopy(arr, index + 1, arrOut, index, remainingElements);
    System.out.println("Elements -- "  + Arrays.toString(arrOut));
  }
}

Output

Enter Element to be deleted : 5
Elements -- [1, 2, 12, 7, 3, 8]

Using ArrayList to remove element from an array

If you want to remove element from an array using Collection API provided by the Java language then you can convert array to an ArrayList and then remove element from the ArrayList. Shuffling and all would be taken care of by the ArrayList itself. Once the element is removed you can again convert the ArrayList to an array.

 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Integer[] intArr = {1, 2, 5, 12, 7, 3, 8};            
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
        
    System.out.println("Original Array " + Arrays.toString(intArr));        
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        intArr = removeElementUsingCollection(intArr, i);
        break;
      }
    }
    System.out.println("Array after removal of Element -- " );
    for(int i = 0; i < intArr.length; i++){
      System.out.print(" " + intArr[i]);
    }
        
    public static Integer[] removeElementUsingCollection( Integer[] arr, int index ){
      List<Integer> tempList = new ArrayList<Integer>(Arrays.asList(arr));
      tempList.remove(index);
      return tempList.toArray(new Integer[0]);
    }
}

Output

Enter Element to be deleted : 2
Original Array [1, 2, 5, 12, 7, 3, 8]
Array after removal of Element -- 
 1 5 12 7 3 8

That's all for this topic How to Remove Elements From an Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Find Duplicate Elements in an Array Java Program
  2. Remove Duplicate Elements From an Array in Java
  3. Matrix Subtraction Java Program
  4. Difference Between Array And ArrayList in Java
  5. How ArrayList Works Internally in Java

You may also like-

  1. Split a String Java Program
  2. Format Date in Java Using SimpleDateFormat
  3. How to Create PDF From XML Using Apache FOP
  4. How to Create Deadlock in Java
  5. Difference Between equals() Method And equality Operator == in Java
  6. Arithmetic and Unary Operators in Java
  7. Java Object Cloning - clone() Method
  8. Java Nested Class And Inner Class

Wednesday, February 3, 2021

Spring MVC Java Configuration Example

In the post Spring MVC Example Using XML Configuration and Annotations we saw a Spring MVC example with XML configuration, here we’ll create the same MVC application using Spring MVC Java configuration.

In this Spring MVC example using Java configuration we’ll create two views (JSPs), that will give you a better idea about the controller mapping, how Java model bean is bound to a web form and the Spring web MVC flow ) (request - Servlet – Controller – Model – View).

Technologies used

Following is the list of tools used for the Spring web MVC example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. Tomcat server V 9.0.10
  4. Eclipse IDE

Spring MVC Exception Handling Tutorial

Exception handling is an important part of any application and Spring MVC applications are no exception. Spring MVC exception handling set up is important so that the user doesn’t suddenly see an exception trace from the server side. By using Spring MVC exception handling you can configure error pages that are displayed with the proper information to the user in case any exception occurs.

This post gives an overview of Spring MVC exception handling, for an example of Spring MVC exception handling refer this post- Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice


HandlerExceptionResolver in Spring MVC exception handling

HandlerExceptionResolver is an interface in Spring framework which is to be implemented by objects that can resolve exceptions thrown during handler mapping or execution.

Spring framework delegates the exception handling to a chain of HandlerExceptionResolver beans where you can try to resolve the exception, prepare an error response (HTML error page, error status).

Tuesday, February 2, 2021

Nonlocal Keyword in Python With Examples

In this post we’ll see what is nonlocal keyword in Python and how to use it.

To understand nonlocal keyword better an understanding of local, global and nonlocal variables is required, as a requisite please go through this post- Local, Nonlocal And Global Variables in Python

Python nonlocal keyword

The nonlocal keyword causes the variable to refer to previously bound variables in the nearest enclosing scope excluding globals. Note that nonlocal keyword is added in Python 3.

Python nonlocal keyword is used with variables in nested functions to bind the variable defined in outer function, by making variable nonlocal it can be accessed in nested function.

Let’s try to understand it with some examples.

Global Keyword in Python With Examples

In this post we’ll see what is global keyword in Python and how to use it.

To understand global keyword better an understanding of local, global and nonlocal variables is required, as a requisite please go through this post- Local, Nonlocal And Global Variables in Python

Some important points that you should know about local and global variables in Python-

  1. Variables that are declared outside a function are known as global variables in Python. There is no need to qualify these variables with global keyword such variables have global scope by default.
  2. When a variable is declared inside a function then it is a local variable. A local variable’s scope is limited with in the function where it is created.
  3. If you declare a variable inside a function having the same name as the global variable then with in the scope of the method local variable overshadows the global variable.