What are the differences between the built-in, primitive types (like int) and the equivalent, non-primitive object-wrapper classes (like Integer)?

Finlay McWalter

The elemental types (int, long etc.) are fundamental parts of the Java language - they're reserved words. They directly represent a quantity, a character, etc.

The java.lang classes (e.g. Void, Integer, Long etc.) serve two functions - first, they provide utility methods (generally static to those classes) for doing commonplace tasks like turning an integer into a String and vice versa.

The second use for the java.lang classes is as a wrapper for the elemental types - this is needed because Java represents all collections (other than arrays) in terms of java.lang.Object - so e.g., a Vector can only contain objects, not elemental types. If you wanted a Vector or Hashtable of ints, you'd have to wrap each int in a java.lang.Integer, and then unwrap the int when you retrieved values from the collection.

Equally, if you wanted to define a method that returned either a String or an int, you would define the function as returning a java.lang.Object; and then in practice you'd return either a java.lang.String or a java.lang.Integer, as appropriate.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact