Java Reference
In-Depth Information
Such types represent one intuition about values: values are immutable, and only variables
(which contain values) may be mutated to contain a different immutable value. As we remarked
at the head of this section, Java authors including ourselves sometimes have inconsistently
talked about the possibility of a Java value being a mutable array. In the next section, we return
to proper intuition and discuss the idea of a value type ; these can only contain immutable values,
even if variables of value type can still be updated, unless qualified with final.
16.2.6. Value types
In this section, we discuss the difference between primitive types and object types , linking into
the discussion earlier about the desire for value types , which help you to write programs
functionally, just as object types are necessary for object-oriented programming. Many of the
issues we discuss are interrelated, so there's no easy way to explain one problem in isolation.
Instead we identify the problem by its various facets.
Can't the compiler treat Integer and int identically?
Given all the implicit boxing and unboxing that Java has slowly acquired since Java 1.1, you
might ask whether it's time for Java to treat, for example, Integer and int identically and to rely
on the Java compiler to optimize into the best form for the JVM.
This would be a wonderful idea in principle, but let's consider the problems surrounding adding
the type Complex to Java to see why boxing is problematic. The type Complex, which models
so-called complex numbers having real and imaginary parts, is naturally introduced as follows:
class Complex {
public final double re;
public final double im;
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
public static Complex add(Complex a, Complex b) {
return new Complex(a.re+b.re, a.im+b.im);
}
}
 
Search WWH ::




Custom Search