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. Java Stream API Tutorial
  2. Java Stream - limit() With Examples
  3. collect() Method And Collectors Class in Java Stream API
  4. Java Stream - Convert Stream to List
  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

Sunday, September 12, 2021

How to Sort ArrayList of Custom Objects in Java

In the post How to sort ArrayList in Java you have already seen how to sort an ArrayList of Strings, Integers or Dates. In this post we'll see how to sort an ArrayList of custom objects in Java.

In order to sort an ArrayList of objects you can use sort() method provided by the Collections class, which takes List as an argument. Note that there are two overloaded variants of the sort() method.

  • sort(List<T> list)- If you are using this method to sort ArrayList of objects, the class whose objects are stored in the List should implement Comparable interface. If the class whose objects are stored in the List doesn’t implement the Comparable interface and you pass that list as an argument in sort(List<T> list) method that will result in compile time error. See example.
  • sort(List<T> list, Comparator<? super T> c)- This is another overloaded sort() method where you can pass your own Comparator along with the List that has to be sorted. See example.

Let’s see examples using both Comparable and Comparator interfaces to sort ArrayList of objects in Java.

Sorting ArrayList containing custom objects using Comparable

Let's say you have an Employee class. Objects of this Employee class are stored in an ArrayList and you want to sort it on both first name and last name.

public class Employee implements Comparable<Employee> {
  private String lastName;
  private String firstName;
  private String empId;
  private int age;
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getEmpId() {
    return empId;
  }
  public void setEmpId(String empId) {
    this.empId = empId;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public String toString() {    
    return getFirstName() + " " + getLastName() + " " + getAge() + " " + getEmpId();
  }
  @Override
  public int compareTo(Employee o) {
    int firstCmp = this.getFirstName().compareTo(o.getFirstName());
    return firstCmp != 0 ? firstCmp :  this.getLastName().compareTo(o.getLastName());
  }
}
Class where sorting of the list will be done.
public class SortObjectList {
  public static void main(String[] args) {
    List<Employee> empList = new ArrayList<Employee>();
    // Storing elements in the arraylist
    empList.add(getData("E001", "Mishra", "Pyaremohan", 35));
    empList.add(getData("E002", "Smith", "John", 45));
    empList.add(getData("E003", "Sharma", "Ram", 23));
    empList.add(getData("E004", "Mishra", "Pyaremohan", 60));
    empList.add(getData("E005", "Caroll", "Eva", 32));
    empList.add(getData("E003", "Tiwari", "Ram", 23));
    
    System.out.println("Original List");
    for(Employee emp : empList){
      System.out.println("" + emp);
    }
    // Sorting the list
    Collections.sort(empList);
    
    System.out.println("Sorted List");
    for(Employee emp : empList){
      System.out.println("" + emp);
    }    
  }
                
  // Stub method 
  private static Employee getData(String empId, String lastName, 
      String firstName, int age){
    Employee employee = new Employee();
    employee.setEmpId(empId);
    employee.setLastName(lastName);
    employee.setFirstName(firstName);
    employee.setAge(age);
    return employee;
  }    
}

Output

Original List
Pyaremohan Mishra 35 E001
John Smith 45 E002
Ram Sharma 23 E003
Pyaremohan Mishra 60 E004
Eva Caroll 32 E005
Ram Tiwari 23 E003
Sorted List
Eva Caroll 32 E005
John Smith 45 E002
Pyaremohan Mishra 35 E001
Pyaremohan Mishra 60 E004
Ram Sharma 23 E003
Ram Tiwari 23 E003

Some of the points to note about this program are-

  1. Employee class whose objects are stored in the ArrayList implements the Comparable interface and provides implementation of the compareTo() method.
  2. compareTo() method implementation provides logic for elements ordering.
  3. Collections.sort() method is used to sort the List.

Sorting ArrayList containing custom objects using Comparator

In the above example Employee class implements the compareTo() method, where first name takes precedence over last name. So this is the natural ordering for sorting the Employee class objects.

Now in case you want to sort using the following order-

If names are same, they are sorted on the basis of age in descending order.

If you have to sort using this rule you can’t use the already implemented compareTo() method of the Employee class. Other scenario is what if you want to sort some objects that don't implement Comparable?

To sort an ArrayList of objects in Java using any of the above mentioned scenarios, you'll need to provide a Comparator. An object of Comparator class is passed as a parameter in sort() method, this Comparator class object encapsulates an ordering.

  • Refer Difference between Comparable and Comparator to see the differences between the two interfaces Comparable and Comparator.
  • Comparator interface consists of a single method compare().

    public interface Comparator<T> {
      int compare(T o1, T o2);
    }
    

    The compare method compares its two arguments, returning a negative integer, 0, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second. If either of the arguments has an inappropriate type for the Comparator, the compare method throws a ClassCastException.

    So the case where sorting logic is - if names are same, they are sorted on the basis of age in descending order you have to write a comparator class which will implement Comparator interface and provide implementation for the compare method. You will also have to use that variant of the sort() method where you can pass Comparator.

    public class SortObjectList {
      public static void main(String[] args) {
        List<Employee> empList = new ArrayList<Employee>();
        // Storing elements in the arraylist
        empList.add(getData("E001", "Mishra", "Pyaremohan", 35));
        empList.add(getData("E002", "Smith", "John", 45));
        empList.add(getData("E003", "Sharma", "Ram", 23));
        empList.add(getData("E004", "Mishra", "Pyaremohan", 60));
        empList.add(getData("E005", "Caroll", "Eva", 32));
        empList.add(getData("E003", "Tiwari", "Ram", 23));
        
        System.out.println("Original List");
        for(Employee emp : empList){
          System.out.println("" + emp);
        }
        // Sorting the list
        Collections.sort(empList, new MyComparator());
                
        System.out.println("Sorted List");
        for(Employee emp : empList){
          System.out.println("" + emp);
        }    
      }
                
      // Stub method 
      private static Employee getData(String empId, String lastName, String firstName, int age){
        Employee employee = new Employee();
        employee.setEmpId(empId);
        employee.setLastName(lastName);
        employee.setFirstName(firstName);
        employee.setAge(age);
        return employee;
      }       
    }
    
    class MyComparator implements Comparator<Employee>{
      @Override
      public int compare(Employee o1, Employee o2) {
        int firstCmp = o1.getFirstName().compareTo(o2.getFirstName());
        if(firstCmp == 0){
          int lastCmp = o1.getLastName().compareTo(o2.getLastName());
          if(lastCmp == 0){
            return (o2.getAge() < o1.getAge() ? -1 :
                   (o2.getAge() == o1.getAge() ? 0 : 1));
          }else{
            return lastCmp;
          }
            
        }else{
          return firstCmp;
        }        
      }    
    }
    

    Output

    Original List
    Pyaremohan Mishra 35 E001
    John Smith 45 E002
    Ram Sharma 23 E003
    Pyaremohan Mishra 60 E004
    Eva Caroll 32 E005
    Ram Tiwari 23 E003
    Sorted List
    Eva Caroll 32 E005
    John Smith 45 E002
    Pyaremohan Mishra 60 E004
    Pyaremohan Mishra 35 E001
    Ram Sharma 23 E003
    Ram Tiwari 23 E003
    

    Here it can be seen that the name which is same is sorted by age in descending order. The logic for sorting is in the compare() method.

    That's all for this topic How to Sort ArrayList of Custom Objects in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


    Related Topics

    1. How ArrayList Works Internally in Java
    2. Difference Between ArrayList And LinkedList in Java
    3. How to Remove Elements From an ArrayList in Java
    4. How and Why to Synchronize ArrayList in Java
    5. Java Collections Interview Questions And Answers

    You may also like-

    1. How HashMap Works Internally in Java
    2. Difference Between ArrayList And CopyOnWriteArrayList in Java
    3. Thread Priority in Java Multi-Threading
    4. final Vs finally Vs finalize in Java
    5. Executor And ExecutorService in Java With Examples
    6. Java DelayQueue With Examples
    7. Why main Method static in Java
    8. Java Reflection API Tutorial

    Saturday, September 11, 2021

    Armstrong Number or Not Java Program

    Java program to check if a given number is an Armstrong number or not can be termed as a fresher level interview question. An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

    As Example- If we take 371, it is an Armstrong number as the number of digits here is 3, so

    371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

    Another Example is 9474, here the number of digits is 4, so

    9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

    And obviously 0 and 1 are also Armstrong number.

    Check given number Armstrong number or not

    So let's write a Java program to check whether a given number is an Armstrong number or not. How does the program work is explained after the program.

    import java.util.Scanner;
    
    public class ArmstrongNumber {
      public static void main(String[] args) {
        System.out.println("Please enter a number : ");
        Scanner scanIn = new Scanner(System.in);
        int scanInput = scanIn.nextInt();
        boolean isArmstrong = checkForArmstrongNo(scanInput);
        if(isArmstrong){
         System.out.println(scanInput + "  is an Armstrong number");
        }else{
         System.out.println(scanInput + " is not an Armstrong number"); 
        }
        scanIn.close();
      }
     
