Difference between BigDecimal.ONE and new BigDecimal("1") - java

what is the difference between below two lines of code?
BigDecimal one = new BigDecimal("1");
BigDecimal two = BigDecimal.ONE;
Are both the lines same?
Thanks!

No, they're not quite the same - new BigDecimal("1") allocates a new object each time it's executed (and have to parse the value, too); BigDecimal.ONE will use a reference to the same existing object each time.
As BigDecimal is immutable, you can reuse an existing instance freely - so it makes sense to refer to a "pre-canned" object where you know what the value will be.

BigDecimal.ONE is a pre scanned object and its efficient in terms of memory utilization as compared to
BigDecimal one = new BigDecimal("1");
because in this line it first creates an instance and then parses string "1" and then assigns.
whereas BigDecimal.ONE is like a constant and will give you direct value.
Hope this helps!

Related

Best practice to convert a Double to a String

I am currently using
Double a = 0.00;
for(condition)
//Do things
String result = "" + a;
Would using
String result = a.toString();
Provide any real benefit compared to what I have now. Does this just help the compiler or are there any differences between the two methods?
The first version - String result = "" + a under the hood is the same as String result = "" + a.toString();. Whenever there is a concatenation of String + Object the toString method is called.
What is the best practice here? What looks better for you. I'd probably go with the first version.
If you're concerned about the performance of both - String result = a.toString(); on paper will be faster because you don't need to create / get an empty String just to create a new one. However, as with many things in Java, something like that most likely gets optimized by JIT compiler anyway so I wouldn't worry about it too much. Even if it doesn't you shouldn't worry about optimization prematurely - if your code runs slowly then usually there is something else wrong with it that is much bigger than that.
I think second option is better because concatenation of strings cost much more memory.Since Strings are immutable objects in the first way your memory is wasting for store a Double object + two String Objects .
But in the second option it only create one new String object only .So in your memory there will only be one Double object + one String Object.

BigDecimal math operations

I want to write this in Java but I get some errors and I am not sure how to write it:
C = A - (A*B)/100
All of my values are defined as Bigdecimal objects.
I tried something like this but is not working:
C = A.subtract(A.multiply(B).divide(100));
..I get a warning to add more arguments to the divide method. I do not know how to write it correctly. What am I doing wrong? Thanks in advance
BigDecimal has no divide(int) method, but that's what you're asking it to do with .divide(100), because 100 is an int literal. If you refer to the documentation, all of the divide methods accept BigDecimal instances.
You can use divide(BigDecimal) instead, by using BigDecimal.valueOf:
C = A.subtract(A.multiply(B).divide(BigDecimal.valueOf(100)));
(It accepts a long [or double], but int can be promoted to long.)
Alternately, for some values, you might use the String constructor instead:
C = A.subtract(A.multiply(B).divide(new BigDecimal("100")));
...particularly if you're dealing with floating-point values that might lose precision in double. 100 is fine for valueOf, though.
c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));

How do I use ArrayList<Integer>#contains when I only have a BigInteger?

