[   ^ to index...   |   next -->   ]

CSE 341 : 24 May 2001

Data types: Java's split personality

    Two very different kinds of types:
  1. Classes: Subclasses of java.lang.Object.
  2. Primitive types:
Classes Primitive types
Uniform reference model, like ML and Smalltalk Pass by value/copy
Can subclass, define methods, etc. (normal "object-oriented" stuff) Cannot
Can pass references to methods that expect Object parameters. Cannot

Q: What if you want to treat a primitive type as if it were an object?

A: Java provides a wrapper class for each primitive type, in the java.lang package. Therefore, if you want to treat an int as an object, you can "wrap" it in an instance of the class java.lang.Integer; for char, you can use class java.lang.Character, etc.:

    char c = 'h';
    Character objectC = new Character(c);
    char d = objectC.charValue();

Note that primitive types can be modified directly, but instances of the wrapper classes are immutable---they do not have any methods that change their value.

Meta-note: immutable objects in OO languages provide many of the same benefits that immutable values in functional languages do. You can pass and share them freely without worrying about side effects. So, standard string objects (java.lang.String), for example, are immutable. (java.lang.StringBuffer is the mutable string class)

By the way, strings are objects that have special syntactic support. For example, string literals are actually instances of class String:

    String s = "hi";                // These two lines produce equivalent-valued
    String t = new String("hi");    // String objects.
    if("hi".equals(t))              // BTW, by convention the message
        System.out.println("eq0");  // .equals() means value comparison.

    if(t == "hi")                   // Also BTW, == is "object identity" testing.
        System.out.println("eq1");  // t and "hi" have the same value, but
    else                            // are different objects, so the identity
        System.out.println("not1"); // test will return false.

Keunwoo Lee
Last modified: Wed May 23 22:43:43 PDT 2001