Java JDK – possible lossy conversion from double to int

When you convert double to int,the precision of the value is lost. For example, When you convert 4.8657 (double) to int.The int value will be 4.Primitive int does not store decimal numbers.So you will lose 0.8657. In your case,0.7 is a double value(floating point treated as double by default unless mentioned as float-0.7f). When you calculate price*much*0.7 ,the answer is a double … Read more

How do I limit the number of decimals printed for a double?

Use a DecimalFormatter: double number = 0.9999999999999; DecimalFormat numberFormat = new DecimalFormat(“#.00”); System.out.println(numberFormat.format(number)); Will give you “0.99”. You can add or subtract 0 on the right side to get more or less decimals. Or use ‘#’ on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to … Read more

How to check if an int is a null

An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int. Integer id; String name; public Integer getId() { return id; } Besides the statement if(person.equals(null)) can’t be true, because if person is null, then a NullPointerException will be thrown. So the correct expression is if (person == null)

What is the difference between Integer and int in Java?

int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt(“1”) doesn’t make sense because int is not a class and therefore doesn’t have any methods. Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt(“1”) is a call to the … Read more

Java Array Sort descending?

You could use this to sort all kind of Objects sort(T[] a, Comparator<? super T> c) Arrays.sort(a, Collections.reverseOrder()); Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error no suitable method found for sort(int[],comparator) That will work … Read more