I am pulling data values from a database that returns a List of <Integer>. However, I would like to see if the List contains my BigInteger. Is there a simple way to do this?
I currently have the following code in Java:
ArrayList<Integer> arr = new ArrayList<Integer>() {{add(new Integer(29415));}};
boolean contains = arr.contains(29415); // true
boolean contains2 = arr.contains(new BigInteger("29415")); // false
I'm not sure on an efficient way to do this?
The correct answer will be returned by evaluation of the following:
val != null
&& BigInteger.valueOf(Integer.MIN_VALUE).compareTo(val) < 0
&& BigInteger.valueOf(Integer.MAX_VALUE).compareTo(val) > 0
&& list.contains(val.intValue())
This will correctly solve the question of whether the BigInteger you have is "contained" within the List<Integer>. Note that here we only downcast where necessary. If the val is outside the range of Integer values there is no need to downcast as we know that the value cannot be within the list.
A more relevant question is whether you should actually be using a List<BigInteger> in place of a List<Integer> but that is a different question and not part of the answer to your explicit question
While arshajii provides a solution which works, i would vote against it.
You should never downcast values. You are running in danger of your program producing larger values which translate to invalid values when downcasted. This kind of bug will be super nasty to troubleshoot months later.
If your code works with BigInteger, then you should convert all values from the database into BigInteger. This is an upcast where you cannot loose values.
Overall I would value correctness over efficiency. If at all, I would reconsider your usage of BigInteger (maybe long is fine?) but because you have it, I assume you have a reason for it.
In Java List.contains() uses the equals() method internally and because BigInteger.equals(Integer) returns false, your List.contains() also returns false. Either use the an List<BigInteger> or extract the Int value from BigInteger (as arshajii explained!). Of course, if you really want to search effectively, you should think of a binary search (in a sorted list) or of another data structure like Map.
You can try using BigInteger#intValue():
arr.contains(myBigInteger.intValue())
Note, however, that if myBigInteger is too big to fit into an int, then only the lower 32 bits will be returned (as described in the linked docs). Therefore, you might want to check if myBigInteger is less than or equal to Integer.MAX_VALUE before checking for containment.

Wrapper Classes, Difference in functionality when creating object via a String parameter in Constructor?

In terms of instances of wrapper classes, does the instance behave differently when the instance is created via a String arg in the constructor in comparison to an int, double etc.
E.g is there a difference in:
Integer wrapperInt= new Integer(33);
Integer wrapperInt2= new Integer("33");
The end result will be the same - you'll have an Integer object with the value 33.
The version that takes a String will throw a NumberFormatException if the input string cannot be parsed.
Note: There's no need to write a statement like Integer wrapperInt = new Integer(33);. Let the compiler do it for you (auto-boxing):
Integer wrapperInt = 33;
If, for some reason, you do not want to use auto-boxing, then at least use Integer.valueOf(...) instead of using the constructor:
Integer wrapperInt = Integer.valueOf(33);
This is more efficient; the valueOf method can return a cached object (so that it's not necessary to create a new Integer object).
No, it doesn't. Both instances represent the integer 33. If there was a difference, it would be written in the javadoc.
Note that you should favor the usage of the factory methods instead:
Integer i = Integer.valueOf(33);
i = Integer.valueOf("33");
The only difference is you will be creating a string object unnecessarily in the second approach and it will try to parse the string you have passed to the constructor, If it couldn't parse the string then it will throw NumberFormatException.
The answer is that yes, there can be a difference between the two syntaxes. Specifically, the syntax
new Integer(33);
results in the value 33 being interpreted as an integer constant by the compiler and stored as a literal in the code. By contrast, the syntax
new Integer("33");
results in a call that routes the string value through Integer.parseInt(s, 10). This matters if the value in question has a leading zero character; in the case of an int literal, the compiler will evaluate the literal as octal:
new Integer(010); // equals 8
By contrast, the string constructor will always evaluate the value as base 10:
new Integer("010"); // equals 10
In any case, you should almost always be using Integer.valueOf(), as it is usually more efficient.

BigDecimal assign operator

I have a problem with assigning one big decimal value to another
I am trying such as creating one temp big decimal and add 0 to another big decimal
BigDecimal temp = new BigDecimal(0);
dropStartValue = temp.add(newCounterValue);
However, I only want simply do the operation below on big decimals:
dropStartValue = newCounterValue
You haven't specified the type of either dropStartValue or newCounterValue. If they're both BigDecimals, then this should be fine:
dropStartValue = newCounterValue;
Note that although that's just making both variables refer to the same object, it's safe because BigDecimal itself is immutable.
If that's not working for you, please give details of what problems you're seeing (exceptions? compile-time errors?).
Assuming this is Java ans newCounterValue is an integer type or a box thereof, dropStartValue = new BigDecimal(newCounterValue); should do what you want.

Categories