Select Page

The print and println methods in Java


The print() and println() methods are Java’s predefined methods used to display text output on the console. These methods are part of the Java API.


nanadwumor

June 01, 2023

print and println methods - Java for beginners


  • The print and println methods are used to print string of characters  onto the console
  • The print method prints and leaves cursor on the same line
  • The println method prints and moves cursor to the next line

RECOMMENDED ARTICLES


Variables and Literals in Java

Variables and Literals in Java

Variables are used in many situations. For Instance, game applications use variables to collect your name when you sign in; to store and keep track of your number of trials, successes and failures. In Java, a variable is a container used to store...

double data type in Java

double data type in Java

The double data type is also a floating point number. It is called double because it has a double-precision decimal number.   The double data type is a floating point number. It is double precision data type The range is 4.9406564584124654 x...

float data type in Java

float data type in Java

It is a floating point number. It has single precision data type. It stores a floating point number of 7 digits of accuracy. The float data type is a floating point number. It has single precision data type The float type is stored in 32 bits of...


The print() and println() methods are Java’s predefined methods used to display text output on the console. These methods are part of the Java API.

The term, API, stands for Application Programming Interface. The Java API is a collection of prewritten classes and methods for performing specific operations. These classes and methods are available to the programmer when coding his application.


Join Other Subscribers on Our YouTube Channel and Don’t Miss a thing!


Example of usage of print() method

System.out.print(“Thanks for visiting www.villagecoder.com”);

Explanation of above statement

The above statement displays the text Thanks for visiting www.villagecoder.com

Parameters the print() method accepts

The print() method accepts any parameter the programmer may wish to print out on the output screen.

Output

Program demonstrates the print function in Java

System : System is a class. It is found in java.lang.package. A class in Java contains methods and fields. A clas is used to construct objects in Java. Note that Java is an object oriented programming language.

That’s, to code in java, you create objects. And these objects are created from classes. So you see, classes are some sort of blueprint or plan from which you create your items or objects. This is similar to how a building constructor uses his building plan (the class) on paper to actually build a house (the object)

Where from the System class?

The System class is part of the Java API. This implies, you can call it anytime in your program if needed. Classes in the java.lang package are readily available to a program. System is a class that performs operations on system level.

Fields in System class

As said earlier, a class in Java has fields and methods (or functions). The fields store important information about the class (or objects created from the class).  One example of the fields of the System class is out.

what is the ‘out’ field?

Mostly, fields are primitive values. Example of primitive values are int (for integer), float (for floating point number), double (another floating point number), boolean (true or false values) etc. However, a field in Java can also be an object. Example is a String.

String nameOfWebsite=“villagecoder”;

In the above statement, the field is called nameOfWebsite. It’s a String variable. Strings are objects but not primitive values. This implies, Strings have fields and methods on their own. Strings are enclosed in double quotation marks.

So you see, a field (which is an object) has fields and methods too. Don’t be confused! In simple terms, if the field of a class is an object (eg. a String), then it has its own fields and methods you can call.

String nameOfWebsite=“villagecoder”;

In the above statement, the String field is initialized to the value villagecoder. Because it’s a String, we can call one of its methods to perform operation on the value villagecoder.

Example, the statement nameOfWebsite.charAt(5) will print out g because g is the 5th character in the String villagecoder. charAt() is a pre-built method of the String class. Note that in Java, counting begins from 0, not 1 so g falls at the 5th position.

Now, is the ‘out’ field primitive or an object?

out is an object. This means out itself was created from another class. This class is called PrintStream class. This might sound confusing at a glance. The practice of creating an object from one class and using the object as a field in another class is called aggregation in Java.

out is public and static. public means it can be accessed by code outside the class. out is static means it belongs to the class but not instance of the class.

This implies that the class System can call its static field, out, straightaway without the need to create an instance (object) of System before calling the field, out. That is why we write:

System.out without creating any instance of the System class.

Methods of the out object

We have already established that, in Java, objects have both fields and methods which they can call when necessary. One of the methods of  out (which serves as a field for System class) is the print() method.

