Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

PrintWriter write() vs print() Method in Java

$
0
0

1. Introduction

In this article, we’ll talk about the PrintWriter class of the Java IO package. Specifically, we’ll discuss two of its methods, write() and print(), and their differences.

The PrintWriter class prints formatted representations of objects to a text-output stream. Methods in this class never throw I/O exceptions. However, there is the possibility that some of its constructors may. To use these methods, we must call the PrintWriter constructor and offer as an argument a file, a file name, or an output stream.

2. PrintWriter.write()

The write() method has five overloaded versions, two for char, two for String, and one for intThis method is only one of the possible ways we can write to console or files.

Furthermore, the char and String versions can either write a whole char[] or a String, or portions of the array or String. In addition, the int version writes a single character – the ASCII symbol equivalent to the decimal input given.

First, let’s have a look at the write(int c) version:

@Test
void whenUsingWriteInt_thenASCIICharacterIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    printWriter.write(48);
    printWriter.close();
    assertEquals(0, outputFromPrintWriter());
}

We passed 48 as an argument to the write() method and obtained 0 as the output. Furthermore, if we check the ASCII table we see that the corresponding symbol for the 48 DEC input is number 0. If we pass another value, let’s say 64, then the printed output will be number 4.

Here, outputFromPrintWriter() is simply a service method that reads what the write() method writes in the file, so we can compare the values:

Object outputFromPrintWriter;
Object outputFromPrintWriter() {
    try (BufferedReader br = new BufferedReader(new FileReader("output.txt"))){
        outputFromPrintWriter = br.readLine();
    } catch (IOException e){
        e.printStackTrace();
        Assertions.fail();
    }
    return outputFromPrintWriter;
}

Now, let’s take a look at the second version – write(char[] buf, int off, int len) – which writes a portion of the array, from a given starting position and up to a given length:

@Test
void whenUsingWriteCharArrayFromOffset_thenCharArrayIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    printWriter.write(new char[]{'A','/','&','4','E'}, 1, 4);
    printWriter.close();
    assertEquals("/&4E", outputFromPrintWriter());
}

As we can see from the test above, the write() method took the four characters we specified from the desired offset and printed them to the output.txt file.

Let’s analyze the second version of the write(String s, int off, int len) method. This writes a portion of the String, from a given starting position and up to a given length:

@Test
void whenUsingWriteStringFromOffset_thenLengthOfStringIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    printWriter.write("StringExample", 6, 7 );
    printWriter.close();
    assertEquals("Example", outputFromPrintWriter());
}

3. PrintWriter.print()

The print() method has nine overloaded versions of itself. It can take the following types as arguments: boolean, char, char[], double,  float, int, long, Object, and String.

The behavior of the print() method is similar throughout its variations. For every type, except String and char, the string produced by the String.valueOf() method is translated into bytes. This translation is according to the platform’s default character encoding, and the bytes are written in the same way as the write(int) version.

First, let’s have a look at the print(boolean b) version:

@Test
void whenUsingPrintBoolean_thenStringValueIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    printWriter.print(true);
    printWriter.close();
    assertEquals("true", outputFromPrintWriter());
}

Now, let’s take a look at print(char c) :

@Test
void whenUsingPrintChar_thenCharIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    printWriter.print('A');
    printWriter.close();
    assertEquals("A", outputFromPrintWriter());
}

This is how print(int i) works:

@Test
void whenUsingPrintInt_thenValueOfIntIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    printWriter.print(420);
    printWriter.close();
    assertEquals("420", outputFromPrintWriter());
}

Let’s see what the print(String s) version outputs:

@Test
void whenUsingPrintString_thenStringIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    printWriter.print("RandomString");
    printWriter.close();
    assertEquals("RandomString", outputFromPrintWriter());
}

Here’s a test for print(Object obj):

@Test
void whenUsingPrintObject_thenObjectToStringIsPrinted() throws FileNotFoundException {
    PrintWriter printWriter = new PrintWriter("output.txt");
    Map example = new HashMap();
    printWriter.print(example);
    printWriter.close();
    assertEquals(example.toString(), outputFromPrintWriter());
}

As we can see from the example above, calling the print() method and passing an object as the argument prints the toString() representation of that object.

4. Differences Between the write() and print() Methods

The differences between the two methods are subtle, so we need to pay attention to them.

write(int) writes only one character. It outputs the ASCII symbol equivalent to the passed argument.

Moreover, the print(typeOfData) converts the argument of type char, int, etc. to a String by calling String.valueOf(typeOfData). This String is translated into bytes according to the platform’s default character encoding and its bytes are written the same way as write(int).

Unlike print() method, write() method handles only single characters, strings, and arrays of characters. The print() method covers many argument types, transforming them into printable strings of characters using String.valueOf().

5. Conclusion

In this tutorial, we’ve explored PrintWriter class and, more specifically, the write() and print() methods. As we saw, the PrintWriter class makes available several methods that help us print data to the output. The write() method prints the characters passed to it, while print() method translates the output.

As always, the code is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>