      private static boolean checkForArmstrongNo(int number){
        // convert number to String
        String temp = number + "";
        int numLength = temp.length();
        int numCopy = number;
        int sum = 0;
        while(numCopy != 0 ){
          int remainder = numCopy % 10;
          // using Math.pow to get digit raised to the power
          // total number of digits
          sum = sum + (int)Math.pow(remainder, numLength);
          numCopy = numCopy/10;
        }
        System.out.println("sum is " + sum );
        return (sum == number) ? true : false;
      }
    }
    

    Some outputs-

    Please enter a number : 
    125
    sum is 134
    125 is not an Armstrong number
    
    Please enter a number : 
    371
    sum is 371
    371  is an Armstrong number
    
    Please enter a number : 
    54748
    sum is 54748
    54748  is an Armstrong number
    

    Armstrong number Java program explanation

    Here the input is taken from the user, that number is converted to String just to get the length of the number. Logic here is to get one digit of the number at a time, starting from the last digit, get the value of that number power raised to the number of the digits and then divide the number by 10 to reduce the number by one digit.
    Repeat the process for all the digits in the given number. Keep adding the values to get the final result. Compare the result with the original number to check whether given number is Armstrong number or not.

    That's all for this topic Armstrong Number or Not 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. Check if Given String or Number is a Palindrome Java Program
    2. How to Display Pyramid Patterns in Java
    3. Java Program to Display Prime Numbers
    4. Factorial program in Java
    5. Write to a File in Java

    You may also like-

    1. Find Duplicate Elements in an Array Java Program
    2. Difference Between Two Dates in Java
    3. How to Create Password Protected Zip File in Java
    4. Spring Component Scan Example
    5. Java Collections Interview Questions And Answers
    6. Java Abstract Class and Abstract Method
    7. Switch Case Statement in Java With Examples
    8. Java SynchronousQueue With Examples

    Friday, September 10, 2021

    Java Automatic Numeric Type Promotion

    In Java, numeric promotion happens automatically in case of primitive types when those primitives are used in an expression.

    As example

    byte a = 100;
    byte b = 50;
    int i = a * b;
    

    In the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these type of situations Java will automatically promote the byte, short or char to int when evaluating an expression. Also, note that the result is assigned to an int variable i without any explicit casting as the result was already an int.

    Rules for Type promotion in Java

    There are several type promotion rules in Java that are followed while evaluating expressions-

    • All byte, short and char values are promoted to int.
    • If any operand is long then the expression result is long. i.e. whole expression is promoted to long.
    • If any operand is a float then the expression result is float. i.e. whole expression is automatically promoted to float.
    • If any operand is a double then the expression result is double. i.e. whole expression is promoted to double in Java.

    Let's see some Java examples depicting the numeric promotion rules in Java-

    1- When one of the operand is double.
    public class PromotionExample {
     public static void main(String[] args) {
      int i = 30;
      double d = 2.5;
      double result = i * d;
      System.out.println("Result is- " + result);
     }
    }
    

    Output

    Result is- 75.0
    

    In the code one of the operand is int and another operand is double so the expression result has to be double because of the numeric promotion.

    2- When one of the operand is float.
    public class PromotionExample {
     public static void main(String[] args) {
      short s = 4;
      int i = 30;
      float f = 6.75f;
      float result = (s+i) * f;
      System.out.println("Result is- " + result);
     }
    }
    

    Output

    Result is- 229.5
    

    In the code one of the operand is float so the whole expression is promoted to float.

    3- Trying to assign the result to int when one of the operand is float.
    automatic numeric type promotion in Java

    As shown in the code, since one of the value is float so the result should also be float and that's what the compiler is complaining about here.

    Problems because of automatic type promotion

    Sometimes automatic numeric promotion in Java may cause confusing compilation problems. Let's see it with an example-

    automatic numeric type promotion

    Here byte b has the value 2. Again I am trying to assign (b * 2) to b which is with in the range of byte (-128 to 127) but compiler complains "Can't convert from int to byte". This error is there because the byte is automatically converted to int at the time of evaluating the expression. If it has to be assigned to a byte then explicit type casting is required.

    b=(byte)b*2;

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

    >>>Return to Java Basics Tutorial Page


    Related Topics

    1. Access Modifiers in Java - Public, Private, Protected and Default
    2. Interface in Java With Examples
    3. Constructor in Java
    4. static Keyword in Java With Examples
    5. Core Java Basics Interview Questions And Answers

    You may also like-

    1. Inheritance in Java
    2. Marker Interface in Java
    3. static Import in Java With Examples
    4. Covariant Return Type in Java
    5. Varargs (Variable-length Arguments) in Java
    6. Java Exception Handling Tutorial
    7. Lambda Expressions in Java 8
    8. How HashMap Works Internally in Java

