Home »
Java »
Java Reference »
Java BigDecimal Class
Java BigDecimal plus() Method with Example
BigDecimal Class plus() method: Here, we are going to learn about the plus() method of BigDecimal Class with its syntax and example.
Submitted by Preeti Jain, on May 05, 2020
BigDecimal Class plus() method
Syntax:
public BigDecimal plus();
public BigDecimal plus(MathContext ma_co);
- plus() method is available in java.math package.
- plus() method is used to get the value with (+) representation of this BigDecimal.
- plus(MathContext ma_co) method is used to get the value with (+) representation of this BigDecimal along with rounding based on the given MathContext settings.
- These methods may throw an exception at the time of + representation of an object.
ArithmeticException: This exception may throw when the result is not accurate and set the rounding mode "UNNECESSARY".
- These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.
Parameter(s):
-
In the first case, plus(),
- It does not accept any parameter.
-
In the first case, plus(MathContext ma_co),
- MathContext ma_co – represents the context setting to use in rounding.
Return value:
In both the cases, the return type of the method is BigDecimal,
- In the first case, it returns the plus value of this BigDecimal.
- In the second case, it returns the plus value of this BigDecimal. with rounding based on the given context setting.
Example:
// Java program to demonstrate the example
// of plus() method of BigDecimal
import java.math.*;
public class PlusOfBD {
public static void main(String args[]) {
// Initialize two variables val1,
// val2
String val1 = "-10.30";
int val2 = 4;
// Initialize two BigDecimal objects and
// one MathContext
BigDecimal b_dec1 = new BigDecimal(val1);
BigDecimal b_dec2 = new BigDecimal(val2);
MathContext ma_co = new MathContext(2, RoundingMode.CEILING);
System.out.println("plus(): ");
// returns the plus representation of this BigDecimal
// like (+ b_dec2)
BigDecimal plus = b_dec2.plus();
System.out.println("b_dec2.plus(): " + plus);
System.out.println(" ");
System.out.println("plus(MathContext): ");
// returns the plus representation of this BigDecimal
// (+b_dec1) and return the result based on the given
// context settings
plus = b_dec1.plus(ma_co);
System.out.println("b_dec1.plus(ma_co): " + plus);
}
}
Output
plus():
b_dec2.plus(): 4
plus(MathContext):
b_dec1.plus(ma_co): -10