Monday, October 18, 2021

Spring Constructor Based Dependency Injection

In the post Dependency Injection in Spring I have already talked about dependency injection. In this post we'll explore one of the type of the dependency injection called Constructor based dependency injection in Spring.

In Constructor based dependency injection, Spring IOC container invokes a class' constructor with arguments that represent the dependencies of that class.


Constructor Dependency Injection Example

Let's see an example of constructor dependency injection in Spring, there is one class called PayServiceImpl which is dependent on Payment class and also has a field amount of type int and those constructor arguments are injected through a constructor DI.

Wednesday, October 6, 2021

Java Stream - distinct() With Examples

In this tutorial you will see some examples of distinct() method in Java Stream API. Stream.distinct() method is used to remove duplicate elements and the method returns a new stream consisting of the distinct elements. To determine which elements are duplicates distinct() method uses the equals() method of the Object class.

distinct() in Java Stream

Syntax of the distinct() method is as given below-

Stream<T> distinct()

Here are some important points about the distinct operation.

  1. It is a stateful intermediate operation which means it may incorporate state from previously seen elements when processing new elements.
  2. Method takes no arguments and returns a new Stream consisting of the distinct elements.
  3. For ordered streams distinct operation is stable i.e. if there are duplicate elements the element appearing first in the encounter order is preserved.
  4. For unordered streams there are no stability guarantees.

Monday, October 4, 2021

Java Stream - filter() With Examples

In this tutorial you will see some examples of filter() method in Java Stream API. filter() method is used to filter out some elements based on the passed condition and the remaining elements, that satisfy the condition, are returned as a new Stream.


filter() in Java

filter() is an intermediate operation and its syntax is as given below-

Stream<T> filter(Predicate<? super T> predicate)

Here Predicate, which is a functional interface, is used to pass the condition that is used to filter out elements. Since Predicate is a functional interface so it is usually implemented as a lambda expression.

Friday, October 1, 2021

Java Program to Reverse a Number

How to reverse a number in Java without using any API is asked in many interviews in order to check the logic. Though how to reverse a string program is applicable for numbers also by treating the numbers as String but in some interviews it is specifically asked that it has to be a number and then you need to reverse it without using any in-built method.

Reversing number in Java can be done in two ways

  • By iterating through digits of the number and using mathematical operators like divide and multiply.
  • Using recursive function.

Iterative logic for reversing a number

When iterating through each digit of the number idea is to divide the given number by 10 and adding that remainder to an integer (which is initially initialized to 0) also multiply that integer by 10 in each iteration. That is required to move place values in the reversed number. Also divide the original number by 10 to get the quotient.

As example– If original number is 189 then first iteration will give remainder as 9 and quotient as 18. In the second iteration remainder will be 8 and quotient 1. And every time it is also multiplied by 10 for place value. Thus after second iteration it will be (9 * 10) + 8 = 98. Same for third iteration where remainder will be 1 and quotient 0. Thus making it (98 * 10) + 1 = 981. Which is the reversed number.

Recursive logic for reversing number

In recursive method you call the same method with one less digit in every recursive call. That is done by dividing the number by 10. You have to print modulo division in every recursive call. Using recursion this way will also print the zeroes which the iterative logic will not do. Meaning using the first method will give you 2 if input is 200. Whereas recursive method will give 002.

Java program to reverse a number

import java.util.Scanner;

public class ReverseNumber {

 public static void main(String[] args) {
  System.out.println("Please enter a number : ");
  Scanner sc = new Scanner(System.in);
  int scanInput = sc.nextInt();
  // Using recursion
  reverseRec(scanInput);
  System.out.println();
  System.out.println("------------------");
  // Using while loop
  reverseNum(scanInput);
 }
 
 // Method for reversing number using recursion
 public static void reverseRec(int num){
  //System.out.println("num" + num);
  if(num == 0)
   return;
  System.out.print(num % 10);
  reverseRec(num/10);
 }
 
 // Non-recursive method for reversing number  
 public static void reverseNum(int num){
  int reversedNum = 0;
  int mod = 0;
  while(num != 0){
   mod = num % 10;
   reversedNum = (reversedNum * 10) + mod;
   num = num/10;
  }
  System.out.println("reversedNum -- " + reversedNum);
 }
}

Output

Please enter a number : 
91346
64319
------------------
reversedNum -- 64319

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

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Display Prime Numbers
  2. Convert float to int in Java
  3. Arrange Non-Negative Integers to Form Largest Number - Java Program
  4. How to Run Threads in Sequence in Java
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. How to Untar a File in Java
  2. How to Append to a File in Java
  3. String in Java Tutorial
  4. Constructor Chaining in Java
  5. Difference Between Encapsulation And Abstraction in Java
  6. Difference Between HashMap And ConcurrentHashMap in Java
  7. Difference Between Comparable and Comparator in Java
  8. Java Stream API Tutorial

