Explanation

You should replace it with:

d[i] = Double.valueOf(d.length - i);

From its Javadoc:

Deprecated.

It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance.

In general, valueOf is not forced to always return a new instance. It can utilize an internal cache and re-use values created before already, which makes it faster. For example if you create hundreds of 1.0.


Note

Is there a specific reason you are using a Double[] in the first place? If not, go for double[] instead. The primitives are much faster and have less memory overhead, compared to their object wrapper.

Then your code is just:

double[] d = new double[10];
for (int i = 0; i < d.length; i++)
    d[i] = d.length - i;

By the way, you should prefer to never omitt the curly braces. Even if your loop is just one line. This is a very common source for bugs that are hard to find.

Also, your variable naming is not very good. What is d? Try to give it a name that reflects what it actually means. Like ages if it stores person ages, for example. If you do not have something specific, maybe use values. That is already better than just d. Especially since it is plural, so it is clear that it is an array of multiple values.

double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
    values[i] = values.length - i;
}
Answer from Zabuzard on Stack Overflow
Top answer
1 of 2
21

Explanation

You should replace it with:

d[i] = Double.valueOf(d.length - i);

From its Javadoc:

Deprecated.

It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance.

In general, valueOf is not forced to always return a new instance. It can utilize an internal cache and re-use values created before already, which makes it faster. For example if you create hundreds of 1.0.


Note

Is there a specific reason you are using a Double[] in the first place? If not, go for double[] instead. The primitives are much faster and have less memory overhead, compared to their object wrapper.

Then your code is just:

double[] d = new double[10];
for (int i = 0; i < d.length; i++)
    d[i] = d.length - i;

By the way, you should prefer to never omitt the curly braces. Even if your loop is just one line. This is a very common source for bugs that are hard to find.

Also, your variable naming is not very good. What is d? Try to give it a name that reflects what it actually means. Like ages if it stores person ages, for example. If you do not have something specific, maybe use values. That is already better than just d. Especially since it is plural, so it is clear that it is an array of multiple values.

double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
    values[i] = values.length - i;
}
2 of 2
1

From Java 9 constructor(s) method(s) was Deprecated

Deprecated. It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance. Constructs a newly allocated Double object that represents the primitive double argument.

So replace with:

Double.valueOf(d.length - i)
🌐
Reddit
reddit.com › r/learnprogramming › stack overflow error after changing from double to bigdecimal in java/oop & polymorphism
r/learnprogramming on Reddit: Stack overflow error after changing from double to BigDecimal in Java/OOP & Polymorphism
January 5, 2022 -

Hi, So after changing in program the Gross and netSalary to BigDecimal, I got lots of errors and it is not clear how I can fix them. So first of all in the main, I want to print the sum of all netSalaries paid, however when I changed it to BigDecimal it is saying that I cannot apply '+' to java.math.BigDecimal and I really can't find a solution for it. Secondly, my getEmployeeGrossSalary in the superclass RegularEmployees is highlighted and it says that the method recurses infinitely and can only end by throwing an exception and when I run the program I am getting a stackOverflow error because I am calling it in the main to print all salaries from highest to lowest, so why was everything fine when the type was double and how can I fix these errors? Thanks in advance!

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RegularEmployees { //superclass
    protected double employeeGrossSalary;

    RegularEmployees(double employeeGrossSalary) {
        this.employeeGrossSalary = employeeGrossSalary;
    }
 public BigDecimal employeeNetSalary() {
        return new BigDecimal(this.employeeGrossSalary - (this.employeeGrossSalary * 0.1)).setScale(2,RoundingMode.DOWN);
    }
public BigDecimal getEmployeeGrossSalary() { //the method here is highlighted and it says that getEmployeeGrossSalary recurses infinitely and can only end by throwing an exception.
        return new
BigDecimal(String.valueOf(this.getEmployeeGrossSalary())).setScale(2,RoundingMode.DOWN);
    }
}

