36

What is the difference between Double and double?

Ashwin Shirva
  • 1,331
  • 1
  • 12
  • 31
  • 1
    http://stackoverflow.com/questions/12226757/java-different-double-and-double-in-comparison?rq=1 , http://stackoverflow.com/questions/13701818/why-is-int-changed-to-integer-automatically-in-java – user2864740 Dec 07 '13 at 03:01
  • 1
    Don't use `Double` unless you have a good reason to do so. It's error prone and needlessly slower. – zapl Dec 07 '13 at 03:03
  • You could have googled your exact title and found the answer a lot faster – Paul Richter Dec 07 '13 at 03:04
  • 2
    @CaptainGiraffe *No* That is C#. In C#, `System.Double` *is* `double`. However, Java has a fixed set of primitive types and a *wrapper* for each primitive type. – user2864740 Dec 07 '13 at 03:05
  • It is 14 years old. http://stackoverflow.com/questions/13332012/double-vs-double-in-java – Captain Giraffe Dec 07 '13 at 03:06

1 Answers1

41

Double is an object and double is a primitive data type. See this answer for more details.

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

Source: http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html

Community
  • 1
  • 1
  • 8
    So when should I use `Double` and when to use `double`? Thank you – F 505 May 02 '18 at 16:16
  • 3
    @F505 I would recommend `double` when just doing basic floating point computation. If there is a lot of string conversion needed, then I would use the class `Double` – But I'm Not A Wrapper Class May 02 '18 at 21:23
  • 10
    Some thing important to note, is that a complex data-type Double can be null. I often use it when an operation could yield something else than a number, if something is not found, and a null value is required. Else, if a result is mandatory, I do prefer using a primitive double type. – Alex Feb 20 '19 at 11:16
  • @F505 I prefer `Double` if I need use of generics: i.e. `List`. Second case: type cast/conversion. Maybe also for comparison purposes it's better to take a wrapper class if we want to define precision level. doubles are not easy to compare if one calculate with doubles before. Maybe it's more convenient with Double wrapper class? – Hermann Schwarz May 14 '22 at 14:22