Java Reference
In-Depth Information
4.7 Summary
This chapter covered two topics: methods and formatted printing. Methods are used to
break a big program into small manageable pieces. When calling a method, one can send
several parameters to the method. A method can return at most one piece of data. When
a method needs to return multiple pieces of data, global variables can be used. However, a
better approach is to avoid using global variables when possible.
Java supports the printf method (inherited from the C programming language). It
allows us to display formatted output. For example, it allows us to justify the output
to the left or to the right, insert leading or trailing spaces, or specify the precision with
which to display a real number. Similarly, Java supports formatted printing through the
DecimalFormat class. You can specify a pattern and the result will be printed according to
the pattern template.
4.8 Syntax
￿ System.out.printf("%.2f",a)
Prints a double formatted two digits after the
decimal dot.
Prints the integer using 5 spaces and right justified.
Prints the integer using 4 spaces and left justified.
￿ System.out.println(new DecimalFormat("$###,###.##").format(3365.34))
System.out.println(new DecimalFormat("
Defines the constant DAYS and sets it to be equal
static final int DAYS = 10
to 10.
￿ public static void m( ... ) {
Method with no return type.
public static int m( ... )
Method that returns an integer.
Method that returns an integer
and takes as input two integers. The input is saved in the variables i and j ,which
are local for the method.
public static int m(int i, int j)
4.9 Important Points
1. Every method must have a return type. When this type is void , the method does not
return anything. When this type is not void , the calling method needs to save the
result of calling the method for future use. It does not make sense to ask a method to
calculate something and then not save the result after calling the method.
Search WWH ::

Custom Search