    How to Sort Elements in Different Order in Java TreeSet

    By default elements in TreeSet are sorted using natural ordering of the elements. If you want to sort a TreeSet in Java using different order than the natural order like in descending order or reverse order then you need to provide your own Comparator at Set creation time.

    Let's see a Java example where TreeSet is sorted in descending order rather than the natural ordering (which is ascending in case of String).

    public class TreeSetDemo {
      public static void main(String[] args) {
        // Providing custom compartor
        Set<String> citySet = new TreeSet<String>(
          new CityComparator());
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add("Bangalore");
        citySet.add("Chennai");
        citySet.add("Hyderabad");
        
        // Iterating the Set
        for(String str : citySet){
          System.out.println("City Name - " + str);
        }
      }
    }
    
    // Comparator class
    class CityComparator implements Comparator<String>{
      @Override
      public int compare(String str1, String str2) {
        return str2.compareTo(str1);
      }    
    }
    

    Output

    City Name - Mumbai
    City Name - Hyderabad
    City Name - Delhi
    City Name - Chennai
    City Name - Bangalore
    

    Here note that a Comparator implementation is provided which reverses the sorting order. That Comparator is specified at the set creation time in a constructor.

    That's all for this topic How to Sort Elements in Different Order in Java TreeSet. 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 Iterate a HashMap of ArrayLists of String in Java
    2. How to Sort ArrayList in Java
    3. How to Sort ArrayList of Custom Objects in Java
    4. Count Number of Times Each Character Appears in a String Java Program
    5. Difference Between Comparable and Comparator in Java

    You may also like-

    1. Convert String to double in Java
    2. Compress And Decompress File Using GZIP Format in Java
    3. Remove Duplicate Elements From an Array in Java
    4. LinkedHashSet in Java With Examples
    5. Synchronization in Java - Synchronized Method And Block
    6. Difference Between Checked And Unchecked Exceptions in Java
    7. Polymorphism in Java
    8. Dependency Injection in Spring Framework

    Thursday, September 9, 2021

    Why Class Name and File Name Should be Same in Java

    When we start learning Java and write our first "Hello World" program, there are two things that stand out.

    • File name and class name should be same in Java.
    • Main method signature- The main method signature must be public static void main(String[] args)

    Refer Why main Method static in Java to understand the requirement why main method should be static.

    Here we'll talk about the requirement that File name and class name should be same in Java. Let's be clear on one point; this requirement is not mandatory unless until there is a public class in the file.

    If there is a class with access modifier as public in the file then it has to be saved with the same file name.

    File name and class name same in Java - Public class

    Let's see the case when we have a public class.

    public class Test {
      public static void main(String[] args) {
        System.out.println("This is a test class");
      }
    }
    

    If we save it as Thetest.java then we'll get an error while trying to compile it.

    class name and file name same in Java

    It can be seen how compiler complains about having the public class Test and how it should be declared as Test.java.

    Now if we save the class as Test.java then it compiles and runs just fine.

    class name and file name should be same

    File name and class name same in Java - Without public class

    Now let's take an example when there is no public class-

    class FinalClass{
      String a;
      final void finalMethod(){
    
      }
    }
    
    class FinalClassDemo {
      public static void main(String[] args) {
    
      }
    }
    

    I have this file with 2 classes and none of them is public, now I can save it giving any name, let's say I saved it as ABC.java. Yes, it is possible if there is no class with access modifier as public. But that is only half of the truth! When this java file is compiled it will create 2 classes-

    FinalClassDemo.class
    FinalClass.class
    

    It can be seen that even if the file name is different compiled classes have the same name as the class names.

    Now if we have to run it then we have to use-

    java FinalClassDemo

    This shows that at compile time file name may be different from the class name in Java (provided there is no public class in the file) but at the run time it has to be same.

    Why these restrictions

    Now let’s try to see why this restriction to have file name same as class name for public class in Java? One scenario which I can think of where it makes sense is when you have a Java file with one public class and other classes too. You must be knowing that you can have a file in Java with at most one public class and other classes with default access (package-private).

    Let’s see it with an example, suppose I have a java file as follows–

    public class Test{
     public static void main(String[] args) {
      System.out.println("in test class");
      //Test1 t = new Test1();
     }
    }
    
    class Test1{
     public void display(){
      System.out.println("in Test1 class");
     }
    }
    
    class Test2{
     public void display(){
      System.out.println("in Test2 class");
     }
    }
    

    Here we have one public class Test and two other classes Test1 and Test2 having default access. Now, let’s say we don’t have the restriction to save this file as Test.java (which is the name of the public class). So, you saved it as ABC.java. Now at the time of compilation (javac ABC.java) compiler has to scan the whole file structure to find out the public class which is surely an overhead and easily avoidable by saving the Java file as Test.java.

