datalogo
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Printing Variables

Java supplies the System class which contains methods for displaying output.

Remember:  The basic output statement in Java is

System.out.println( );  

System.out.println(" text "); will print exactly what is between the double quotes " " and move the printing cursor to the next line.

System.out.print(“ text ”); will print exactly what is between the double quotes and leave the printing cursor on the same line.


When dealing with variables:

System.out.println(" The total pay is " + totalPay);

what is surrounded by " " is referred to as a "literal print" and gets printed exactly as it appears.  The "+" sign indicates that value stored in the variable totalPay will be printed immediately following the literal print.   

double totalPay = 1006.5;
System.out.println("The total pay is " + totalPay);
On the screen:
The total pay is 1006.5


You can print an arithmetic expression within a System.out.print statement.  Use parentheses around the arithmetic expression to avoid unexpected problems.

System.out.println("Adding ten to the total: " + (totalPay + 10));

We will see more about this process in the section on Strings.

 

dividerdash

Programmers that are familiar with other programming languages (such as C, C++, or Perl) are used to working with a print method known as "printf". The formatting styles of this method are reusable between languages, including Java.  

A simple formatting for the "printf" method is shown below:
System.out.printf("The %s has %s, %d of them!", "dog", "fleas", 5);


In Java, this same style of formatting used with "printf" appears in the format method:
System.out.format("The %s has %s, %d of them!", "dog", "fleas", 5);

The printf method is seen by some programmers as simply a "convenience" for C/C++ programmers who are programming in Java. The format method is thought of as a more Java-like choice.

This site will be using the format method. See more information about using this method at Formatting Output.

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Notice: These materials are free for your on-line use at this site, but are not free for the taking.
Please do not copy these materials or re-post them to the Internet, as it is copyright infringement.
If you wish hard-copies of these materials, refer to our subscription area, JavaMathBits.com.
Help us keep these resources free. Thank you.