Perform Simple Math Tasks with Java - dummies

Perform Simple Math Tasks with Java

By John Paul Mueller

In your Java applications, you’ll often need to perform simple multiplication, division, addition, or subtraction. The combined assignment operators provide the best way to perform single math tasks. You can see how Java performs math operations involving multiple operators or situations where the combined assignment operators don’t work.

Some code examples use the printf() method. You use this method to create formatted output. However, instead of using the date and time formatting strings, you use the formatting strings shown in this table instead.

The table shows the most common formatting strings — Java does provide others that are used for special tasks.

Common Java Formatting Strings
Code Specific Use Description
%b
%B
General Displays the Boolean value of the variable. When working with a
Boolean variable (either primitive type or object), the result is
the actual value of the variable. Other variables display false
when the variable is null (hasn’t been initialized) or true
when the variable contains a value. The uppercase %B uses uppercase letters.
%s
%S
General Displays the string value of a variable — whatever the
toString() method would normally display. The uppercase %S uses uppercase letters.
%c
%C
Character Displays the specified Unicode character using the rules of the
Character data type. The uppercase %C
uses uppercase letters even if the character value would normally
produce a lowercase output.
%d Integral Outputs an integer variable in decimal format.
%o Integral Outputs an integer variable in octal format.
%x
%X
Integral Outputs an integer variable in hexadecimal format. The
uppercase %X uses uppercase letters.
%e
%E
Floating point Outputs a floating point variable using scientific notation.
The uppercase %E uses uppercase
letters.
%f Floating point Outputs a floating point variable using standard floating point
(decimal) notation.
%g
%G
Floating point Outputs a floating point variable using either decimal or
scientific notation depending on the precision of the variable.
(The application uses the format that will provide the best
output.) The uppercase %G uses uppercase
letters.
%% Percent sign Outputs a percent sign. You can’t use a single % sign because the %
sign is used for other purposes when used alone.
%n Newline character Adds a newline character to the end of any output that you
create. You can also use the n escape character, but using %n is preferable in formatted output because it
matches the remaining formatting strings.