THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

if (values == null || values.length == 0)
throw new IllegalArgumentException();


Now if values is null the value of the conditional-OR expression is known to be true and so no attempt
is made to access the length field.


The binary boolean operatorsAND (&), inclusive-OR (|), and exclusive-OR (^)are logical operators when their
operands are boolean values and bitwise operators when their operands are integer values. The conditional-OR
(||) and conditional-AND (&&) operators are logical operators and can only be used with boolean operands.


Exercise 1.9: Modify the Fibonacci application to store the sequence into an array and print the list of
values at the end.


Exercise 1.10: Modify the ImprovedFibonacci application to store its sequence in an array. Do this by
creating a new class to hold both the value and a boolean value that says whether the value is even, and
then having an array of object references to objects of that class.


1.10. String Objects


A String class type deals specifically with sequences of character data and provides language-level support
for initializing them. The String class provides a variety of methods to operate on String objects.


You've already seen string literals in examples like the HelloWorld program. When you write a statement
such as


System.out.println("Hello, world");


the compiler actually creates a String object initialized to the value of the specified string literal and passes
that String object as the argument to the println method.


You don't need to specify the length of a String object when you create it. You can create a new String
object and initialize it all in one statement, as shown in this example:


class StringsDemo {
public static void main(String[] args) {
String myName = "Petronius";


myName = myName + " Arbiter";
System.out.println("Name = " + myName);
}
}


Here we declare a String variable called myName and initialize it with an object reference to a string literal.
Following initialization, we use the String concatenation operator (+) to make a new String object with
new contents and store a reference to this new string object into the variable. Finally, we print the value of
myName on the standard output stream. The output when you run this program is


Name = Petronius Arbiter

Free download pdf