    Coming to another point that a class with default access can be saved with different name but the compiled .class file will have the same name as the class name.

    Here again let’s try to understand it with an example–

    Let’s say I have one class Test1 with Default access and I have saved it as XYZ.java

    class Test1 {
     public void display(){
      System.out.println("in Test1 class");
     }
    }
    

    And another class where Test1 class object is created.

    public class Test{
     public static void main(String[] args) {
      System.out.println("in Test class");
      Test1 t = new Test1();
      t.display();
     }
    }
    

    In this class when you are creating the object of class Test1 you are using the name of the class (Test1 t = new Test1();) not the saved filename (XYZ.java).

    Test will look for a .class file Test1 when it has to load Test1 class. If .class file also won’t have the same name as the class then JVM must maintain some internal structure to have that mapping from saved file name to class name and refer that mapping every time to load the correct class. That again is an overhead so better to have the easy solution to generate at least the .class file with the same name as class name even in the case of class which is not public.

    Well the gist is better to always have the same name for the java file as the class name. For academic purpose, you may fiddle with the file name Vs class name to see what is permitted and what is restricted.

    Points to note-

    • If there is no public class then file name may be different from the class name in Java.
    • In case there is a public class then it is enforced that the file name is same as the public class.
    • Even, in the case, where the file name is different, after compilation .class files have the same name as the class names.
    • Having the same name as class name is how the JVM will know which class to load and where to look for entry point (main method).

    Recommendations for learning (Udemy Courses)

    1. Java Programming Masterclass Course
    2. Java In-Depth: Become a Complete Java Engineer!
    3. Spring Framework Master Class Course
    4. Complete Python Bootcamp Course
    5. Python for Data Science and Machine Learning

    That's all for this topic Why Class Name and File Name Should be Same in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

    >>>Return to Java Basics Tutorial Page


    Related Topics

    1. Java Pass by Value or Pass by Reference
    2. What are JVM, JRE and JDK in Java
    3. Object in Java
    4. Just In Time Compiler (JIT) in Java
    5. Core Java Basics Interview Questions And Answers

    You may also like-

    1. Class in Java
    2. final Keyword in Java With Examples
    3. Automatic Numeric Type Promotion in Java
    4. How HashMap Works Internally in Java
    5. Difference between ArrayList and CopyOnWriteArrayList in Java
    6. Functional Interfaces in Java
    7. Fail-Fast Vs Fail-Safe Iterator in Java
    8. String in Java Tutorial

    Wednesday, September 8, 2021

    Constructor Chaining in Java

    When we have a hierarchy of classes (in case of inheritance) it is important to know the order in which constructors for the classes are executed. That order is known as constructor chaining in Java.

    There is also concept of constructor overloading in Java where, with in the same class, there are multiple constructors with different signatures.

    How does Constructor Chaining work in Java

    If class A is superclass and there is a child class Class B. In that case if a new instance of class B is created what is the order in which constructors of Class A and Class B are executed?

    Answer is; the order followed is from superclass to subclass.

    Subclass can call a constructor in the superclass inside one of the subclass constructors explicitly using super(). In that case super() must be the first statement in a subclass constructor. If super() is not used then the default no-arg constructor of each superclass will be executed implicitly. Note that the order remains same (from superclass to subclass ) whether or not super() is used.

    Monday, September 6, 2021

    Find Largest And Smallest Number in a Given Array Java Program

    This post is about writing a Java program to find the largest and the smallest number in a given array or it can also be rephrased as- Find the maximum and minimum number in a given array.

    Condition here is that you should not be using any inbuilt Java classes (i.e. Arrays.sort) or any data structure.

    Solution to find the largest and the smallest number in an array

    Logic here is to have two variables for maximum and minimum numbers, initially assign the element at the first index of the array to both the variables.

    Then iterate the array and compare each array element with the max number if max number is less than the array element then assign array element to the max number.

    If max number is greater than the array element then check if minimum number is greater than the array element, if yes then assign array element to the minimum number.

    Java code

    public class FindMaxMin {
     public static void main(String[] args) {
      int numArr[] = {56, 36, 48, 49, 29, 458, 56, 4, 7};
      
      // start by assigning the first array element
      // to both the variables
      int maxNum = numArr[0];
      int minNum = numArr[0];
      // start with next index (i.e. i = 1)
      for(int i = 1; i < numArr.length; i++){
       if(maxNum < numArr[i]){
        maxNum = numArr[i];
       }else if(minNum > numArr[i]){
        minNum = numArr[i];
       }  
      }
      System.out.println("Largest number -  " 
         + maxNum + " Smallest number - " + minNum);
     }
    }
    

