Monday, February 22, 2021

Fix Cannot make a static Reference to The Non-static Method Error

When a person moves beyond the "Hello world" program where everything is with in a main method and writes a program with more than one method, one error he or she surely will encounter is "Cannot make a static reference to the non-static method or a non-static field".

Not only beginners even experienced programmers unknowingly keep making the mistake of trying to access a non-static method or field from a static context and get a reminder from compiler that they have forgotten the basics! At least I do that many times when I write a program to test something and from main method (which is static) I try to access some non-static method and get the error "Cannot make a static reference to the non-static method or a non-static field".

Sunday, February 21, 2021

Difference Between Encapsulation And Abstraction in Java

Encapsulation and Abstraction are two of the fundamental OOP concepts other two being Polymorphism and Inheritance. Some times people do get confused between encapsulation and abstraction as both are used to "hide something". So in this post let's try to see the difference between encapsulation and abstraction in Java.

First let's try to define these two OOPS concepts encapsulation and abstraction to get a better idea-
  • Encapsulation- Encapsulation means keeping together the implementation (code) and the data it manipulates (variables). Having proper encapsulation ensures that the code and data both are safe from misuse by outside entity. So, in a way Encapsulation is more about data hiding.

    It is a Java class which is the foundation of encapsulation in Java.

    Following image shows the concept of encapsulation. Fields and methods are encapsulated with in the class and the methods of the class can access and manipulate fields. Outside entity can't access fields directly but need to call methods which in turn can access data.

Saturday, February 20, 2021

How to Create PDF in Java Using OpenPDF

In the post Creating PDF in Java Using iText we have already seen how to use iText library to generate a PDF in Java. Itext is one of the best way to generate PDF in Java, has many features but there is one problem; it is AGPL licensed which means you must distribute all source code, including your own product and web-based applications. Many times the idea to use iText is shot down by the clients because of this reason. So, in this post we’ll see one alternative of using iText for generating PDF in Java. That option is OpenPDF for generating PDF.

OpenPDF for creating PDF in Java

OpenPDF is a free Java library for creating and editing PDF files with a LGPL and MPL open source license. OpenPDF is based on a fork of iText. In fact you will find the code for generating PDF using OpenPDF quite similar to iText API till version 5. OpenPDF is actively maintained and a very good option for creating PDF in Java.

Maven dependecy

For using OpenPDF library you must add the following dependencies to your pom.xml file.

For Java 8 onward-

<dependency>
  <groupId>com.github.librepdf</groupId>
  <artifactId>openpdf</artifactId>
  <version>1.2.4</version>
</dependency>
Java 7 compatible branch-
<dependency>
  <groupId>com.github.librepdf</groupId>
  <artifactId>openpdf</artifactId>
  <version>1.2.3.java7</version>
</dependency>

Friday, February 19, 2021

Convert HTML to PDF in Java + Openhtmltopdf and PDFBox

In this tutorial we’ll see how to convert HTML to PDF in Java using Openhtmltopdf and PDFBox.

Check another option to convert HTMP to PDF in this post- HTML to PDF in Java + Flying Saucer and OpenPDF

How does it work

Let’s first understand what do the libraries mentioned here do-

  1. Open HTML to PDF is a pure-Java library for rendering arbitrary well-formed XML/XHTML (and even HTML5) using CSS 2.1 for layout and formatting, outputting to PDF or images.
  2. jsoup library is used for parsing HTML using the best of HTML5 DOM methods and CSS selectors. That gives you a well formed HTML (XHTML) that can be passed to the Openhtmltopdf.
  3. Openhtmltopdf uses the open-source PDFBOX as PDF library which generates PDF document from the rendered representation of the XHTML returned by Openhtmltopdf.

Thursday, February 18, 2021

Creating PDF in Java Using Apache PDFBox

In the post Creating PDF in Java Using iText we have already seen how to use iText library to generate a PDF in Java, we have already seen one alternative of iText which is OpenPDF for generating PDF. In this tutorial we’ll learn about another option for generating PDF in Java using Apache PDFBox.

PDFBox for creating PDF in Java

The Apache PDFBox library (https://pdfbox.apache.org/) is an open source tool written in Java for working with PDF documents. Using PDFBox you can create new PDF documents, manipulate existing documents and extract content from PDF documents. Apache PDFBox also includes several command-line utilities. Apache PDFBox is published under the Apache License v2.0.

Wednesday, February 17, 2021

Java Program to Find First Non-Repeated Character in a Given String

A very popular interview question for String is to write a Java program to find first non-repeated character in a given String. For example if given string is “always” then first non-repeated character is ‘l’ as character ‘a’ is repeated. Same way if String is “net” then first non-repeated character is ‘n’.

There are many ways to solve this problem, in this post I am giving 4 solutions to find first non-repeated character in a given String using Java.

  1. If you are asked not to use any inbuilt API or data structure.
  2. Solution using LinkedHashMap.
  3. Solution using indexof() method of the String class.
  4. Java 8 onward you can also use Stream API

Wednesday, February 10, 2021

HTML to PDF in Java + Flying Saucer and OpenPDF

In your application you may come across a scenario to convert the HTML to PDF on the fly. In this tutorial we’ll see how to convert HTML to PDF in Java using Flying Saucer and OpenPDF.

Check another option to convert HTMP to PDF in this post- Convert HTML to PDF in Java + Openhtmltopdf and PDFBox

How does it work

Let’s first understand which library is used for what purpose-

  1. Flying Saucer is an XML/CSS renderer, which means it takes XML files as input, applies formatting and styling using CSS, and generates a rendered representation of that XML as output. As an input you can pass an XHTML file which is an XML document format that standardizes HTML.
  2. jsoup library is used for parsing HTML using the best of HTML5 DOM methods and CSS selectors. That gives you a well formed HTML that can be passed to the Flying Saucer.
  3. Flying Saucer renders the input XHTML that still needs to be converted to PDF for that OpenPDF is used. OpenPDF is a free Java library for creating and editing PDF files with a LGPL and MPL open source license. OpenPDF is based on a fork of iText.

Tuesday, February 9, 2021

Invoke Method at Runtime Using Java Reflection API

In this post we’ll see how to invoke a method at runtime using Java reflection API. You can even call a private method using reflection.

How to get the method instance

In order to invoke a method first thing you need to do is to get an instance of the Method. Using the class object (instance of the class in which method is defined) you can invoke one of the following methods to get an instance of a single method or get all the methods of the class in an array.

  • getMethod(String name, Class<?>... parameterTypes)- Using getMethod() you can get a Method object for the specified public member method of the class (instance or static). As method arguments pass the method name and the type of the method parameters.
  • getMethods()- This method returns an array containing Method objects for all the public methods of the class even the inherited ones.
  • getDeclaredMethod(String name, Class<?>... parameterTypes)- Using getDeclaredMethod() you can get a Method object for the specified method of the class (having any access modifier public, private, protected, default).
  • getDeclaredMethods()- This method returns an array containing Method objects for all the declared methods of the class including public, protected, default (package) access, and private methods, but excluding inherited methods.

Monday, February 8, 2021

Angular + Spring Boot JWT Authentication Example

In this tutorial we’ll create a full login example with authentication using Angular, Spring Boot, Spring Security, JWT authentication.

In the back end Spring Boot is used to create REST APIs, Spring security is used for authentication and authorization, token based authentication is done using JWT, Spring Data JPA is used for DB operations.

In the front end Angular is used to create forms, provide routing and Bootstrap is used for styling.

Back end Spring Boot service

In the backend we have a Spring Boot application that uses Spring Security and JWT token based authentication to bring authentication and authorization to the exposed REST APIs. DB used is MySQL.

To get more details and code for the Spring Boot + Spring Security JWT Authentication Example refer this post- https://www.netjstech.com/2021/02/spring-boot-spring-security-jwt-authentication.html

Only change that is required in the Spring boot application is to add @CrossOrigin annotation in the Controller class to enable cross-origin resource sharing (CORS). If you won't use this annotation cross browser HTTP request won't be allowed and the Spring Boot application won't accept any request coming from http://localhost:4200

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.