Thursday, September 30, 2021

Java Stream - limit() With Examples

In Java Stream API limit(long maxSize) method is used to truncate the stream so that it is not longer than maxSize in length and the method returns a stream consisting of that many elements of this stream.

Java Stream limit() method

Syntax of the limit method is as given below-

Stream<T> limit(long maxSize)

Here maxSize argument represents the number of elements the stream should be limited to.

If maxSize is negative then IllegalArgumentException is thrown otherwise a new Stream is returned which is no longer than maxSize in length.

Notes about limit() method

  • limit() is generally considered a cheap operation on sequential stream pipelines
  • limit() can be quite expensive on ordered parallel pipelines, since limit(n) is constrained to return not just any n elements, but the first n elements in the encounter order.
  • It is a short-circuiting stateful intermediate operation. Since limit() method returns a new stream that makes it a stateful intermediate operation. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result.

limit() Java examples

1. Getting a sublist from a List by limiting the number of elements to the first n elements of the original list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamLimit {
  public static void main(String[] args) {
    StreamLimit sl = new StreamLimit();
    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> subList = numList.stream().limit(5).collect(Collectors.toList());     
    System.out.println("Sublist after limiting elements- " + subList);
  }
}

Output

Sublist after limiting elements- [1, 2, 3, 4, 5]

2. Getting 10 random numbers by using limit() with generate() method.

public class StreamLimit {
  public static void main(String[] args) {
    Stream.generate(Math::random)
          .map(n -> (int)(n * 100))
          .limit(10)
          .forEach(System.out::println);
  }
}

That's all for this topic Java Stream - limit() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - skip() With Examples
  2. Primitive Type Streams in Java Stream API
  3. Reduction Operations in Java Stream API
  4. Spliterator in Java
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Just In Time Compiler (JIT) in Java
  2. Byte Streams in Java IO
  3. How to Get The Inserted ID (Generated ID) in JDBC
  4. Method Reference in Java
  5. java.lang.ClassCastException - Resolving ClassCastException in Java
  6. Creating PDF in Java Using Apache PDFBox
  7. Method Overloading in Python
  8. Spring Boot Spring Initializr

Wednesday, September 29, 2021

Java Stream - skip() With Examples

In Java Stream API skip(long n) method is used to skip the first 'n' elements of the stream and return a stream consisting of the remaining elements of this stream.

Java Stream skip() method

Syntax of the skip method is as given below-

Stream<T> skip(long n)

Here n represents the number of leading elements to skip.

Method returns a new stream consisting of the remaining elements of this stream after skip operation. Since a new stream is returned that means skip() is a stateful intermediate operation.

If n is passed as a negative number, then IllegalArgumentException is thrown.

If this stream contains fewer than n elements then an empty stream will be returned.

skip() Java examples

1. To get a sublist from a List using skip method.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamSkip {

  public static void main(String[] args) {
    StreamSkip ss = new StreamSkip();
    // Get sublist from the list of Integers
    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> subList = ss.getSubList(numList, 4);
    System.out.println("Sublist after skipping elements- " + subList);
    
    // Get sublist from the list of Strings
    List<String> strList = Arrays.asList("one", "two", "three", "four",
        "five","six","seven","eight","nine","ten");
    List<String> strSubList = ss.getSubList(strList, 5);
    System.out.println("Sublist after skipping elements- " + strSubList);
  }

  public <T> List<T> getSubList(List<T> firstList, long n){
    return firstList.stream().skip(n).collect(Collectors.toList());
  }
}

Output

Sublist after skipping elements- [5, 6, 7, 8, 9, 10]
Sublist after skipping elements- [six, seven, eight, nine, ten]

2. If n is greater than the stream size

public class StreamSkip {

  public static void main(String[] args) {
    StreamSkip ss = new StreamSkip();
    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6);
    List<Integer> subList = numList.stream().skip(7).collect(Collectors.toList());     
    System.out.println("Sublist after skipping elements- " + subList);
  }
}

Output

Sublist after skipping elements- []

As you can see an empty stream is returned because elements you are trying to skip is more than the size of the stream itself.

That's all for this topic Java Stream - skip() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Stream API in Java 8
  2. Java Stream - limit() With Examples
  3. collect() Method And Collectors Class in Java Stream API
  4. Spliterator in Java
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. New Date And Time API in Java With Examples
  2. StringJoiner Class in Java 8
  3. JShell in Java With Examples
  4. Private Methods in Java Interface
  5. Lambda Expressions in Java 8
  6. Convert float to int in Java
  7. Spring MVC Configuring Multiple View Resolvers Example
  8. NgNonBindable Directive in Angular

