Tuesday, April 30, 2024

Pre-defined Functional Interfaces in Java

We saw in the post Functional Interfaces in Java how you can create your own functional interface and also annotate it using @FunctionalInterface Annotation. Though it is not always required that you have to create your own functional interface for each scenario, Java has introduced a new package java.util.function that defines many general purpose pre-defined functional interfaces used by many Java libraries like Collection framework, Java Stream API and used by user code as well. In this post we’ll go through these built-in functional interfaces in Java so you have a good idea which functional interface to use in which context while using with Lambda expressions in Java.


Pre-defined functional interfaces categorization

Functional interfaces defined in java.util.function package can be categorized into five types-

  1. Consumer- Consumes the passed argument and no value is returned.
  2. Supplier- Takes no argument and supplies a result.
  3. Function- Takes argument and returns a result.
  4. Predicate- Takes argument and returns a boolean result (true or false).
  5. Operators- Functional interfaces categorized under Operator are specialized Function where the passed argument and result are of the same type.

Consumer functional interface

Consumer<T> represents a function that accepts a single input argument and returns no result. Consumer functional interface definition is as given below consisting of an abstract method accept() and a default method andThen()-

@FunctionalInterface
public interface Consumer<T> {
  void accept(T t);
  default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
  }
}

Following pre-defined Consumer functional interfaces are categorized as Consumer as all of these interfaces have the same behavior of consuming the passed value(s) and returning no result. You can use any of these based on number of arguments or data type.

  • BiConsumer<T,U>- Represents an operation that accepts two input arguments and returns no result.
  • DoubleConsumer- Represents an operation that accepts a single double-valued argument and returns no result.
  • IntConsumer- Represents an operation that accepts a single int-valued argument and returns no result.
  • LongConsumer- Represents an operation that accepts a single long-valued argument and returns no result.
  • ObjDoubleConsumer<T>- Represents an operation that accepts an object-valued and a double-valued argument, and returns no result.
  • ObjIntConsumer<T>- Represents an operation that accepts an object-valued and a int-valued argument, and returns no result.
  • ObjLongConsumer<T>- Represents an operation that accepts an object-valued and a long-valued argument, and returns no result.

Consumer functional interface Java example

In the example elements of List are displayed by using an implementation of Consumer functional interface.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerExample {
  public static void main(String[] args) {
    Consumer<String> consumer = s -> System.out.println(s);
    List<String> alphaList = Arrays.asList("A", "B", "C", "D");
    for(String str : alphaList) {
      // functional interface accept() method called
      consumer.accept(str);
    }
  }
}

Output

A
B
C
D

Supplier functional interface

Supplier<T> represents a function that doesn't take argument and supplies a result. Supplier functional interface definition is as given below consisting of an abstract method get()-

@FunctionalInterface
public interface Supplier<T> {
  T get();
}

Following pre-defined Supplier functional interfaces are categorized as Supplier as all of these interfaces have the same behavior of supplying a result.

  • BooleanSupplier- Represents a supplier of boolean-valued results.
  • DoubleSupplier- Represents a supplier of double-valued results.
  • IntSupplier- Represents a supplier of int-valued results.
  • LongSupplier- Represents a supplier of long-valued results.

Supplier functional interface Java example

In the example Supplier functional interface is implemented as a lambda expression to supply current date and time.

import java.time.LocalDateTime;
import java.util.function.Supplier;

public class SupplierExample {
  public static void main(String[] args) {
    Supplier<LocalDateTime> currDateTime = () -> LocalDateTime.now();
    System.out.println(currDateTime.get());
  }
}

Function functional interface

Function<T,R> represents a function that accepts one argument and produces a result. Function functional interface definition is as given below consisting of an abstract method apply(), two default methods compose(), andThen() and a static method identity().

@FunctionalInterface
public interface Function<T, R> {

  R apply(T t);

  default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
    Objects.requireNonNull(before);
    return (V v) -> apply(before.apply(v));
  }

  default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
    Objects.requireNonNull(after);
    return (T t) -> after.apply(apply(t));
  }
  static <T> Function<T, T> identity() {
    return t -> t;
  }
}

Following pre-defined Function functional interfaces are categorized as Function as all of these interfaces have the same behavior of accepting argument(s) and producing a result.

  • BiFunction<T,U,R>- Represents a function that accepts two arguments and produces a result.
  • DoubleFunction<R>- Represents a function that accepts a double-valued argument and produces a result.
  • DoubleToIntFunction- Represents a function that accepts a double-valued argument and produces an int-valued result.
  • DoubleToLongFunction- Represents a function that accepts a double-valued argument and produces a long-valued result.
  • IntFunction<R>- Represents a function that accepts an int-valued argument and produces a result.
  • IntToDoubleFunction- Represents a function that accepts an int-valued argument and produces a double-valued result.
  • IntToLongFunction- Represents a function that accepts an int-valued argument and produces a long-valued result.
  • LongFunction<R>- Represents a function that accepts a long-valued argument and produces a result.
  • LongToDoubleFunction- Represents a function that accepts a long-valued argument and produces a double-valued result.
  • LongToIntFunction- Represents a function that accepts a long-valued argument and produces an int-valued result.
  • ToDoubleBiFunction<T,U>- Represents a function that accepts two arguments and produces a double-valued result.
  • ToDoubleFunction<T>- Represents a function that produces a double-valued result.
  • ToIntBiFunction<T,U>- Represents a function that accepts two arguments and produces an int-valued result.
  • ToIntFunction<T>- Represents a function that produces an int-valued result.
  • ToLongBiFunction<T,U>- Represents a function that accepts two arguments and produces a long-valued result.
  • ToLongFunction<T>- Represents a function that produces a long-valued result.

Function functional interface Java example

In the example a Function interface is implemented to return the length of the passed String.

import java.util.function.Function;

public class FunctionExample {
  public static void main(String[] args) {
    Function<String, Integer> function = (s) -> s.length();
    System.out.println("Length of String- " + function.apply("Interface"));
  }
}

Output

Length of String- 9

