Docsity

Java Wrapper Classes: Understanding Objects' Role in Holding Primitive Data, Study notes of Java Programming

Partial preview of the text

Download Java Wrapper Classes: Understanding Objects' Role in Holding Primitive Data and more Study notes Java Programming in PDF only on Docsity!

Wrapper Classes for

Primitive Types in Java

Primitive Data Types

Include...

byte, short, int, long, float, double

char

boolean

Q. Why aren’t these objects?

A. Efficiency (avoid “object overhead”)

NOTE: all wrapper classes capitalize the name of the associated primitive type, except for Integer and Character. UML Class Diagram for Wrapper Classes

Converting Between Strings and Primitive Numeric Types Converting to String

Double doubleObject = new Double(5.0);

String s = doubleObject.toString();

Converting from String

double d = Double.parseDouble(“5.0”);

int i = Integer.parseInt(“5”);

// Using ‘parse’ method with a radix (base):

int j = Integer.parseInt(“11”, 2); // j=3 (in base 10!)

Example: A Polymorphic (“Generic”) Sorting Method

Text Example, GenericSort.java

(implementation of Selection Sort: iteratively finds largest element, places it at the end of the array)

  • Using the Comparable interface (compareTo()), different object types are sorted using the same sorting method; each class defines how objects of the class should be ordered.
  • NOTE: Java defines a static sort in the Arrays class, for any array of objects implementing Comparable - e.g. Arrays.sort(intArray);