    Output

    Largest number -  458 Smallest number - 4
    

    That's all for this topic Find Largest And Smallest Number in a Given 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 Largest and Second Largest Number in Given Array Java Program
    2. How to Find Common Elements Between Two Arrays Java Program
    3. Find Duplicate Elements in an Array Java Program
    4. How to Remove Elements From an Array Java Program
    5. Matrix Multiplication Java Program

    You may also like-

    1. Java Program to Find The Longest Palindrome in a Given String
    2. Find All Permutations of a Given String Java Program
    3. How to Convert Date to String in Java
    4. How to Read File From The Last Line in Java
    5. Creating Tar File And GZipping Multiple Files in Java
    6. How to Remove Elements From an ArrayList in Java
    7. Executor And ExecutorService in Java With Examples
    8. Java Reflection API Tutorial

    Sunday, September 5, 2021

    throw Statement in Java Exception Handling

    It is possible for a Java program to throw an exception explicitly, that is done using the throw statement in Java.

    The flow of execution, with in a method where throw is used, stops immediately after the throw statement; statements after the throw statement are not executed.

    General form of throw in Java

    General form of throw statement is-

    throw throwableObject;
    
    Here, throwableObject should be an object of type Throwable or any subclass of it.

    We can get this throwableObject in 2 ways-

    • By using the Exception parameter of catch block.
    • Create a new one using the new operator.

    Java example program using throw keyword

    public class ThrowDemo {
    
     public static void main(String[] args) {
      ThrowDemo throwDemo = new ThrowDemo();
      try{
        throwDemo.displayValue();
      }catch(NullPointerException nExp){
         System.out.println("Exception caught in catch block of main");
         nExp.printStackTrace();;
      }
     }
     
     public void displayValue(){
      try{
        throw new NullPointerException();   
      }catch(NullPointerException nExp){
         System.out.println("Exception caught in catch block of displayValue");
         throw nExp;
      }
     }
    }
    

    Note that in this program throw keyword is used at two places. First time, in the try block of displayValue() method, it uses the new operator to create an instance of type throwable. Second time it uses the parameter of the catch block.

    throw statement helps in preserving loose coupling

    One of the best practices for the exception handling is to preserve loose coupling. According to that an implementation specific checked exception should not propagate to another layer.

    As Example SQL exception from the DataAccessCode (DAO layer) should not propagate to the service (Business) layer. The general practice in that case is to convert database specific SQLException into an unchecked exception and throw it.

    catch(SQLException ex){
        throw new RuntimeException("DB error", ex);
    }
    

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


    Related Topics

    1. Difference Between throw And throws in Java
    2. Exception Propagation in Java Exception Handling
    3. Try-With-Resources in Java With Examples
    4. Creating Custom Exception Class in Java
    5. Java Exception Handling Interview Questions And Answers

    You may also like-

    1. Fail-Fast Vs Fail-Safe Iterator in Java
    2. How HashMap Works Internally in Java
    3. finalize() Method in Java
    4. Java Pass by Value or Pass by Reference
    5. Why Class Name And File Name Should be Same in Java
    6. Java CyclicBarrier With Examples
    7. Lambda Expressions in Java 8
    8. Count Number of Times Each Character Appears in a String Java Program

    Saturday, September 4, 2021

    BeanFactoryAware Interface in Spring Framework

    If a class implements org.springframework.beans.factory.BeanFactoryAware interface, then the class bean is provided with a reference to their owning BeanFactory. BeanFactoryAware interface has a single method setBeanFactory(BeanFactory beanFactory).

    BeanFactoryAware interface in Spring

    public interface BeanFactoryAware extends Aware {
      void setBeanFactory(BeanFactory beanFactory) throws BeansException
    }
    

    As you see there is one callback method setBeanFactory that supplies the owning factory to a bean instance.

    Bean implementing BeanFactoryAware interface can look up collaborating beans via the factory (Dependency Lookup). However, in general you should not use it, because it couples the code to Spring and does not follow the Inversion of Control style, where most beans will choose to receive references to collaborating beans via corresponding bean properties or constructor arguments i.e. Dependency Injection.

    Spring BeanFactoryAware interface example

    As already stated this interface should not be used but one scenario where it can help is having many beans of the same type and deciding at the run time which specific bean to use.

    For example– Suppose you have IPayment interface and two implementing classes CardPayment and CashPayment. Based on the user’s choice appropriate bean should be called to execute payments. In this scenario you can use BeanFactoryAware interface to do a dependency lookup and load the required bean.

    Let’s see Java code for all the classes.

