Java system out object

System.out.println() in Java explained with examples

In java, we use System.out.println() statement to display a message, string or data on the screen. It displays the argument that we pass to it.

Let’s understand each part of this statement:

  1. System: It is a final class defined in the java.lang package.
  2. out: It is an instance of PrintStream type and its access specifiers are public and final
  3. println(): It is a method of PrintStream class.

As we know that we need to create the object of a class to invoke its method. Here instead of creating the object of the PrintStream class we use System.out, it internally creates the object of PrintStream class so we can use the statement System.out.println() to invoke println() method.

Example 1: Displaying Strings using System.out.println()

Here we are displaying three Strings using System.out.println() statements.

Output: Since we are using println() method, the strings are displayed in new lines, if there is a need to display the strings in a single line, use print() method instead.

Example 2: Displaying the variable values using println() method

In the above example, we simply passed the strings that we wanted to be displayed as output. However, we can do so much more with the println() method. We can pass the variable name in this method and it can read and display the value of the passed variable as output.

The product of 10 and 20 is: 200

Overloading of println() method

We learned in Overloading in Java that we can have more than one methods with the same name but different signatures.

The println() method belongs to the PrintStream class and this class has total 10 overloaded variants of println() method. The overloaded methods are invoked based on the arguments passed by the user.

Some of the overloaded methods are as follows. If user passes int to the println() method, it invokes the overloaded method with int parameter and if the passed parameter is of String type, it invokes String variant and so on.

System.out.println() System.out.println(int) System.out.println(double) System.out.println(boolean) System.out.println(String) System.out.println(char)

Difference between print() and println() methods

System.out.print(): This method displays the result on the screen and the cursor remains at the end of the the printed line. The next printing starts in the same line where the cursor is at. This method will only work when there is at least one parameter passed to it else it will throw an error.

System.out.println(): Like print() method, this method also displays the result on the screen based on the parameter passed to it. However unlike print() method, in this method the cursor jumps to the next line after displaying the result, which means the next printing starts in the new line. This method doesn’t throw an error if no parameters are passed in it.

Читайте также:  How to upgrade python on mac os

Let’s take an example to see this in action.

print() statements: This is just a String println() statements: This is just a String

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Formatting

Stream objects that implement formatting are instances of either PrintWriter , a character stream class, or PrintStream , a byte stream class.

Note: The only PrintStream objects you are likely to need are System.out and System.err . (See I/O from the Command Line for more on these objects.) When you need to create a formatted output stream, instantiate PrintWriter , not PrintStream .

Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. Two levels of formatting are provided:

  • print and println format individual values in a standard way.
  • format formats almost any number of values based on a format string, with many options for precise formatting.

The print and println Methods

Invoking print or println outputs a single value after converting the value using the appropriate toString method. We can see this in the Root example:

Here is the output of Root :

The square root of 2 is 1.4142135623730951. The square root of 5 is 2.23606797749979.

The i and r variables are formatted twice: the first time using code in an overload of print , the second time by conversion code automatically generated by the Java compiler, which also utilizes toString . You can format any value this way, but you don’t have much control over the results.

The format Method

The format method formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.

Format strings support many features. In this tutorial, we’ll just cover some basics. For a complete description, see format string syntax in the API specification.

The Root2 example formats two values with a single format invocation:

The square root of 2 is 1.414214.

Like the three used in this example, all format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output being generated. The three conversions used here are:

  • d formats an integer value as a decimal value.
  • f formats a floating point value as a decimal value.
  • n outputs a platform-specific line terminator.

Here are some other conversions:

  • x formats an integer as a hexadecimal value.
  • s formats any value as a string.
  • tB formats an integer as a locale-specific month name.

There are many other conversions.

Except for %% and %n , all format specifiers must match an argument. If they don’t, an exception is thrown.

Читайте также:  Html get form array

In the Java programming language, the \n escape always generates the linefeed character ( \u000A ). Don’t use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n .

In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output. Here’s an example, Format , that uses every possible kind of element.

3.141593, +00000003.1415926536

The additional elements are all optional. The following figure shows how the longer specifier breaks down into elements.

Elements of a Format Specifier.

