JAVA Arrays and Strings
JAVA Arrays and Strings
This class demonstrates how to define arrays in Java and iterate over arrays by using
for- each loop.
The first array, names, creates a String array and initializes each element separately. The
second array, numbers is an array of integers.
Each array is iterated through using the Java for-each construct
The enhanced for loop is used to make the for loop more compact and easy to read
It is used to access each successive value in a collection of values. It is commonly used
to iterate over an array or a Collections class (for example, an Array or an ArrayList)
Strings
The String class is immutable
After being created, the contents of an object of the class String can never be modified
The immutability of String objects helps the JVM to reuse String objects, reducing memory
overhead and improving performance.
Strings should always be initialized by using the assignment operator "=" and text in
quotation marks, as shown in the examples.
The use of new to initialize a String is strongly discouraged.
The reason is that "Bad Practice" in line 10 is a String literal of type String.
Using the new keyword simply creates another instance functionally identical to the literal.
If this statement appeared inside of a loop that was frequently invoked, a lot of needless
String instances could be created.
Strings
Strings