    IPayment interface

    public interface IPayment{
     void executePayment();
    }
    

    CardPayment.java

    public class CardPayment implements IPayment{
     public void executePayment() {
      System.out.println("Perform Card Payment "); 
     }
    }
    

    CashPayment.java

    public class CashPayment implements IPayment{
     
     public void executePayment() {
      System.out.println("Perform Cash Payment "); 
     }
    }
    

    IPayService interface

    public interface IPayService{
     void performPayment(String paymentType);
    }
    

    Class implementing BeanFactoryAware interface

    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.BeanFactoryAware;
    
    public class PayServiceImpl implements IPayService, BeanFactoryAware{
     
     private BeanFactory beanFactory;
     private IPayment payment;
     //private int amount;
     
     public void performPayment(String paymentType) {
      System.out.println("performPayment Method called");
      payment = (IPayment)beanFactory.getBean(paymentType);
      payment.executePayment();
     }
     
     @Override
     public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
      this.beanFactory = beanFactory;
     }
    }
    

    In the class you can see setBeanFactory() method is implemented, also notice the performPayment() method where the beanFactory is used to load the required bean based on the paymentType parameter.

    XML configuration

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
        <bean id="cash" class="org.netjs.exp.Spring_Example.CashPayment" />
        <bean id="card" class="org.netjs.exp.Spring_Example.CardPayment" />
       
        <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl">
        </bean>
      
    </beans>
    

    Here you can see that there is no bean injected as dependency in the bean definition of payServiceBean. As you are going to get the bean by dependency lookup in performPayment() method.

    You can use the following class to run and test the code.

    public class App {
      public static void main( String[] args ){
        AbstractApplicationContext context = new ClassPathXmlApplicationContext
           ("appcontext.xml");
    
        IPayService payBean = (IPayService)context.getBean("payServiceBean");
       
        payBean.performPayment("cash");
       
        payBean.performPayment("card");
    
        context.registerShutdownHook(); 
      }  
    }
    

    Output

    performPayment Method called
    Perform Cash Payment 
    performPayment Method called
    Perform Card Payment 
    

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

    >>>Return to Spring Tutorial Page


    Related Topics

    1. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
    2. Spring Bean Life Cycle
    3. @Required Annotation in Spring Framework
    4. registerShutdownHook() Method in Spring Framework
    5. Autowiring in Spring Using @Autowired and @Inject Annotations

    You may also like-

    1. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
    2. How to Read Properties File in Spring Framework
    3. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
    4. Java Reflection API Tutorial
    5. Java Stream API Examples
    6. How LinkedList Class Works Internally in Java
    7. Java Lambda Expressions Interview Questions And Answers
    8. Constructor Chaining in Java

    Friday, September 3, 2021

    BeanFactoryPostProcessor in Spring Framework

    BeanFactoryPostProcessor interface in Spring resides in org.springframework.beans.factory.config package. BeanFactoryPostProcessor implementation is used to read the configuration metadata and potentially change it before beans are instantiated by IOC container.

    You can configure multiple BeanFactoryPostProcessors, you can also control the order in which these BeanFactoryPostProcessors execute by setting the order property. You can set the order property only if the BeanFactoryPostProcessor implements the Ordered interface.

    BeanFactoryPostProcessor interface in Spring

    BeanFactoryPostProcessor interface is a functional interface meaning it has a single abstract method, that method is postProcessBeanFactory() which you need to implement in order to custom modify the bean definitions. Note that when this method is called at that time all bean definitions will have been loaded, but no beans will have been instantiated yet. This allows for overriding or adding properties even to eager-initializing beans.

    @FunctionalInterface
    public interface BeanFactoryPostProcessor {
      void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 
        throws BeansException;
    }
    

    Usage of BeanFactoryPostProcessor in Spring

    The implementations of BeanFactoryPostProcessor interface are used by Spring framework itself. When you read from property files in Spring and configure the <context:property-placeholder> element that registers PropertySourcesPlaceholderConfigurer which implements BeanFactoryPostProcessor interface and set the properties there in the bean.

    Spring BeanFactoryPostProcessor example

    Here let’s have a simple example of BeanFactoryPostProcessor in Spring.

    The scenario is that you have set the properties in a property file for DB config but for a particular run you want to use the separate schema which is set up in such a way that all the otehr properties remain same except the url. Which means you want to override the url property of the DataSource and modify it so that you can connect to the new Schema.

    Though a better option would be to create separate Spring profiles and switch among those profiles but you can access bean definition and modify the value of the property using the BeanFactoryPostProcessor.

    db.properties file

    db.driverClassName=com.mysql.jdbc.Driver
    db.url=jdbc:mysql://localhost:3306/netjs
    db.username=root
    db.password=admin
    pool.initialSize=5
    

    XML configuration for the datasource

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
      <property name="driverClassName" value = "${db.driverClassName}" />
      <property name="url" value = "${db.url}" />
      <property name="username" value = "${db.username}" />
      <property name="password" value = "${db.password}" />
      <property name="initialSize" value = "${pool.initialSize}" /
    </bean>
    

    BeanFactoryPostProcessor implementation class

    import org.springframework.beans.BeansException;
    import org.springframework.beans.MutablePropertyValues;
    import org.springframework.beans.PropertyValue;
    import org.springframework.beans.factory.config.BeanDefinition;
    import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
    import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
    import org.springframework.core.Ordered;
    
    public class TestDBPostProcessor implements BeanFactoryPostProcessor, Ordered {
    
      @Override
      public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 
          throws BeansException {
        System.out.println("In postProcessBeanFactory");
        // Getting the dataSource bean
        BeanDefinition bd = beanFactory.getBeanDefinition("dataSource");
        if(bd.hasPropertyValues()){
          MutablePropertyValues pvs = bd.getPropertyValues();
          PropertyValue[] pvArray = pvs.getPropertyValues();
          for (PropertyValue pv : pvArray) {
            System.out.println("pv -- " + pv.getName());
            // changing value for url property
            if(pv.getName().equals("url")){
              pvs.add(pv.getName(), "jdbc:mysql://localhost:3306/TestSchema");
            }
          }
        } 
      }
      @Override
      public int getOrder() {
        // TODO Auto-generated method stub
        return 0;
      }
    }
    

    As you can see in the method postProcessBeanFactory() you can get the dataSource bean and modify the bean definition.

    To register the BeanFactoryPostProcessor add the following line in your configuration.

    <bean class="org.netjs.config.TestDBPostProcessor"  />
    

    Here is the method where I want to use the new schema.

    public List<Employee> findAllEmployees() {
      System.out.println("URL " + ((BasicDataSource)jdbcTemplate.getDataSource()).getUrl());
      return this.jdbcTemplate.query(SELECT_ALL_QUERY, (ResultSet rs) -> {
        List<Employee> list = new ArrayList<Employee>();  
        while(rs.next()){
          Employee emp = new Employee();
          emp.setEmpId(rs.getInt("id"));
          emp.setEmpName(rs.getString("name"));
          emp.setAge(rs.getInt("age"));
          list.add(emp);
        }
        return list;
      });
    }
    
    To run this example following code can be used.
    public class App {
      public static void main(String[] args) {      
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
         ("appcontext.xml");
        EmployeeDAO dao = (EmployeeDAO)context.getBean("employeeDAOImpl");  
        List<Employee> empList = dao.findAllEmployees();
        for(Employee emp : empList){
          System.out.println("Name - "+ emp.getEmpName() + " Age - " 
          + emp.getAge());
        }
        context.close();    
      }
    }
    

    Output

    Relevant lines from the console. 
    
    In postProcessBeanFactory
    pv -- driverClassName
    pv -- url
    pv -- username
    pv -- password
    pv – initialSize
    
    URL jdbc:mysql://localhost:3306/TestSchema
    

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

    >>>Return to Spring Tutorial Page


    Related Topics

    1. BeanPostProcessor in Spring Framework
    2. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
    3. BeanFactoryAware Interface in Spring Framework
    4. Injecting Inner Bean in Spring
    5. Circular Dependency in Spring Framework

    You may also like-

    1. Spring JdbcTemplate Insert, Update And Delete Example
    2. Spring JdbcTemplate With ResultSetExtractor Example
    3. Spring Expression Language (SpEL) With Examples
    4. Spring depends-on Attribute
    5. How HashMap Internally Works in Java
    6. Covariant Return Type in Java
    7. Spliterator in Java
    8. Replica Placement Policy in Hadoop Framework

    Thursday, September 2, 2021

    Race Condition in Java Multi-Threading

    Race condition in Java occurs in a multi-threaded environment when more than one thread try to access a shared resource (modify, write) at the same time. Since multiple threads try to race each other to finish executing a method thus the name race condition.

    Two points to note about race condition are-
    • It is safe if multiple threads are trying to read a shared resource as long as they are not trying to change it.
    • Multiple threads executing inside a method is not a problem in itself, problem arises when these threads try to access the same resource. Examples of shared resources are class variables, DB record in a table, writing in a file.

    Example of race condition in Java

    Let’s see one example of race condition in Java multi-threading, where we have a shared instance variable. Since there are three threads sharing the same object of the class so the field in the object is shared among the threads.