book
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
The value of s1 after the concat method is executed remains an unchanged "abc". s2 is<br />
equal to "abcdef" since concat returns a new object with the concatenated result, which<br />
is assigned to s2. The main advantage of String immutability is that the Java compiler<br />
can save space by sharing Strings. If a program repeatedly performs String<br />
concatenation, when processing a file, for example, then the repeated creation of new<br />
objects becomes inefficient. To cater for this, Java provides a mutable StringBuffer<br />
class, which we discuss in Chapter 4.<br />
We can convert all primitive data types to a String using the<br />
java.lang.String.valueOf method. For example, the following converts an int to a<br />
String:<br />
int count = 123;<br />
String countString = String.valueOf(count);<br />
2.5.6 Arrays<br />
An array contains a collection of elements, all of which have the same type. Arrays can be<br />
of any type. An array declaration is of the form<br />
datatype variable_name [] ;<br />
or<br />
datatype [] variable_name;<br />
We have already seen an array, args, of type String in the Circle program. If we<br />
wish to declare an array, intArray, say, of type int, enter either<br />
int [] intArray;<br />
or<br />
int intArray[];<br />
This statement only declares the variable intArray. To create or define an array, that is,<br />
reserve storage in memory to hold the array, we need to use the new keyword. For example,<br />
intArray = new int [2];<br />
will create the array intArray with two elements and initialize it with zero values, the<br />
default value for numbers. The reason for the new keyword is that an array is actually an<br />
object in Java. Objects in Java are created using the new keyword, as we shall see in<br />
Chapter 4.<br />
Array elements are counted from zero, so