Monday, September 13, 2021

BigDecimal in Java With Examples

This post gives an overview of BigDecimal in Java and the examples of BigDecimal class usage in scale manipulation, rounding and format conversion where more precision is required.


Why BigDecimal is needed

While reading about primitive date types in Java we get to know that we should use float and double primitive types for decimal numbers. But there is one problem with these primitive types float and double that these types should never be used for precise value, such as currency.

Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

As exmaple

double d1 = 374.56;
double d2 = 374.26;
System.out.println( "d1 - d2 = " + ( d1 - d2 ));

Here you may expect the output to be .30 but the actual output is-

d1 - d2 = 0.30000000000001137

That’s why in financial applications where scale and rounding mode for the numbers is an important aspect while doing calculations, it’s a better choice to go with BigDecimal in Java.

Java BigDecimal class

BigDecimals are immutable, arbitrary-precision signed decimal numbers which can be used for monetary calculations.

In the example used above if we use BigDecimal instead of double then value would be calculated precisely.

BigDecimal bd1 = new BigDecimal("374.56");
BigDecimal bd2 = new BigDecimal("374.26");
  
System.out.println("bd1 - bd2 = " + bd1.subtract(bd2));

Now the output will be as expected-

bd1 - bd2 = 0.30

BigDecimal class in Java extends Number and implements Comparable.

public class BigDecimal extends Number implements Comparable<BigDecimal> {

}

Constructors in BigDecimal class

BigDecimal class in Java provides many constructors where a BigDecimal object can be initialized using int, char[], BigDecimal, String, double, long. In total 18 constructors are there.

One thing to note here is using a double value to initialize a BigDecimal may give the precision problem again. As seen in the example below-

BigDecimal bde = new BigDecimal(23.12);
System.out.println("" + bde.toString());

Output you get from printing this BigDecimal is-

23.120000000000000994759830064140260219573974609375

Thus it is always safe to go with a constructor that takes String as argument when representing a decimal value.

BigDecimal bde = new BigDecimal("23.12");
System.out.println("" + bde.toString());

Output

23.12

Scaling in BigDecimal

One of the biggest reason to use BigDecimal is to be able to provide scale (How many numbers will be there after the decimal) and to provide rounding mode.

In order to specify the number of digits after the decimal point you can use the setScale(int scale) method.

But it is always better to provide the rounding mode too along with scale. For that there are two overloaded methods.

  • setScale(int newScale, int roundingMode)
  • setScale(int newScale, RoundingMode roundingMode)

Let’s see an example to show why you should that, let’s assume you are using a double value to construct a BigDecimal object then you will loose some precision as shown in an example in the Constructor section.

BigDecimal bde = new BigDecimal(23.12);
System.out.println("Value- " + bde.toString());
System.out.println("Scaled value- " + bde.setScale(1).toString());

Output

Value- 23.120000000000000994759830064140260219573974609375
Exception in thread "main" java.lang.ArithmeticException: Rounding necessary
 at java.base/java.math.BigDecimal.commonNeedIncrement(BigDecimal.java:4495)
 at java.base/java.math.BigDecimal.needIncrement(BigDecimal.java:4702)
 at java.base/java.math.BigDecimal.divideAndRound(BigDecimal.java:4677)
 at java.base/java.math.BigDecimal.setScale(BigDecimal.java:2811)
 at java.base/java.math.BigDecimal.setScale(BigDecimal.java:2853)
 at org.netjs.Programs.App.main(App.java:15)

From the output you can see that some precision is lost as the value of bde is 23.120000000000000994759830064140260219573974609375. When setting scale as 1 it is not known what is the rounding mechanism so Arithmetic exception is thrown instead.

Rounding modes in Java BigDecimal

There are eight rounding modes provided by the BigDecimal class as static final int. If you have noticed above in scaling section there are two overloaded methods where the second one takes RoundingMode as parameter. RoundingMode is an Enum provided in the package java.math.

It is always recommended to use RoundingMode enum in place of int constants. According to Java docs-

“Using the integer fields in this class (such as ROUND_HALF_UP) to represent rounding mode is largely obsolete; the enumeration values of the RoundingMode enum, (such as RoundingMode.HALF_UP) should be used instead.”

RoundingMode Enum Constants

Eight rounding modes provided are-

  • CEILING- Rounding mode to round towards positive infinity.
  • DOWN- Rounding mode to round towards zero.
  • FLOOR- Rounding mode to round towards negative infinity.
  • HALF_DOWN- Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
  • HALF_EVEN- Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
  • HALF_UP- Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
  • UNNECESSARY - Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
  • UP- Rounding mode to round away from zero.

Here is a summary table showing the results of these rounding operations for all rounding modes.