Putting it all together

So why don’t programmers type just System.print() but System.out.print()? In other words, why wasn’t the print() method made a method of the System class but rather made a method of another class called PrintStream?

The System class has a number of functions including taking  inputs and printing out data. Putting all these functions or methods under System would make it quite cumbersome.

Due to that, the brilliant designers of the Java language decided to group methods that perform similar functions under one umbrella and give them name.

Example, System methods that print out data are grouped together and given a class name PrintStream. To use PrintStream class, an object has to be created. One example of a PrintStream object is out, which is already created. Within the PrintStream class, we have methods such as print, println, printf, etc. Thus, the out object can call all these methods.

   System.out.print()

   System.out.println()

   System.out.printf()

System functions that accept inputs from outside sources are grouped together and given a class name called InputStream. One object of InputStream is called in which is a field of the System class, written as, System.in.

The print() method

The print method prints string on the console and keeps cursor on the same line.

The print method is found in the out object.

After printing, the print() method leaves the cursor on the same line. Hence, subsequent printing instructions will print on the same line. Let’s look at example

Output

Program demonstrates that the print method in Java prints and leaves cursor on the same line

The print method was called twice, one after the other. The first print method prints the message The print method and the cursor stays on the same line.

The second print method continues from where the cursor was left off. The cursor was left on the same line as the first statement. The second message leaves the cursor on the same line is printed in addition. The two messages appear on the same line in the output even though they were typed on different lines.

That is, print method displays text or message in a continuous stream.

Common errors associated with the print() method

Because the print method prints text and leaves the cursor on the same line, the displayed texts can be jammed up if space character is not left at the end of statements. 

Let’s look at an example.

Ouput

Program demonstrates that the print method jams strings of characters together if whitespace is not inserted at the beginning or end of strings

The output is displayed in one string although the code uses four print() methods to display the message on each line. This is because each print method leaves the cursor on the same line after displaying text. This jams the strings on the different lines up. There are no spaces left in between the different lines of strings.

To remedy this we can type space character at the end of the preceding statement or at the beginning of the succeeding one.

Let’s look at how this can be done.

Ouput

This program demonstrates how the space character problem with the print method can be solved

How to make print() method print on different lines

The print method displays text and keeps the cursor on the same line. There’s a way to force the cursor to the next line even if you use the print method. 

We type an escape character at the end of the string in order to force the cursor to the next line. An escape character begins with a backslash (\) and followed by a control sequence. There are different types of escape sequences. The escape sequence to move the cursor to next line is \n. n signifies newline.

Output

The print method
leaves the cursor
on the same
line.

The first print method displays The print method and gets to the escape sequence \n. This moves the cursor to the next line.

Note that the \n escape sequence is not printed by the print method. The print method interprets it as a special command and advances the cursor to the next line.

Escape Sequence

As the name suggests, an escape sequence enables the cursor to escape sequential movement of its path. An escape sequence is also called an escape character. 

An escape sequence begins with a backslash (\) not a forward slash. That’s, don’t type /n but type \n.

Also, there shouldn’t be any space left between the backslash (\) and the character. That’s, don’t type \ n but \n.

Escape sequence in Java

The print() method and data types

The text passed to the print method is normally a String. A String is an object and an object is a type of data in Java. There are other simple data types we call primitive data types. Examples of primitive data types in Java are int, double, float, short, byte, long, Boolean etc.

The print method can accept these data types and print on the console.

void print(boolean b) – Prints a boolean value.

Example

boolean status=true;

System.out.print(status);

Output

true

void print(char c) – Prints a character.

Example

char grade=’B’;

System.out.print(grade);

Output

B

void print(char[ ] s) – Prints an array of characters. .

Example

char[ ] grade={ ‘A‘,’B‘,’C’,’D‘,’E‘,’F‘};

System.out.print(grade);

Output

[A B C D E F]

void print(double d) –

Prints a double-precision floating-point number.

Example

double cost=34.7;

System.out.print(cost);

Output

34.5