import java.math.BigDecimal;
import java.math.RoundingMode;

public class ManagerEmployees extends RegularEmployees { //Subclass
    private String managerDegree;

    ManagerEmployees(double employeeGrossSalary, String managerDegree) {
        super(employeeGrossSalary);
this.managerDegree = managerDegree;

public BigDecimal getEmployeeGrossSalary() {
        return new
BigDecimal(String.valueOf(this.getEmployeeGrossSalary())).setScale(2,RoundingMode.DOWN);
    } 
@Override
    public BigDecimal employeeNetSalary(){
        return new BigDecimal(super.employeeGrossSalary - (super.employeeGrossSalary * 0.1)).setScale(2, RoundingMode.DOWN);
    }
@Override
    public BigDecimal getEmployeeGrossSalary() {

        BigDecimal grossSalaryWithBonus = BigDecimal.valueOf(0.00);

        if (this.managerDegree.equals("BSc")) {
            grossSalaryWithBonus = new BigDecimal(super.employeeGrossSalary - (super.employeeGrossSalary * 0.1)).setScale(2, RoundingMode.DOWN);

        } else {

            if (this.managerDegree.equals("MSc")) {
                 grossSalaryWithBonus = new BigDecimal(super.employeeGrossSalary -(super.employeeGrossSalary * 0.2)).setScale(2, RoundingMode.DOWN);

            } else {

                if (this.managerDegree.equals("PhD")) {
                    grossSalaryWithBonus = new BigDecimal(super.employeeGrossSalary + (super.employeeGrossSalary * 0.35)).setScale(2, RoundingMode.DOWN);
                }
            }
        }
        return grossSalaryWithBonus;
    }
}

import java.util.Comparator;
import java.util.ArrayList;
import java.math.BigDecimal;

public class Main { //main class
public static void main(String[] args){

ArrayList<RegularEmployees> employeesList = new ArrayList<>();

BigDecimal totalNetSalaries = BigDecimal.valueOf(0.00);

                    for (RegularEmployees currentEmployee : employeesList) {
                    totalNetSalaries = BigDecimal.valueOf(totalNetSalaries + currentEmployee.employeeNetSalary()); //Bug here ; Operator "+" cannot be applied to  'java.math.BigDecimal','java.math.BigDecimal' how can I fix it?
                  }
                   System.out.println(totalNetSalaries);

employeesList.sort(Comparator.comparing(RegularEmployees::getEmployeeGrossSalary).reversed());
                    for(RegularEmployees current : employeesList){
                    System.out.println(current.getEmployeeGrossSalary());
                    }
🌐
University of Colorado Boulder
home.cs.colorado.edu › ~main › docs › edu › colorado › collections › DoubleStack.html
DoubleStack
The new item may be the null reference. ... item - the item to be pushed onto this stack Postcondition: The item has been pushed onto this stack. ... java.lang.OutOfMemoryError - Indicates insufficient memory for increasing the stack's capacity. Note: An attempt to increase the capacity beyond Integer.MAX_VALUE will cause the stack to fail with an arithmetic overflow...
Top answer
1 of 3
45

Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).

This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.

Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).

2 of 3
16

Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.

double has 64 bits. The first one is reserved for the sign.

Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.

Then there are 52 bits that hold the mantissa.

This is easily computed like this for example:

public static void main(String[] args) {

    String test = Strings.repeat("1", 52);

    double first = 0.5;
    double result = 0.0;
    for (char c : test.toCharArray()) {
        result += first;
        first = first / 2;
    }

    System.out.println(result); // close approximation of 1
    System.out.println(Math.pow(2, 1023) * (1 + result));
    System.out.println(Double.MAX_VALUE);

} 

You can also prove this in reverse order :

    String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));

    String sign = max.substring(0, 1);
    String exponent = max.substring(1, 12); // 11111111110
    String mantissa = max.substring(12, 64);

    System.out.println(sign); // 0 - positive
    System.out.println(exponent); // 2046 - 1023 = 1023
    System.out.println(mantissa); // 0.99999...8
