Java Reference
In-Depth Information
The text between double quotes, "A totally fruity program" , is a character string. Whenever you
need a string constant, you just put the sequence of characters that you want in the string between double
quotes.
You can see from the annotations in Figure 2-3 how you execute methods that belong to an object. Here
you execute the method println() , which belongs to the object out , which, in turn, is a variable that is
a static member of the class System . Because the object out is static, it exists even if there are no objects
of type System in existence. This is analogous to the use of the keyword static for the method main() .
Most objects in a program are not static members of a class though, so calling a method for an object typ-
ically just involves the object name and the method name. For instance, if you guessed based on the last
example that to call the putHatOn() method for an object cowboyHat of the type Hat that I introduced
in Chapter 1, you would write
cowboyHat.putHatOn();
you would be right. Don't worry if you didn't though. I go into this again when we look at classes in
detail. For the moment, any time you want to output something as text to the console, you just write
System.out.println( whateverYouWantToDisplay );
with whatever character string you want to display plugged in between the parentheses.
Thus, the second statement in the example
System.out.println("Total fruit is " + numFruit);
outputs the character string “Total fruit is” followed by the value of numFruit converted to a character
string, that is “15”. So what's the + doing here — it's obviously not arithmetic we are doing, is it? The
addition operator has a special effect when used with operands that are character strings — it joins them
together to produce a single string. But numFruit is not a string, is it? No, but the left operand, "Total
fruit is " is, and this causes the compiler to decide that the whole thing is an expression working
on character strings. Therefore, the compiler inserts code that converts the value of the right operand,
numFruit , to a character string to be compatible with the left operand. The effect of the + operation is
to tack the string representation of the value of numFruit on to the end of the string "Total fruit is
" . The composite string is then passed to the println() method to display it on your screen. Dashed
clever, these compilers.
If you want to output the value of numOranges as well, you could write the following:
System.out.println("Total fruit is " + numFruit + " and oranges = " +
numOranges);
Search WWH ::




Custom Search