Summary of Rounding Operations Under Different Rounding Modes
Result of rounding input to one digit with the given rounding mode
Input Number UP DOWN CEILING FLOOR HALF_UP HALF_DOWN HALF_EVEN UNNECESSARY
5.5 6 5 6 5 6 5 6 throw ArithmeticException
2.5 3 2 3 2 3 2 2 throw ArithmeticException
1.6 2 1 2 1 2 2 2 throw ArithmeticException
1.1 2 1 2 1 1 1 1 throw ArithmeticException
1.0 1 1 1 1 1 1 1 1
-1.0 -1 -1 -1 -1 -1 -1 -1 -1
-1.1 -2 -1 -1 -2 -1 -1 -1 throw ArithmeticException
-1.6 -2 -1 -1 -2 -2 -2 -2 throw ArithmeticException
-2.5 -3 -2 -2 -3 -3 -2 -2 throw ArithmeticException
-5.5 -6 -5 -5 -6 -6 -5 -6 throw ArithmeticException

Reference- https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html

Java BigDecimal Examples

In most of the cases conventional logic is to have a scale of 2 (2 digits after the decimal) and rounding up if the digit after the scale is >= 5.

BigDecimal bd1 = new BigDecimal("23.1256");
System.out.println("bd1 " + bd1.setScale(2, RoundingMode.HALF_UP).toString());

Here scale is set to 2 and digit after the 2 decimal digits is 5 so the last digit(after scaling) will be rounded up and the output is 23.13.

BigDecimal bd1 = new BigDecimal("23.1236");
System.out.println("bd1 " + bd1.setScale(2, RoundingMode.HALF_UP).toString());

Here digit after the 2 decimal digits is 3 (less than 5) so the last digit(after scaling) will not be rounded up and the output is 23.12.

BigDecimal bd1 = new BigDecimal("-15.567");
System.out.println("bd1 " + bd1.setScale(2, RoundingMode.HALF_UP).toString());

Same logic applies to negative numbers too so here the output is -15.57.

Features of BigDecimal in Java

  1. No Overloaded operators– In Java arithmetic operators (+, -, *, /) are not permitted with objects so these operators are not used with BigDecimal numbers, you will have to use method calls instead. BigDecimal class has methods add, subtract, multiply and divide for the arithmetic operations.
    BigDecimal bd1 = new BigDecimal("15.567");
    
    BigDecimal result = BigDecimal.valueOf(68).multiply(bd1);
    System.out.println("result " + result.toString());
    

    Output

    result 1058.556
    
  2. Use compareTo() to compare BigDecimals not equals()- Don’t use equals method to compare 2 BigDecimal numbers as this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method.
    BigDecimal bd1 = new BigDecimal("2.00");
    BigDecimal bd2 = new BigDecimal("2.0");
    System.out.println("bd1 equals bd2 - " + bd1.equals(bd2));
    

    Output

    bd1 equals bd2 - false
    

    You should use compareTo() method instead, BigDecimal class implements comparable and provides its own implementation of compareTo() method.

    Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method.

    For a statement like bd1.compareTo(bd2) this method returns -

    • -1 if bd1 is less than bd2.
    • 0 if both are equal.
    • 1 if bd1 is greater than bd2.
    BigDecimal bd1 = new BigDecimal("2.00");
    BigDecimal bd2 = new BigDecimal("2.0");
    System.out.println("bd1 compareTo bd2 - " + bd1.compareTo(bd2));
    

    Output

    bd1 compareTo bd2 - 0
    
  3. BigDecimals are immutable- BigDecimal objects are immutable, so any operation won't result in the original object being modified. You can take example of the setScale method, usual convention is that methods named setX mutate field X. But setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

Points to remember

  • The BigDecimal class should be used when we need accurate precision rather than approximation.
  • BigDecimal class in Java provide methods to provide scale and rounding options for the result.
  • BigDecimal class extends Number class like other wrapper classes.
  • BigDecimal class has specific methods for addition, subtraction, multiplication, and division.
  • BigDecimal objects are immutable.
  • With BigDecimal object creation overhead is involved so operations are slightly slower compared to primitive types.

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. BigInteger in Java With Examples
  2. Encapsulation in Java
  3. Constructor overloading in Java
  4. final Keyword in Java With Examples
  5. static Keyword in Java With Examples

You may also like-

  1. Volatile Keyword in Java With Examples
  2. Is String Thread Safe in Java
  3. AutoBoxing and UnBoxing in Java
  4. Generic Class, Interface And Generic Method in Java
  5. Lambda Expressions in Java 8
  6. How to Sort ArrayList of Custom Objects in Java
  7. Comparing Enum to String in Java
  8. Convert float to String in Java