The elements must appear in the order shown. Working from the right, the optional elements are:

  • Precision. For floating point values, this is the mathematical precision of the formatted value. For s and other general conversions, this is the maximum width of the formatted value; the value is right-truncated if necessary.
  • Width. The minimum width of the formatted value; the value is padded if necessary. By default the value is left-padded with blanks.
  • Flags specify additional formatting options. In the Format example, the + flag specifies that the number should always be formatted with a sign, and the 0 flag specifies that 0 is the padding character. Other flags include — (pad on the right) and , (format number with locale-specific thousands separators). Note that some flags cannot be used with certain other flags or with certain conversions.
  • The Argument Index allows you to explicitly match a designated argument. You can also specify < to match the same argument as the previous specifier. Thus the example could have said: System.out.format("%f, %

Источник

I/O from the Command Line

A program is often run from the command line and interacts with the user in the command line environment. The Java platform supports this kind of interaction in two ways: through the Standard Streams and through the Console.

Standard Streams

Standard Streams are a feature of many operating systems. By default, they read input from the keyboard and write output to the display. They also support I/O on files and between programs, but that feature is controlled by the command line interpreter, not the program.

The Java platform supports three Standard Streams: Standard Input, accessed through System.in ; Standard Output, accessed through System.out ; and Standard Error, accessed through System.err . These objects are defined automatically and do not need to be opened. Standard Output and Standard Error are both for output; having error output separately allows the user to divert regular output to a file and still be able to read error messages. For more information, refer to the documentation for your command line interpreter.

You might expect the Standard Streams to be character streams, but, for historical reasons, they are byte streams. System.out and System.err are defined as PrintStream objects. Although it is technically a byte stream, PrintStream utilizes an internal character stream object to emulate many of the features of character streams.

By contrast, System.in is a byte stream with no character stream features. To use Standard Input as a character stream, wrap System.in in InputStreamReader .

InputStreamReader cin = new InputStreamReader(System.in);

The Console

A more advanced alternative to the Standard Streams is the Console. This is a single, predefined object of type Console that has most of the features provided by the Standard Streams, and others besides. The Console is particularly useful for secure password entry. The Console object also provides input and output streams that are true character streams, through its reader and writer methods.

Before a program can use the Console, it must attempt to retrieve the Console object by invoking System.console() . If the Console object is available, this method returns it. If System.console returns NULL , then Console operations are not permitted, either because the OS doesn’t support them or because the program was launched in a noninteractive environment.

The Console object supports secure password entry through its readPassword method. This method helps secure password entry in two ways. First, it suppresses echoing, so the password is not visible on the user’s screen. Second, readPassword returns a character array, not a String , so the password can be overwritten, removing it from memory as soon as it is no longer needed.

The Password example is a prototype program for changing a user’s password. It demonstrates several Console methods.

import java.io.Console; import java.util.Arrays; import java.io.IOException; public class Password < public static void main (String args[]) throws IOException < Console c = System.console(); if (c == null) < System.err.println("No console."); System.exit(1); >String login = c.readLine("Enter your login: "); char [] oldPassword = c.readPassword("Enter your old password: "); if (verify(login, oldPassword)) < boolean noMatch; do < char [] newPassword1 = c.readPassword("Enter your new password: "); char [] newPassword2 = c.readPassword("Enter new password again: "); noMatch = ! Arrays.equals(newPassword1, newPassword2); if (noMatch) < c.format("Passwords don't match. Try again.%n"); >else < change(login, newPassword1); c.format("Password for %s changed.%n", login); >Arrays.fill(newPassword1, ' '); Arrays.fill(newPassword2, ' '); > while (noMatch); > Arrays.fill(oldPassword, ' '); > // Dummy change method. static boolean verify(String login, char[] password) < // This method always returns // true in this example. // Modify this method to verify // password according to your rules. return true; >// Dummy change method. static void change(String login, char[] password) < // Modify this method to change // password according to your rules. >>

The Password class follows these steps:

  1. Attempt to retrieve the Console object. If the object is not available, abort.
  2. Invoke Console.readLine to prompt for and read the user’s login name.
  3. Invoke Console.readPassword to prompt for and read the user’s existing password.
  4. Invoke verify to confirm that the user is authorized to change the password. (In this example, verify is a dummy method that always returns true .)
  5. Repeat the following steps until the user enters the same password twice:
    1. Invoke Console.readPassword twice to prompt for and read a new password.
    2. If the user entered the same password both times, invoke change to change it. (Again, change is a dummy method.)
    3. Overwrite both passwords with blanks.

    Источник

Оцените статью