Find elsewhere
Top answer
1 of 3
17

double overflows to Infinity and -Infinity, it doesn't wrap around. BigDecimal doesn't overflow, period, it is only limited by the amount of memory in your computer. See: How to get biggest BigDecimal value

The only difference between + and .addExact is that it attempts to detect if overflow has occurred and throws an Exception instead of wraps. Here's the source code:

public static int addExact(int x, int y) {
    int r = x + y;
    // HD 2-12 Overflow iff both arguments have the opposite sign of the result
    if (((x ^ r) & (y ^ r)) < 0) {
        throw new ArithmeticException("integer overflow");
    }
    return r;
}

If you want to check that an overflow has occurred, in one sense it's simpler to do it with double anyway because you can simply check for Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY; in the case of int and long, it's a slightly more complicated matter because it isn't always one fixed value, but in another, these could be inputs (e.g. Infinity + 10 = Infinity and you probably don't want to throw an exception in this case).

For all these reasons (and we haven't even mentioned NaN yet), this is probably why such an addExact method doesn't exist in the JDK. Of course, you can always add your own implementation to a utility class in your own application.

2 of 3
5

The reason you do not need a addExact function for floating point digits is because instead of wrapping around, it overflows to Double.Infinity.

Consequently you can very easily check at the end of the operation whether it overflowed or not. Since Double.POSITIVE_INFINITY + Double.NEGATIVE_INFINITY is NaN you also have to check for NaN in case of more complicated expressions.

This is not only faster but also easier to read. Instead of having Math.addExact(Math.addExact(x, y), z) to add 3 doubles together, you can instead write:

double result = x + y + z;
if (Double.isInfinite(result) || Double.isNan(result)) throw ArithmeticException("overflow");

BigDecimal on the other hand will indeed overflow and throw a corresponding exception in that case as well - this is very unlikely to ever happen in practice though.

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 185870 › one-method-for-stack-of-either-integer-or-double-parameters
java - One method for stack of either Integer or ... | DaniWeb
Yes, you can do that, but what when you want to return a value of type T? If you define the result as Integer, that's OK, you can then do the same thing for Double, that's OK too, now you have overloaded methods that will work, but that's not what … — JamesCherrill 4,733 Jump to Post · Ah yes, good point. And I'm not trying to argue either, just trying to increase my understanding. Most of my recent programming has been in PHP, so just trying to keep my Java knowledge up to date.
🌐
Reddit
reddit.com › r/learnprogramming › resolving java stack overflow
r/learnprogramming on Reddit: Resolving Java stack overflow
October 30, 2021 -

I've linked my function here

For one of my assignments, I'm supposed to be creating a binary search function using recursion. I'm supposed to be testing it with arrays of up to a size of 250,000 integers.

I've been getting "Exception in thread "main" java.lang.StackOverflowError" on line 15, which is one of the lines of recursion, so I assume it's something to do with the recursion itself, though I'm not quite sure what the issue is.

If someone could explain what I'm doing wrong and how to go about fixing it, that would be great!

🌐
GeeksforGeeks
geeksforgeeks.org › dsa › implement-two-stacks-in-an-array
Implement two Stacks in an Array - GeeksforGeeks
import java.util.Arrays; class TwoStacks { int[] arr; int size; int top1, top2; public TwoStacks(int n) { size = n; arr = new int[n]; top1 = n / 2 + 1; // top1 starts from the middle of the array + 1 top2 = n / 2; // top2 starts from the middle of the array } void push1(int x) { if (top1 < size) { // Ensure there is space for stack1 arr[top1++] = x; // Increment top1 and then insert the element } else { System.out.println("Stack Overflow for stack1"); } } void push2(int x) { if (top2 >= 0) { // Ensure there is space for stack2 arr[top2--] = x; // Decrement top2 and then insert the element } el
Published   April 9, 2012