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 between double quotes.
You can see from the annotations above how you execute methods that belong to an object. Here we
execute the method println() which belongs to the object out , which, in turn, is a static variable
of the class System . Because the object out is static , it will exist 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
typically just involves the object name and the method name. For instance, if you guessed from the last
example that to call the putHatOn() method for an object cowboyHat , of type Hat introduced in
Chapter 1, you would write:
cowboyHat.putHatOn();
you would be right. Don't worry if you didn't though. We will be going into this again when we get to
look at classes in detail. For the moment, any time we want to output something as text to the console,
we will just write,
System.out.println( whateverWeWantToDisplay );
with whatever data we want to display plugged in between the parentheses.
Thus the second statement in our example:
System.out.println("Total fruit is " + numFruit);
outputs the character string "Total fruit is " followed by the value of numFruit converted to
characters, that is 15 . So what's the + doing here - it's obviously not arithmetic we are doing, is it? No, but
the plus has a special effect when used with character strings - it joins them together. But numFruit is not a
string, is it? No, but "Total fruit is " is, and this causes the compiler to decide that the whole thing is
an expression working on character strings. It therefore converts numFruit to a character string to be
compatible with the string "Total fruit is " and tacks it on the end. The composite string is then passed
to the println() method. Dashed clever, these compilers.
If you wanted to output the value of numOranges as well, you could write:
System.out.println("Total fruit is " + numFruit
+ " and oranges = " + numOranges);
Try it out if you like. You should get the output:
Total fruit is 15 and oranges = 5
Search WWH ::




Custom Search