Java Reference
In-Depth Information
numbers[0] = 10; // This is okay
int[] newNumbers = new int[]{10,20,30};
numbers = newNumbers; // This is not okay
There is one case, however, that's a little bit special, namely Strings . As you have seen, Strings are
not a primitive type in Java, and are, in fact, objects like any other. You might thus try something
like the following:
final String myString = "Hi there";
myString = "bye";
However, this approach will not work, as this is actually a shorthand notation for the following:
final String myString = new String("Hi there");
myString = new String("bye");
When writing this piece of code, it becomes clear why you cannot do it this way. However, when
you are particularly observant, you might say, since String is a class and I create String objects,
surely the actual value of the String object must be stored somewhere, probably as an array of
char is The answer is that, indeed, a String object keeps an internal representation of the actual
textual value, but it cannot be publicly accessed or modified. This is done for performance reasons.
But wait—why then can you execute the following:
String myString = "a";
myString = "b";
myString += "cde";
Again, the reason is that this is shorthand and Java helps you out. In fact, this code actually corre-
sponds to:
String myString = new String("a");
myString = new String("b");
myString = new String(myString + "cde");
This immediately provides you with the reasoning behind the fact that changing Strings in Java are
an intensive, relatively slow operation. For a few modifications, this does not matter, but when you
have to modify a String many thousands of times, it is advisable to look at other text‐representing
classes, such as StringBuilder —more about this later.
Note Variables are not the only elements that can be defined as being final.
Methods can also be set as being final—meaning that they cannot be over-
ridden or hidden by subclasses. Classes can also be set to final, meaning that
they cannot be subclassed at all.
Don't worry about what subclassing and subclasses mean at this point, as I
will explain them when we talk about advanced object‐oriented concepts in
Chapter 8. Just remember for now that “final” can serve as a way to allow for
continues
Search WWH ::




Custom Search