How to Print in Java – Complete guide

Posted by Marta on March 28, 2021 Viewed 38 times

Learning how to use the java print and other methods to print messages to the console using Java. See how print an array and an object to the console.

Card image cap

This article is about learning how to use the java print method and other methods to print messages to the console using Java. This guide also includes using java print to print an array and an object to the console.

After reading this article, you will understand how to use the java print method, the different ways to print, when to use each, and how to use them.

Let’s dive in!

Java Print to Console

Java print is a method that allow you to print any message to your console or terminal. This is really useful since it allow you to display any variable, and in a way communicate with your java program.

Here is how to call the java print method:

System.out.print("Hello");

As you can see, the .print() method belongs to the System.out instance. System.out is an instance of the PrintStream. Its main functionality is providing access to the console or standard output. Writing System.out in our program is accessing the console. This console offers different methods like .flush() or .checkError(), however we will focus on the print functionality.

The System.out.print() method accepts several types: String, char, char[], double, float, int, long, and Object. See an example below:

System.out.print("Hey");
System.out.print('a');
System.out.print("Hello".toCharArray());
System.out.print(34.45d);
System.out.print(342.4f);
System.out.print(2342l);
System.out.print(12);
System.out.print(new Object());

Output:

HeyaHello34.45342.4234212java.lang.Object@266474c2

As shown above, the code prints all values correctly; however, this is readable since they are all together in the same line. You could fix this by adding a new line character "\n":

System.out.print("Hey");
System.out.print("\n");
System.out.print('a');
System.out.print("\n");
System.out.print("Hello".toCharArray());
System.out.print("\n");

Output:

Hey
a
Hello

Another choice is using the following method, .println().

.println() method

This method is an improvement over the .print() method. Apart from printing your value to the console, it will add a line separator, meaning the next print statement will start writing on the next line. See the .println() method in action in the example below:

System.out.println("Hey");
System.out.println('a');
System.out.println("Hello".toCharArray());
System.out.println(34.45d);
System.out.println(342.4f);
System.out.println(2342l);
System.out.println(12);
System.out.println(new Object());

Output:

Hey
a
Hello
34.45
342.4
2342
12
java.lang.Object@266474c2

.printf() method

Apart from the .print() and .println() methods, Java provides another method for printing to the console. The .printf(). Why another method? This method offers more control over the output when you want to include numbers on the printed message. See how to see it below:

float floatVar = 23.4f;
System.out.printf("A float number %f %n", floatVar);

int num = 23;
System.out.printf("A integer number: %d %n", num);

String stringVar = "text";
System.out.printf("Or print %s",stringVar);
System.out.printf("Or print them all at once %f %d %s %n",floatVar,num,stringVar);

Output:

A float number 23.400000 
A integer number: 23 
Or print text
Or print them all at once 23.400000 23 text 

You might be wondering what the percentage symbol is. It indicates to Java where you want to insert a value, and the type of value to insert. The most common symbols are:

  • %f for a float number.
  • %d refers to integers
  • %s for strings
  • %n to print a line separator.

.append() method

This method will append the specified character to the end of the current output printed in the console. In other words, it works in the same way as .print(). The difference is that it allows you to append values of the type CharSequence. See an example:

System.out.append("hellocodeclub".subSequence(5,7));
System.out.append("\n");
System.out.append("hellocodeclub".subSequence(1,5));

Output:

co
ello

Difference between print and println

The difference is that the .println() method will add a line separator at the end of the specified String, while the .print() method doesn’t add a line separator. If you would like that next print to start in a new line, you need to add the line separator( %n) yourself.

How to Print an Array in Java

Let’s see how to print an array. No method will print an array in Java, meaning that you will need to write the code yourself. To print an array, you could go through every character in the array and append the number followed by a comma to a final string. And last print the resulting String using .println(). See this in action below:

public void printArray(int[] array){
        StringBuilder builder = new StringBuilder("{");
        for(int i=0;i<array.length-1;i++){
            builder.append(array[i]).append(",");
        }
        builder.append(array[array.length-1]);
        builder.append("}");
        System.out.println(builder.toString());
}
int[] array = {1, 2, 3, 4, 5};
printArray(array);

Output:

{1,2,3,4,5}

How to Print an Object

You create your Class called Person, and you would like to print it to the console. What do you need to do? You will need to convert your Object to a String using the .toString() function. Is that everything? Not yet.

By default, if you don’t provide code for the .toString() method, Java will call the Object.toString(). This method will print your object memory address. See the example below:

class Person{
	private String name;
    private int age;

    private Person(String name, int age){
    	this.name = name;
        this.age = age;
    }
}
Person myObject = new Person("Peter",16);
System.out.printf(myObject.toString());

Output:

Person@4dc63996

Well, that is not very useful, so how can I change this? Initially you will need to add your own .toString() method in your Class, specifying how you want the Object to be converted to String. See this in action below:

class Person{
	private String name;
    private int age;

    private Person(String name, int age){
    	this.name = name;
        this.age = age;
    }

    public String toString(){
    	return String.format("Person: name=%s, age=%d %n",this.name,this.age);
    }
}
Person myObject = new Person("Peter",16);
System.out.printf(myObject.toString());

Output:

Person: name=Peter, age=16 

Example: Print a Char array

You can print a char array by merely calling the .println() method, no need to write your method. However, if you like to print an array of anything else, integers, floats, String, etc., you will need to add a specific method similar to the one above.

char[] array = {'h','e','l','l','o'};
System.out.println(array);

Output:

hello

Conclusion

To summarize, in this article, we covered all that you need to know about the java print method. We have seen what it is and how to do it. Plus, other methods provide similar extended functionality and some examples of using the java print method.

I hope you enjoyed the article, and thank you so much for reading and support this blog! Happy Coding!

More Interesting Articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java