Predicate functional interface

Predicate<T> represents a function that accepts one argument and produces a boolean result. Abstract method in the Predicate functional interface is boolean test(T t).

Following pre-defined Predicate functional interfaces are categorized as Predicate as all of these interfaces have the same behavior of accepting argument(s) and producing a boolean result.

  • BiPredicate<T,U>- Represents a predicate (boolean-valued function) of two arguments.
  • DoublePredicate- Represents a predicate (boolean-valued function) of one double-valued argument.
  • IntPredicate- Represents a predicate (boolean-valued function) of one int-valued argument.
  • LongPredicate- Represents a predicate (boolean-valued function) of one long-valued argument.

Predicate functional interface Java Example

In the example a number is passed and true is returned if number is even otherwise odd is retuned.

import java.util.function.Predicate;

public class PredicateExample {
  public static void main(String[] args) {
    Predicate<Integer> predicate = (n) -> n%2 == 0;
    boolean val = predicate.test(6);
    System.out.println("Is Even- " + val);    
    System.out.println("Is Even- " + predicate.test(11));
  }
}

Output

Is Even- true
Is Even- false

Operator functional interfaces

Operator functional interfaces are specialized Function interfaces that always return the value of same type as the passed arguments. Operator functional interfaces extend their Function interface counterpart like UnaryOperator extends Function and BinaryOperator extends BiFunction.

Following pre-defined Operator functional interfaces are there that can be used in place of Function interfaces if returned value is same as the type of the passed argument(s).

  • BinaryOperator<T>- Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
  • DoubleBinaryOperator- Represents an operation upon two double-valued operands and producing a double-valued result.
  • DoubleUnaryOperator- Represents an operation on a single double-valued operand that produces a double-valued result.
  • IntBinaryOperator- Represents an operation upon two int-valued operands and producing an int-valued result.
  • IntUnaryOperator- Represents an operation on a single int-valued operand that produces an int-valued result.
  • LongBinaryOperator- Represents an operation upon two long-valued operands and producing a long-valued result.
  • LongUnaryOperator- Represents an operation on a single long-valued operand that produces a long-valued result.
  • UnaryOperator<T>- Represents an operation on a single operand that produces a result of the same type as its operand.

UnaryOperator functional interface Java example

In the example UnaryOperator is implemented to return the square of the passed integer.

import java.util.function.UnaryOperator;

public class UnaryOperatorExample {
  public static void main(String[] args) {
    UnaryOperator<Integer> unaryOperator = (n) -> n*n;
    System.out.println("4 squared is- " + unaryOperator.apply(4));
    System.out.println("7 squared is- " + unaryOperator.apply(7));
  }
}

Output

4 squared is- 16
7 squared is- 49

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


Related Topics

  1. Exception Handling in Java Lambda Expressions
  2. Method Reference in Java
  3. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  4. Java Stream API Tutorial
  5. Java Lambda Expressions Interview Questions And Answers

You may also like-

  1. Java Stream flatMap() Method
  2. Java Lambda Expression Callable Example
  3. Invoke Method at Runtime Using Java Reflection API
  4. LinkedHashMap in Java With Examples
  5. java.lang.ClassCastException - Resolving ClassCastException in Java
  6. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  7. BeanFactoryAware Interface in Spring Framework
  8. Angular Two-Way Data Binding With Examples

Monday, April 29, 2024

Checkbox in Angular Form Example

In this post we’ll see how to use check boxes in Angular form. We’ll see examples of adding check boxes to both template-driven and reactive form in Angular.

Checkbox in Reactive form Angular example

In this Angular Reactive form example we’ll have a form with two input fields for name and date (with a date picker for picking date) and a group of check boxes to select favorite exercises.

Friday, April 26, 2024

Printing Numbers in Sequence Using Threads Java Program

This post shows how you can print numbers in sequence using three threads in Java. If there are three threads thread1, thread2 and thread3 then numbers should be printed alternatively by these threads like this.

thread1 - 1
thread2 - 2
thread3 – 3
thread1 - 4
thread2 - 5
thread3 – 6
...
...
...

Print numbers in sequence using three threads in Java

While printing numbers in sequence using threads trick is to use modulo division to check which thread can print the number and which threads are to be blocked waiting.

Each thread is assigned one of the numbers 0, 1 and 2. Each number is divided by 3 (number of threads), remainder will be any one of these numbers 0, 1 or 2. That is what is checked; if (remainder = number assigned to thread) only then thread can work otherwise it goes into waiting state.