void print(float f) –Prints a single-precision floating-point number.

Example

float cost=34.7f;

System.out.print(cost);

Output

34.7

void print(int i) –Prints an integer.

Example

int age=28;

System.out.print(age);

Output

28

void print(long l) –Prints a long integer.

Example

long age=28L;

System.out.print(age);

Output

28

void print(Object obj) –Prints an object.

Example

Object website==”www.villagecoder.com”;

System.out.print(website);

Output

www.villagecoder.com

void print(String s) –Prints a string.

Example

String website==”www.villagecoder.com”;

System.out.print(website);

Output

www.villagecoder.com

CAUTION : The print() method always needs arguments in order to execute. If arguments aren’t passed to it, it will cause an error.

System.out.print(); //error.No argument

Let’s look at a program that demonstrates that the print method creates an error without argument.

Output

The println() method

The println method displays text on the console just like the print method. However, the println method displays or prints text on the console and then moves the cursor to the beginning of the next line.

println is short for ‘print line’. That’s, println means print and move to next line

Like the print method, the println method also accepts several data types. Let’s look at these data types :

void println() – Terminates the current line by writing the line separator string.

void println(boolean x) – Prints a boolean and then terminates the line. 

void println(char x) – Prints a character variable and then terminates the line. 

void println(char[] x) – Prints an array of characters and then terminate the line. 

void println(double x) – Prints a double variable and then terminates the line. 

void println(float x) – Prints a float variable and then terminates the line. 

void println(int x) – Prints an integer variable and then terminates the line. 

void println(long x) – Prints a long variable and then terminates the line. 

void println(Object x) – Prints an Object and then terminates the line. 

void println(String x) – Prints a String variable and then terminates the line.

Program demonstrates the println() method

Output

Program demonstrates the println method in Java

The println method prints or displays text and moves to the next line. We see that each invocation of the println method displays its text on a new line. Four println methods were called and statements were displayed on four different lines.

The first println displays This is the list of items: and then moves the cursor to the next line. The second println displays Sugar and moves the cursor to the next line. The third println method displays Bread and then moves the cursor to the next line. The fourth println method displays Chocolate and moves cursor to next line.

Using the println method to print empty spaces

The println method can execute without argument. This makes it possible to use it to print spaces between lines of code in order to make the code neat.

Output

println method is used to print whitespaces

We called the println method to display statements on the console. The first statement is :

System.out.println(“This is statement One”);  This displays This is statement One

After displaying this message, the cursor moves to the next line. Here we call the println method again but we do not pass any argument to it. Thus, it prints an empty space and moves to the third line.

We call the println method again and pass the statement “This is statement Two“. This gets printed and the cursor advances to the next line.

We call the println method again yet does not pass it any argument. This prints an empty space and the cursor moves to next line.

We call the println method again and pass the statement “This is statement Three“. This gets printed and the cursor advances to the next line.

Here, we call the println method three times in succession without passing any argument to it. The reason is to create three empty lines of space.

System.out.println();. //leave a space

System.out.println(); //leave a space

System.out.println();//leave a space

We want to separate the statements above from the next group of statements. 

We call the println statements again this time passing arguments to it in each case.

System.out.println(“This is statement Four”);.

System.out.println(“This is statement Five”);

System.out.println(“This is statement Six”);

Because we do not print any space in between these statements, we see the statements stacked to each other.

println method is used to print whitespaces2

Differences between print and println method

We summarize the differences between the print and println method.

print() println()
Prints text and remains on same line prints text and moves to the next line
It always needs argument to execute else error will occur It can execute without argument. In such casse, it prints empty line of space.

If you enjoyed this article, consider joining our Telegram and WhatSapp groups for more.

What do you think? Don’t you have anything to add? Leave your comment below and I will respond swiftly.

Click to Watch a Video Tutorial

print and println methods

You May Also Like…


double data type in Java

double data type in Java

The double data type is also a floating point number. It is called double because it has a...

float data type in Java

float data type in Java

It is a floating point number. It has single precision data type. It stores a floating point...



0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *