Apps/Gaming

Java Output Basics

Whatever programming language you work with, you likely have to accept input from an external source and produce output to be consumed by another program or end-user. Typically, the keyboard is the standard input device and the screen is the standard output device. As such, this programming tutorial will present a few useful methods for printing content to the screen in Java, including using the print() other println() methods.

Looking to learn Java in a classroom or online course environment? We have a list of the Best Online Courses to Learn Java to help get you started.

The print() and println() Methods in Java

The simplest way to send output to the screen in Java is to use the print() or println() methods, or, more precisely, System.out.println() or System.out.print()as both methods belong to the system class’s public static output field. As such, we never have to instantiate the system class in order to access its methods.

You have heard no doubt of the time honored Hello World applications. Here is what that looks like in Java:

class OutputExamples { public static void main(String[] args) { System.out.print(“Hello world!”); } }

What’s the Difference Between print() and println()?

At this point you may be wondering why there are two methods to do the same thing. That is a fair question, and the reason is that println() adds an extra newline character, or character combination, so that the cursor appears on the following line. Here is an example to illustrate how to use println() in Java:

System.out.println(“println #1”); System.out.println(“println #2”); System.out.print(“print #1 “); System.out.print(“print #2”); /* Outputs: println #1 println #2 print #1 print #2 /*

How to Display Variables and Literals in Java

There are versions of both the print() other println() method for every native data type, wrapper class, and objects too. In the case of native types, like int or wrappers, like doubles, these methods allow developers to print variables and literals without having to convert them to strings first. Here is some example code that prints a doubles variable and internal literal in Java, respectively:

Double monthlyAvg = 20.87; System.out.println(monthlyAvg); //variable System.out.println(99); //literal /* outputs: 20.87 99 /*

Reading: Java Tools to Increase Productivity

using print() other println() with objects

When the print() or println() method receives an object type that it does not recognize, it employs the class’s toString() method to convert it into a printable format. It is meant to be overridden by your class to print something meaningful. Otherwise, toString() formats the object in the default format. That is:

  1. The name of the class
  2. the@” icon
  3. A hash code of the object

Here’s an example of how to use the toString() method in Java:

class MyClass { } class Main { public static void main(String[] args) { // create an object of the Test class MyClass myClass = new MyClass(); // print the object System.out.println(myClass); // outputs: [email protected]

} }

Here is another example:

class MyClass { static int myClassInstances = 0; MyClass() { myClassInstances++; } @Override public String toString() { return “MyClass instance #” + myClassInstances; } } class Main { public static void main(String[] args) { // create an object of the Test class MyClass myClass = new MyClass(); // print the object System.out.println(myClass); // Outputs: MyClass instance #1 } }

Reading: The Best Tools for Remote Developers

How to Format Output in Java

Looking to have your output printed in a specific format? No problem, Java’s got you covered. For you coding veterans out there, remember the C language’s printf() functions? As it happens, Java, which borrows liberally from C and C++, implements its own version of the popular function. Here are just a sampling of what printf() can do and how to format output in java:

import java.lang.Math; public class FormattedOutputUsingPrintf { public static void main(String args[ ]) { // printing a string value on the console final String str = “Test string”; System.out.printf( “nPrinting a String value: %s n “, str ); // printing an int value on the console final int anInt = 2112 ; System.out.printf( “nPrinting an int value: anInt = %d n “, x ); // printing a decimal value on the console int r = 5; double area = Math.PI*(r*r); System.out.printf( “nPrinting a decimal value: %f n “, f ); // this formatting is used to specify the width to which the digits can extend System.out.printf( “nFormatting the output to specific width: area = %.4f n “, f ); // this formatting will print it up to 2 decimal places System.out.printf( “nFormatted the output with precision: area = %.2f n “, f ); // formats number from right margin and occupies a width of 20 characters System.out.printf( “nFormatted to right margin: area = %20.4f n “, f ); } } /* Displays: Printing a String value: Test string Printing an int value: anInt = 2112 Printing a decimal value: 78.539816 Formatting the output to specific width: area = 78.5398 Formatted the output with precision: area = 78.54 Formatted to right margin : area = 78.5398 */

A Word aboout System.out.format() in Java

If you happen to run across the System.out.format() method, we did not skip it – it is an alias to printf() and does the exact same thing. Perhaps it is meant as an alternative for people who still have nightmares about C pointers.

For the full list of Java String format specifiers, take a look at the Java docs here.

How to Format Numbers Using the DecimalFormat Class

As you are no doubt aware, formatting numbers with decimals can be a challenge. To help with that, Java includes the DecimalFormat class. Here is some example code showing how to use DecimalFormat in Java:

import java.text.DecimalFormat; public class FormattedOutputUsingDecimalFormat { public static void main( String args[ ] ) { double myDouble = 123.4567; // printing the number System.out.printf( “nThe number is: %f n “, myDouble ); // printing only the numeric part of the floating number DecimalFormat ft = new DecimalFormat( “####” ); System.out.println( “nWithout fraction part the number is: ” + ft.format( x ) ); // printing the number only up to 2 decimal places ft = new DecimalFormat( “#.##” ); System.out.println( “nFormatted number with the specified precision is: ” + ft.format( x ) ); // to automatically appends zero to the rightmost decimal place, use 0 instead of # ft = new DecimalFormat( “#.000000” ) ; System.out.println( “nAppending the zeroes to the right of the number: ” + ft.format( x ) ); // to automatically append zero to the leftmost decimal place, use 0 instead of # ft = new DecimalFormat( “00000.00” ) ; System.out.println( “nAppending the zeroes to the left of the number: “+ ft.format( x ) ); // formatting money into dollars double income = 100000.789; ft = new DecimalFormat( “$###,###.##” ); System.out.println( “n Your income in dollars is: ” + ft.format( income ) ); } } /* Displays: The number is: 123.456700 Without fraction part the number is: 123 Formatted number with the specified precision is: 123.46 Appending the zeroes to the right of the number: 123.456700 Appending the zeroes to the left of the number: 00123.46 Your income in dollars is: $100,000.79 */

Final Thoughts on Java Output Basics

This programming tutorial presented a few useful methods for printing content to the screen in Java. Whether you need to display a string, native data type, or object, there is a method for every occasion.

If you enjoyed this Java tutorial, stay tuned. In the next one, we will be learning all about Java variables!

Related posts

JavaScript String Methods for Concatenation and Substitution

TechLifely

Getting started with Kotlin coroutines

TechLifely

Review of Microsoft Project

TechLifely

Leave a Comment