class SharedPrinter{
  int number = 1;
  int numOfThreads;
  int numInSequence;
  SharedPrinter(int numInSequence, int numOfThreads){
    this.numInSequence = numInSequence;
    this.numOfThreads = numOfThreads;
  }
  public void printNum(int result){
    synchronized(this) {
      while (number < numInSequence - 1) {
        while(number % numOfThreads != result){
          try {
            this.wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        System.out.println(Thread.currentThread().getName() + " - " + number++);
        this.notifyAll();
      }
    }
  }
}
class SeqRunnable implements Runnable{
  SharedPrinter sp;
  int result;
  static Object sharedObj = new Object();
  SeqRunnable(SharedPrinter sp, int result){
    this.sp = sp;
    this.result = result;
  }
  @Override
  public void run() {
    sp.printNum(result);
  }
}
public class SeqNumber {
  final static int NUMBERS_IN_SEQUENCE = 10;
  final static int NUMBER_OF_THREADS = 3;
  public static void main(String[] args) {
    // Shared object
    SharedPrinter sp = new SharedPrinter(NUMBERS_IN_SEQUENCE, NUMBER_OF_THREADS);
    // Creating 3 threads
    Thread t1 = new Thread(new SeqRunnable(sp, 1), "Thread1");
    Thread t2 = new Thread(new SeqRunnable(sp, 2), "Thread2");
    Thread t3 = new Thread(new SeqRunnable(sp, 0), "Thread3");

    t1.start();
    t2.start();
    t3.start();
  }
}

Output

Thread1 - 1
Thread2 - 2
Thread3 - 3
Thread1 - 4
Thread2 - 5
Thread3 - 6
Thread1 - 7
Thread2 - 8
Thread3 - 9
Thread1 - 10

That's all for this topic Printing Numbers in Sequence Using Threads 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. How to Run Threads in Sequence in Java
  2. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  3. Producer-Consumer Java Program Using ArrayBlockingQueue
  4. How to Create Deadlock in Java
  5. Race condition in Java multi-threading

You may also like-

  1. Converting String to Enum Type in Java
  2. Connection Pooling Using C3P0 in Java
  3. Java Program to Find First Non-Repeated Character in a Given String
  4. How to Convert String to Date in Java
  5. Java Multithreading Interview Questions And Answers
  6. How and Why to Synchronize ArrayList in Java
  7. BigDecimal in Java With Examples
  8. Introduction to Hadoop Framework

Thursday, April 25, 2024

FormGroup in Angular With Examples

Using FormGroup in Angular forms you can group FormControl instances and track the value and validity state of those instances as a group rather than for each individual FormControl instance. In this post we'll see example of using FormGroup with Angular template-driven form as well as with Reactive form.


Wednesday, April 24, 2024

How to Setup a Node.js Project

In this article we'll see how to set up a Node.js project with a package.json file so that you can easily install other dependencies using NPM. This also shows how you'll use NodeJS' module pattern to create projects which is a collection of many files and packages.

Prerequisite to creating a project is that Node.js is installed in your system (which also install NPM) and you have an IDE like Visual Studio Code.

Check this post How to Install Node.js and NPM in Windows to see how to install Node.js

Setting up NodeJS project

To start with, let's create a new directory and you can name it nodeapp or any other meaningful name. If you open this directory in Visual Studio Code as expected you won't have anything with in it!

In order to make it a Node project you'll have to use the command npm init which creates a package.json file by asking you few questions. If you want to bypass these questions and answer "yes" by default for all the questions you can use npm init -y command instead.

Go to the directory you have just created and run the npm init command to initialize your Node project.

nodeapp>npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodeapp)
version: (1.0.0)
description: A node project
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\NETJS\NetJS_2017\NodeJS\nodeapp\package.json:

{
  "name": "nodeapp",
  "version": "1.0.0",
  "description": "A node project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes)

As you can see for most of the questions asked, I have just pressed enter, only entry is for the "description". You can always go later to the created package.json file and edit it so no worries.

If you go to Visual Studio code now you should see the generated package.json file.

Setting NodeJS project

Since the starting file is named as "index.js" so let's create such a file in our "nodeapp" project.

index.js

console.log("It's a new Node project");

Running this JavaScript file should output the content as expected.

node index.js

It's a new Node project

Now let's change our package.json a little and add a kay-value entry in the "scripts" section.

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },

This instructs Node to use start script as the executor of the command given as value "node index.js". Now you can use npm start command to start your project.

npm start

> nodeapp@1.0.0 start
> node index.js
It's a new Node project

Importing packages in NodeJS

Let's try to import and use modules in our code files. To start with we'll import built-in Node modules for which you don't need any extra installation as these modules are already there in NodeJS.

We'll use fs and path modules to write a file. The 'fs' module is used to handle the file system and the 'path' module is used to handle file paths.

In order to use these modules, you'll need to import them, in NodeJS you can do it as given below.

const fs = require('fs');

const path = require('path');

Using writeFile() method of the fs package we'll write to a file in Node.js. Here is the description of the writeFile() method.

fs.writeFile( file, data, options, callback )
  • file: Path of the file where it has to be written.
  • data: The data you want to write to the file.
  • options: To specify optional parameters like encoding
  • callback: It is the function that would be called when the method is executed.

index.js

Here is the modified index.js file.

const fs = require('fs');
const path = require('path');
console.log(__dirname);
console.log("It's a new Node project");
const content = "A test file";
fs.writeFile(path.join(__dirname, 'test.txt'), content, (err) => {
    if (err)
      console.log(err);
    else {
      console.log("File written successfully\n");
    }
});

Note that __dirname is a variable that tells you the absolute path of the directory containing the currently executing file. Using path.join() method an absolute path for the file is given.

If you run npm start command now you should see a file "test.txt" created within your root project directory.

Installing third party packages in Node project

In the above example we used built-in modules that don’t need any installation but you will definitely use many other third-party packages that would need installation. For that you will use npm install <package_name> command.

In our project we'll try to install Nodemon package that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

To see Nodemon in use we'll change the index.js to create a HTTP Server using Node.js

index.js

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const requestListener = function(req, res){
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.write('Hello World');
    res.write(' From NodeJS\n');
    res.end();
}
const server = http.createServer(requestListener);

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

If you run the npm start command now and go to the URL http://localhost:3000/ once the server is started you should see the response as sent by the server.

If we make a slight change in the code now and change the line from res.write(' From NodeJS\n'); to this res.write(' From NodeJS Project\n');

Above change won't be reflected automatically and you'll have to stop the server and restart it to get this change reflected. That's where Nodemon can help as it automatically restarts the node application when file changes are detected.

npm install options

You can control where and how the specified packages get saved by using some additional flags with npm install

-P, --save-prod: Package will appear in your dependencies. You'll use this option if you want the installed package to be part of production build too. This is the default also

-D, --save-dev: Package will appear in your devDependencies. You'll use this option if you want the installed package to be used during development only.

-O, --save-optional: Package will appear in your optionalDependencies.

--no-save: Prevents saving to dependencies.

It makes sense to install Nodemon as dev dependency so use the following command to install Nodemon.

npm install nodemon --save-dev

Once the installation is done if you go back to your project structure you'll see some new directories and files like package-lock.json and node_modules folder.

package-lock.json- Provides version information for all packages installed into node_modules by the npmclient.
node_modules- Provides npm packages to the entire workspace. That's the directory where packages are installed.

Node project structure

In the package.json file now you'll see a "devDependencies" entry.

"devDependencies": {
    "nodemon": "^3.1.0"
  }

You'll need to make one more change in the start script to start using nodemon rather than node.

"start": "nodemon index.js"

With that if you use npm start command.

npm start

> nodeapp@1.0.0 start
> nodemon index.js

[nodemon] 3.1.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node index.js`
Server running at http://localhost:3000/

If you make changes in index.js file you can see that the application starts automatically now.

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Server running at http://localhost:3000/

That's all for this topic How to Setup a Node.js Project. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Node.js Tutorial Page


Related Topics

  1. Introduction to Node.js
  2. Creating HTTP server in Node.js
  3. Node.js REPL
  4. NodeJS NPM Package Manager
  5. Node.js Event Driven Architecture

You may also like-

  1. Reading a File in Node.js
  2. Node.js path.basename() Method With Examples
  3. JavaScript Rest Parameter
  4. How to Use ngFor and ngIf in Same Element in Angular
  5. React create-react-app Project Structure
  6. Spring Boot Hello World Web Application Example
  7. Java Exception Handling Interview Questions And Answers
  8. Creating PDF in Java Using iText

Tuesday, April 23, 2024

Difference Between StackOverflowError and OutOfMemoryError in Java

Differences between StackOverflowError and OutOfMemoryError in Java is a frequently asked Java interview question. You may also encounter one of these errors in your application. Before going into StackOverflowError Vs OutOfMemoryError let’s get some background about these errors.


StackOverflowError in Java

Whenever you run any Java program even if you don’t explicitly create any thread a main thread is started and that thread runs the program.

For each thread JVM creates a stack, whenever any method is invoked a new frame is created and pushed into the JVM stack for the thread. Each frame stores data corresponding to the invoked method including local variables, operand stack and a reference to the run-time constant pool and reference to exception table.

Once the method execution is completed corresponding stack frame is popped out of the stack.

JVM throws StackOverflowError if the stack memory requirement of any method exceeds the permitted stack memory size. A very common scenario where you may see StackOverflowError is when you have a recursive method with no terminating condition. For example following program that calculates factorial of a number using recursive method call. Since there is no exit condition defined so recursive method call never ends resulting in StackOverflowError.

public class StackOFErrorExp {
  public static void main(String[] args) {
    double factorialResult = factorial(1000);
    System.out.println(factorialResult);
  }
  private static int factorial(int i) {
    /*
     * if (i == 0 || i == 1 ) '
     *  return 1;
     */
    return i * factorial(i - 1);
  }
}

OutOfMemoryError in Java

In Java, memory for each object, for arrays and for instance variables (variables at class level not method level) is created on the heap. When there are no references to an object that object is garbage collected thus clearing the heap memory.

If you try to create an object or array that tries to take more memory than the allocated heap memory or there are a lot of objects in heap that are still referenced so can’t be garbage collected and JVM tries to allocate heap memory for a new object JVM throws java.lang.OutOfMemoryError because there is no sufficient heap memory.

Here is an example of java.lang.OutOfMemoryError where objects are added to an ArrayList in an infinite loop. Since objects stored to the List are not garbage collected so heap memoery will finally run out of memory resulting in OutOfMemoryError.

public class OutofMemoryExp {
  public static void main(String[] args) {
    List list = new ArrayList<>();
    int i = 0;
    // results in indefinite loop
    while(true) {
      i++;
      list.add(i * 1000000);
    }  
  }
}

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at java.base/java.util.Arrays.copyOf(Arrays.java:3721)
 at java.base/java.util.Arrays.copyOf(Arrays.java:3690)
 at java.base/java.util.ArrayList.grow(ArrayList.java:237)
 at java.base/java.util.ArrayList.grow(ArrayList.java:242)
 at java.base/java.util.ArrayList.add(ArrayList.java:485)
 at java.base/java.util.ArrayList.add(ArrayList.java:498)
 at org.netjs.examples.OutofMemoryExp.main(OutofMemoryExp.java:14)

StackOverflowError Vs OutOfMemoryError in Java

  1. StackOverflowError is thrown when there is no sufficient stack space for storing method data.
    OutOfMemoryError is thrown when no sufficient heap space left for creating new objects or requested array size is more than heap memory.
  2. StackOverflowError happens when you have Recursive methods with out terminating condition.
    OutOfMemoryError happens when new objects can’t be allocated on the heap as existing objects still have references so can’t be garbage collected.
  3. In order to avoid StackOverflowError ensure that methods are finishing their execution and corresponding stack memory is freed.
    In order to avoid OutOfMemoryError ensure that there are no references to objects which you don’t need anymore so that such objects can be garbage collected freeing heap memory in the process.

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


Related Topics

  1. Difference Between Checked And Unchecked Exceptions in Java
  2. Difference Between throw And throws in Java
  3. final Vs finally Vs finalize in Java
  4. java.lang.ClassCastException - Resolving ClassCastException in Java
  5. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java

You may also like-

  1. Java Exception Handling Interview Questions And Answers
  2. Array in Java With Examples
  3. Varargs (Variable-length Arguments) in Java
  4. Type Erasure in Java Generics
  5. Pre-defined Functional Interfaces in Java
  6. Linear Search (Sequential Search) Java Program
  7. Introduction to Node.js
  8. Bean Scopes in Spring With Examples

Monday, April 22, 2024

What is In-place Algorithm

An in-place algorithm is an algorithm that doesn’t use any auxiliary space to transform the input. Though theoretically that would mean if you have an array of length n then you should use that n space itself to transform the input array but in reality you will definitely use some variables and index for array and that kind of auxiliary space is allowed for an in-place algorithm.

Examples of in-place algorithm are sorting algorithms like Bubble sort, Selection Sort, Insertion Sort which doesn’t require any extra space to perform sorting. That is why space complexity for these algorithms is O(1).

Merge sort, Bucket sort are examples of not in-place or out-of-place sorting algorithms.

In-place algorithm example

Let’s try to understand this auxiliary space requirement of in-place algorithm by taking an algorithm to reverse an array by using separate input and output arrays making it a not in-place algorithm.

import java.util.Arrays;

public class ReverseArray {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 47, 34, 7, 10, 0, 106, 2, 54};
    reverseArray(intArr);
  }
    
  static void reverseArray(int[] intArray) {
    int n = intArray.length;
    // Using another array
    int[] tempArray = new int[n];
    for (int i = 0; i < n; i++) { 
      tempArray[n - i - 1] = intArray[i]; 
    } 
    System.out.println("Reversed Array- " + Arrays.toString(tempArray));
  }
}

But the algorithm to reverse an array can very well be written to use the same input array to reverse it. There is no need to use a separate array making it an in-place algorithm.

public class ReverseArray {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 47, 34, 7, 10, 0, 106, 2, 54};
    reverseArray(intArr);
  }
    
  static void reverseArray(int[] intArray) {
    int n = intArray.length;
    for (int i = 0; i < n / 2; i++) {
      int temp = intArray[i];
      intArray[i] = intArray[n - 1 - i];
      intArray[n - 1 - i] = temp;
    }
    System.out.println("Reversed Array- " + Arrays.toString(intArray));
  }
}

That's all for this topic What is In-place Algorithm. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Shell Sort Program in Java
  2. Tree Sort in Java Using Binary Search Tree
  3. Linear Search (Sequential Search) Java Program
  4. Reverse Each Word in a String Java Program
  5. How to Remove Elements From an Array Java Program

You may also like-

  1. Converting String to Enum Type in Java
  2. How to Read File From The Last Line in Java
  3. Java Program to Get Current Date and Time
  4. Running Dos/Windows Commands From Java Program
  5. How to Loop Through a Map in Java
  6. Difference Between Abstract Class And Interface in Java
  7. Angular One-Way Data Binding Using String Interpolation
  8. Changing String Case in Python

Sunday, April 21, 2024

Creating PDF in Java Using iText

In this post we’ll see how to create PDF in Java using iText library. Version of iText used here is the latest 8.x.x version. We’ll see various examples of PDF creation using iText showing the use of classes in iText like PdfDocument, Document, PdfWriter, Paragraph, Table, PdfFont, PDFReader.

Note that iText is open source but the open source version is AGPL licensed which means you must distribute all source code, including your own product and web-based applications.

Maven dependecy

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

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <itext.version>8.0.3</itext.version>
</properties>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>kernel</artifactId>
  <version>${itext.version}</version>
</dependency>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>io</artifactId>
  <version>${itext.version}</version>
</dependency>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>layout</artifactId>
  <version>${itext.version}</version>
</dependency>
<!-- Java logging used-->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.13</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.13</version>
</dependency>

Please be aware you will always need kernel, io and layout dependencies while working with iText library. Not having slf4j produces a warning so better have the dependencies available.

Following examples are listed in this post for generating PDF in Java using iText.

Creating PDF in Java using iText – Hello World

First lets see a simple iText PDF creation example where “Hello world” is written to the PDF using a Java program. Also the font and color for the text is specified before writing it to the PDF.

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;

public class PDFCreation {
 public static final String DEST = "G://Test//hello_world.pdf";
 public static void main(String[] args) {
  PdfWriter writer;
  try {
   writer = new PdfWriter(new FileOutputStream(DEST));
   PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
   PdfDocument pdf = new PdfDocument(writer);
   Document document = new Document(pdf);
   Text text = new Text("Hello World with font and color")
         .setFont(font)
         .setFontColor(ColorConstants.BLUE);
   //Add paragraph to the document
   document.add(new Paragraph(text));
   document.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }   
 }
}

Adding table in PDF using iText - Java Program

In this example we’ll see how to present content as a table in PDF using iText from your Java program. Example uses a bean class User, fields of object of type User are displayed in the table.

User.java

public class User {
  private String firstName;
  private String lastName;
  private String email;
  public User() {
   
  }
  public User(String firstName, String lastName, String email) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.email = email;
  }
  
  public String getFirstName() {
   return firstName;
  }
  public void setFirstName(String firstName) {
   this.firstName = firstName;
  }
  public String getLastName() {
   return lastName;
  }
  public void setLastName(String lastName) {
   this.lastName = lastName;
  }
  public String getEmail() {
   return email;
  }
  public void setEmail(String email) {
   this.email = email;
  }
}

Class used for creating PDF showing data in a table.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.netjs.Model.User;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;

public class PDFTableCreation {
  public static void main(String[] args) {
    new PDFTableCreation().createTablePDF("G://Test//table.pdf");
  }
    
  private void createTablePDF(String PDFPath){
    PdfWriter writer;
    try {
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdf = new PdfDocument(writer);
      Document document = new Document(pdf, new PageSize(PageSize.A4));
      PdfFont headerFont = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
      PdfFont cellFont = PdfFontFactory.createFont(StandardFonts.COURIER);
      // Create table with 3 columns of similar length
      Table table = new Table(new float[]{4, 4, 4});
      table.setWidth(UnitValue.createPercentValue(100));
      // adding header
      table.addHeaderCell(new Cell().add(new Paragraph(
              "First Name").setFont(headerFont)));
      table.addHeaderCell(new Cell().add(new Paragraph(
              "Last Name").setFont(headerFont)));
      table.addHeaderCell(new Cell().add(new Paragraph(
              "Email").setFont(headerFont)));
      List<User> users = getListOfUsers();
      // adding rows
      for(User user : users) {
        table.addCell(new Cell().add(new Paragraph(
             user.getFirstName()).setFont(cellFont)));
        table.addCell(new Cell().add(new Paragraph(
             user.getLastName()).setFont(cellFont)));
        table.addCell(new Cell().add(new Paragraph(
             user.getEmail()).setFont(cellFont)));
      }
      document.add(table);
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }    
  }
    
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() {
    List<User> users = new ArrayList<User>();
    users.add(new User("Jack", "Reacher", "abc@xyz.com"));
    users.add(new User("Remington", "Steele", "rs@cbd.com"));
    users.add(new User("Jonathan", "Raven", "jr@sn.com"));
    return users;
  }
}

Created PDF

Creating table in PDF Using iText- Java

Adding background image to PDF using iText

public class PDFCreation {
  public static final String DEST = "G://Test//image.pdf";
  public static void main(String[] args) {
    new PDFCreation().addImageToPDF(DEST);
  }
 
  private void addImageToPDF(String PDFPath){
    PdfWriter writer;
    try {
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc);
      PageSize pageSize = new PageSize(PageSize.A4).rotate();
   
      PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
      // creating image data instance by passing the path to image
      ImageData img = ImageDataFactory.create("resources//netjs.png");
      canvas.saveState();
      // graphic state
      PdfExtGState state = new PdfExtGState();
      state.setFillOpacity(0.2f);
      canvas.setExtGState(state);
      canvas.addImage(img, 20, 650, pageSize.getWidth()/2, false);
      canvas.restoreState();
      document.add(new Paragraph("Adding image to PDF Example"));      
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Created PDF

adding image to PDF in Java

Adding image to PDF using iText - Java Program

If you want to add image to PDF.

public class PDFCreation {
  public static final String DEST = "G://Test//image.pdf";

  public static void main(String[] args) {
    new PDFCreation().addImageToPDF(DEST);
  }
 
  private void addImageToPDF(String PDFPath){
    PdfWriter writer;
    try {
      // creating image data instance by passing the path to image
      Image image = new Image(ImageDataFactory.create("resources//netjs.png"));
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc);       
      document.add(new Paragraph("Adding image to PDF Example"));
      document.add(image);      
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Adding List to PDF using iText - Java Program

If you want to show a list of items in PDF then you can create a List and add ListItems to it. Symbol used for marking ListItems can be passed using setListSymbol() method. There is an Enum ListNumberingType that holds possible values for list item prefix. You can also pass a unicode character.

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.ListNumberingType;

public class PDFCreation {
  public static void main(String[] args) {
    new PDFCreation().addImageToPDF("G://Test//list.pdf");
  }

  private void addImageToPDF(String PDFPath){
    PdfWriter writer;
    try {
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc);       
      document.add(new Paragraph("Choices Are (Using English Letters)"));
            // for offset (space from the left)
      List list = new List().setSymbolIndent(14) 
                            .setListSymbol(ListNumberingType.ENGLISH_LOWER);
       
      // Add ListItem objects
      list.add(new ListItem("Aerobic"))
          .add(new ListItem("Anaerobic"))
          .add(new ListItem("Flexibility Training"));
      // Add the list
      document.add(list);
      
      document.add(new Paragraph("Choices Are (Using Roman upper)"));
      list = new List()
           .setSymbolIndent(14)
           .setListSymbol(ListNumberingType.ROMAN_UPPER);
      // Add ListItem objects
      list.add(new ListItem("Aerobic"))
          .add(new ListItem("Anaerobic"))
          .add(new ListItem("Flexibility Training"));
      // Add the list
      document.add(list);
      
      document.add(new Paragraph("Choices Are (Using bullet symbol)"));
      list = new List()
           .setSymbolIndent(14) 
           .setListSymbol("\u2022"); // Passing unicode for bullet
      // Add ListItem objects
      list.add(new ListItem("Aerobic"))
          .add(new ListItem("Anaerobic"))
          .add(new ListItem("Flexibility Training"));
      // Add the list
      document.add(list);            
      document.close();         
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Created PDF

creating PDF with list items using Java

iText: Render PDF to browser as web response

If you want to render PDF to the browser in your web project using the HTTPResponse, then you can do it as follows. PDFWriter constructor also accepts an OutputStream as parameter. If you want to write a web application, then you can create a ServletOutputStream.

PdfWriter writer;
try{
  response.setContentType("application/pdf");
  writer = new PdfWriter(response.getOutputStream());
  PdfDocument pdfDoc = new PdfDocument(writer);
  Document document = new Document(pdfDoc); 
  PdfFont titleFont = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
  PdfFont textFont = PdfFontFactory.createFont(StandardFonts.COURIER);
  document.add(new Paragraph("PDF generated in Web")
          .setFont(titleFont).setFontColor(ColorConstants.RED)
          .setTextAlignment(TextAlignment.CENTER));
  Paragraph p = new Paragraph("This is the text of the PDF created using iText library and 
               rendered to the browser using a Servlet.");
  document.add(p.setFont(textFont).setFontColor(ColorConstants.ORANGE));
  document.close();
}catch(Exception e){
  e.printStackTrace();
}

Created PDF

rendering PDF in web application

Password protected PDF with user permissions using iText - Java Program

You can encrypt the created PDF, there are two types of passwords you can set-

  • User password
  • Owner password

The userPassword and the ownerPassword can be null or have zero length.

You can also set user permissions (operation permitted when the PDF document is opened with the user password). Available user permissions are defined in the EncryptionConstants class.

  • EncryptionConstants.ALLOW_PRINTING
  • EncryptionConstants.ALLOW_MODIFY_CONTENTS
  • EncryptionConstants.ALLOW_COPY
  • EncryptionConstants.ALLOW_MODIFY_ANNOTATIONS
  • EncryptionConstants.ALLOW_FILL_IN
  • EncryptionConstants.ALLOW_SCREENREADERS
  • EncryptionConstants.ALLOW_ASSEMBLY
  • EncryptionConstants.ALLOW_DEGRADED_PRINTING

The permissions can be combined by ORing them, as example (EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_MODIFY_CONTENTS)

Example code

For this code to run you will need bouncycastle jar. Maven dependency for IText Bouncy Castle Connector is as follows-

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>bouncy-castle-connector</artifactId>
    <version>${itext.version}</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>bouncy-castle-adapter</artifactId>
    <version>${itext.version}</version>
</dependency>
public class PDFWithPwd {
  public static void main(String[] args) {
    new PDFWithPwd().changePermissions("G://Test//Permissions.pdf");
  }
 
  private void changePermissions(String pdfPath) {
    final String USER_PWD="user";
    final String OWNER_PWD="owner";
    try {
      PdfWriter writer = new PdfWriter(pdfPath, new WriterProperties()
                  .setStandardEncryption(USER_PWD.getBytes(), OWNER_PWD.getBytes(), 
                   EncryptionConstants.ALLOW_PRINTING, 
                   EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc); 
      document.add(new Paragraph("This PDF is password protected and its content can’t be copied by user."));
      document.close();
    }catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

If you open the created PDF it will ask for the password. If you open it using the user password then you won’t be able to copy the content as per the user permission settings.

password protected PDF in Java using iText

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

>>>Return to Java Programs Page


Related Topics

  1. How to Create PDF From XML Using Apache FOP
  2. Spring MVC PDF Generation Example
  3. How to Create Password Protected Zip File in Java
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. Convert double to int in Java

You may also like-

  1. How to Count Lines in a File in Java
  2. Creating Tar File And GZipping Multiple Files in Java
  3. Comparing Enum to String in Java
  4. Remove Duplicate Elements From an Array in Java
  5. Difference Between Comparable and Comparator in Java
  6. SerialVersionUID And Versioning in Java Serialization
  7. Difference Between Abstract Class And Interface in Java
  8. Dependency Injection in Spring Framework

Saturday, April 20, 2024

Writing a File Asynchronously Java Program

In this post we’ll see how to write a file asynchronously in Java using java.nio.channels.AsynchronousFileChannel class added in Java 7. Using AsynchronousFileChannel class you can create an asynchronous channel for reading, writing, and manipulating a file.

To see how to read a file asynchronously in Java, refer this post- Read File Asynchronously Java Program

Opening an Asynchronous channel

Whether you are reading or writing a file asynchronously first thing you need to do is to create an asynchronous channel. For that you need to use static open() method of the AsynchronousFileChannel class which opens or creates a file for reading or writing, returning an asynchronous file channel to access the file.

Following code snippet shows how you can create an asynchronous file channel for writing to a file.

Path path = Paths.get("F:\\netjs\\WriteFile.txt");
AsynchronousFileChannel asyncFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)

Writing file asynchronously using AsynchronousFileChannel class

For writing a file asynchronously there are two versions of write() method in the AsynchronousFileChannel class.

  1. write() method that writes the passed buffer to the file and returns a Future representing the result of the write operation.
  2. write() method where you pass CompletionHandler instance as an argument.

We’ll see examples of of both of these ways to write a file asynchronously to have a better idea.

Writing to a file asynchronously in Java

1. In the first Java program we’ll use the write method that returns a Future.

Future<Integer> write(ByteBuffer src, long position)- This method writes a sequence of bytes to this channel from the passed buffer, starting at the given file position.

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AsyncFileWrite {
  public static void main(String[] args) {
    Path path = Paths.get("F:\\netjs\\test.txt");
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    // Write Data to buffer
    buffer.put("This will be written to a file.".getBytes());
    buffer.flip();
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)){
      // Write to async channel from buffer
      // starting from position 0
      Future<Integer> future =  asyncChannel.write(buffer, 0);
      while(!future.isDone()) {
        System.out.println("Waiting for async write operation... ");
        // You can do other processing
      }            
      buffer.clear();            
      System.out.println("Total bytes written- " + future.get());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

2. In this Java program for writing file asynchronously we’ll use the write() method where CompletionHandler instance is passed as an argument.

CompletionHandler interface defines two callback methods which you need to implement.

  • completed(V result, A attachment)- Invoked when an operation has completed.
  • failed(Throwable exc, A attachment)- Invoked when an operation fails.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.channels.CompletionHandler;

public class AsyncFileWrite {
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("F:\\netjs\\test.txt");
    if(!Files.exists(path)){
      Files.createFile(path);
    }
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    // Write Data to buffer
    buffer.put("This will be written to a file.".getBytes());
    buffer.flip();
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)){
      // Write to channel from buffer, start from position 0
      asyncChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
          System.out.println("Total bytes written- " + result);
        }

        @Override
        public void failed(Throwable ex, ByteBuffer attachment) {
          System.out.println("Write operation failed- " + ex.getMessage());                    
        }
      });            
    }
  }
}

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


Related Topics

  1. Write to a File in Java
  2. How to Append to a File in Java
  3. How to Write Excel File in Java Using Apache POI
  4. Creating Temporary File in Java
  5. Reading File in Java Using BufferedReader

You may also like-

  1. How to Create Password Protected Zip File in Java
  2. Creating PDF in Java Using Apache PDFBox
  3. Arrange Non-Negative Integers to Form Largest Number - Java Program
  4. Invoking Getters And Setters Using Reflection in Java
  5. HashMap in Java With Examples
  6. Interface in Java
  7. Passing Arguments to getBean() Method in Spring
  8. YARN in Hadoop

Friday, April 19, 2024

Radio Button in Angular Form Example

In this post we’ll see how to use radio buttons in Angular form. We’ll see examples of adding radio button to both template-driven and reactive form in Angular.


Radio button in template driven form example

In this Angular template driven form example we’ll have a form with two input fields for name and email, a date picker for picking date and a group of radio buttons to select membership type.

Thursday, April 18, 2024

Functional Interfaces in Java

A functional interface in Java 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().


Java functional interface example

interface IMyInterface {
  int getValue();
}

In interface IMyInterface there is only single abstract method getValue() (note that in an interface methods are implicitly abstract).

Wednesday, April 17, 2024

FormBuilder in Angular Example

In this tutorial we’ll see how to use FormBuilder in Angular to create a form. FormBuilder is a helper class that reduces the boilerplate code while building a form. It shortens the code to create instances of a FormControl, FormGroup, or FormArray.

Steps needed to use FormBuilder

  1. Import the FormBuilder class.
    import { FormBuilder } from '@angular/forms';
    
  2. Inject the FormBuilder service.
    constructor(private fb: FormBuilder) { }
    
  3. Generate the form contents. The FormBuilder has three factory methods: control(), group(), and array() used to generate instances of FormControl, FormGroup, and FormArray in your component classes.

Tuesday, April 16, 2024

Java Object Cloning - clone() Method

In this post we'll see what is Object cloning in java and what is shallow copy and deep copy in reference to Java object cloning.

In Java if you assign an object variable to another variable the reference is copied which means both variable will share the same reference. In this case any change in one object variable will be reflected in another.

For example, if there is a class Test and you create an object of that class and then assign that reference to another object variable.

Test obj1 = new Test();
Test obj2 = obj1;

Here both obj1 and obj2 will have the same reference.


Java Object cloning

What is the option then if you want to quickly create an object using the existing object in such a way that you get a new instance (reference is not shared) with the same content for the fields in the new object as in existing object.

That’s when you can use clone() method which creates an exact copy of the existing object. Then you can modify the cloned object without those modifications reflecting in original object (Well we’ll go into shallow copy and deep copy a little later).

clone() method in Java

clone() method is defined as protected in the Java Object class which you must override as public in any derived classes that you want to clone.

Signature of clone method in Object class

protected native Object clone() throws CloneNotSupportedException;

Process of object cloning in Java

There are two required steps if you want to clone any object.

  1. You need to call clone() method of the Object class or provide your own implementation by overriding the clone() method in your class.
  2. Your class, whose object you want to clone, must implement Cloneable interface which is part of java.lang package. Not implementing Cloneable interface will result in CloneNotSupportedException exception being thrown when clone method is called.

Here note that Cloneable interface is a marker interface and defines no members of its own.

Object cloning in Java example

When cloning an object in Java you need to call clone() method of the Object class. You can do it from a method or you can override clone() method of the Object class and then call the clone() method of the super class (Object class).

Scenario 1- Calling clone() method from a method

Here we have a class Test which implements Cloneable interface and it has a method cloneIt() which calls the clone() method of the Object class.

Class Test

public class Test implements Cloneable{
  int a;
  float f;
 
 Test cloneIt(){
  Test test = null;
  try {
   // Calling clone() method of Object class
   test = (Test)super.clone();
  } catch (CloneNotSupportedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return test;
  
 }
}

CloningDemo class

public class CloningDemo {

 public static void main(String[] args) {
  Test t1 = new Test();
  t1.a = 10;
  t1.f = 13.4F;
  // Calling method to clone
  Test t2 = t1.cloneIt();
  System.out.println("t1.a " + t1.a + " t1.f " + t1.f);
  
  System.out.println("t2.a " + t2.a + " t2.f " + t2.f);

  if(t1 != t2){
   System.out.println("Different instances");
  }else{
   System.out.println("Same instances");
  }
 }
}

Output

t1.a 10 t1.f 13.4
t2.a 10 t2.f 13.4
Different instances

Here you can see that Test class object t1 is cloned and a new instance t2 is created. In the code, reference equality is checked and you can see that the reference is not shared and both are indeed different instances. New instance t2 has the same values in the properties.

Points to note

Some of the points to note from this code–

  1. Class whose object has to be cloned should implement Cloneable interface, otherwise java.lang.CloneNotSupportedException exception will be thrown.
  2. clone() method is a protected method in Object class, since all the classes inherit from Object class so you can call the protected method of the super class.
  3. While cloning bitwise copy of the object is created.

Scenario 2 – Overriding clone method

Another way to provide object cloning functionality is to override the clone() method in the class, in that case it has to be a public method in order to be accessible.

If we change the classes used in the above example to have overridden clone method and calling that clone method then the structure will be as follows–

Test class

public class Test implements Cloneable{
 int a;
 float f;
 // Override clone method
 public Object clone(){
  Object obj = null;
  try {
   // Calling clone() method of Object class
   obj = super.clone();
   } catch(CloneNotSupportedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  return obj;
 }
}

CloningDemo class

public class CloningDemo {

 public static void main(String[] args) {
  Test t1 = new Test();
  t1.a = 10;
  t1.f = 13.4F;
  // Call clone method
  Test t2 = (Test)t1.clone();
  System.out.println("t1.a " + t1.a + " t1.f " + t1.f);
  
  System.out.println("t2.a " + t2.a + " t2.f " + t2.f);
  
  if(t1 != t2){
   System.out.println("Different instances");
  }else{
   System.out.println("Same instances");
  }
 }
}

Output

t1.a 10 t1.f 13.4
t2.a 10 t2.f 13.4
Different instances

Advantages of object cloning

If you have an object, creation of which using the usual way is costly; as example if you have to call DB in order to get data to create and initialize your object. In that scenario rather than hitting DB every time to create your object you can cache it, clone it when object is needed and update it in DB only when needed.

Actually there is a design pattern called prototype design pattern which suggests the same approach.

Shallow copy - Java object cloning

In the above examples only primitive types are used so there is no problem, if you change any primitive value that won’t reflect in other object.

What if there is another object reference in your class? As already mentioned when you clone an object all the values for the fields are copied to the cloned object. Since Java is pass by value, if the field value is a reference to an object (a memory address) it copies that reference to the field of the cloned object. In that case referenced field is shared between both objects and any change made to the referenced field will be reflected in the other object too.

This process of cloning when the field values are copied to the new object is known as shallow copy. Shallow copies are simple to implement and typically cheap, as they can be usually implemented by simply copying the bits exactly.

Deep Copy - Java object cloning

If you don’t want references of object being copied during the cloning process then option is deep copy. When a deep copy is done objects referenced by the cloned object are distinct from those referenced by original object, and independent.

Deep copies are more expensive, as you need to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.

That's all for this topic Java Object Cloning - clone() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Serialization and Deserialization in Java
  2. SerialVersionUID And Versioning in Java Serialization
  3. Java Nested Class And Inner Class
  4. Marker interface in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. instanceof Operator in Java With Examples
  2. BigDecimal in Java With Examples
  3. Java split() Method - Splitting a String
  4. final Vs finally Vs finalize in Java
  5. Parallel Stream in Java Stream API
  6. @FunctionalInterface Annotation in Java
  7. Deadlock in Java Multi-Threading
  8. Java Program to Find The Longest Palindrome in a Given String