Sams Teach Yourself C in 21 Days

(singke) #1
Using ClassWithMethods:
Half of 99 is 49.5
The sum of 12345 and 997766 is 1010111
In ClassWithMethods.java, line 1 imports the required Stringclass, and line 3 is
the class definition. Lines 5 to 12 define the method displayText, which takes
one type Stringand one type booleanargument. It has no return value. Code in the
method tests the value of the newlineargument. If it is true,System.out.printlnis
used to display the message on the screen and then start a new line. If newlineis false,
System.out.printis used to display the message without starting a new line.
Lines 15 to 18 define the method halfOf. This method takes one type doubleargument
and returns a type double. There is only one line of code in the method. It divides the
argument by 2 and returns the resulting value.
Lines 20 to 24 define the method sumOf, which takes two type longarguments and also
returns a type long. Line 22 declares a variable to hold the temporary result, and line 23
performs the calculation. Then line 24 terminates the method and returns the result to the
caller.
Now let’s look at MethodsDemo.java. Lines 1 and 2 import two classes that will be used
in the program (explained below). Lines 4 and 5 are the program class and main method
definitions, as you have seen before. Line 6 declares a variable of type
ClassWithMethods, and lines 7 to 9 declare several primitive type variables the program
will use. Line 11 creates an instance of ClassWithMethods. Now the program can get to
work.
Lines 12 and 13 use the displayTextmethod to display two messages on the console. A
new line is started after the first message, but not after the second. Line 14 uses the
halfOfmethod to calculate half of the value 99 , assigning the return value to the variable
d. Line 15 makes use of the toStringmethod of Java’s Doubleclass to convert the
numerical value dinto a string, which is stored in temp. Line 16 displays this string on
the console.
Lines 17 to 20 are essentially a repeat of lines 13 to 16 except that the sumOfmethod is
called and the Long.toStringmethod is used to convert the numerical value to text.

730 Bonus Day 5

OUTPUT

ANALYSIS

Java has a set of classes corresponding to the primitive numeric data types;
these classes are called Boolean,Character,Integer,Long,Float, and
Double. Each of these classes has some useful methods, such as the toString
method used in the previous listing to create a string representation of a
numeric value. These classes can be very useful, and you can find out more
in your Java documentation.

Tip


40 448201x-Bonus5 8/13/02 11:23 AM Page 730

Free download pdf