0% completed
In Java, the System class provides access to the system, including input and output through standard streams. In particular, the out object (an instance of the PrintStream class) is used for displaying output on the console. Java offers several methods to print text on the console:
Below, we explain these methods and show examples that print variables and concatenated strings.
This method prints a message to the console and then moves the cursor to a new line.
Here, we declare an integer variable num
and a string variable text
. Using System.out.println()
, we print a concatenated string that includes the variable values. After printing, the cursor moves to a new line for the next output.
This method prints text without moving the cursor to a new line. It is useful when you want to continue printing on the same line.
Here, we declare two string variables, firstPart
and secondPart
. By using System.out.print()
, we output both strings consecutively on the same line without inserting a new line between them.
The System.out.printf()
method allows you to print formatted text. This method is particularly useful for controlling how numbers and text appear in the output. You can use format specifiers to define the output format, such as specifying the number of decimal places or aligning text.
The table below shows some of the commonly used format specifiers:
Specifier | Description | Example |
---|---|---|
%d | Prints a decimal (integer) number | System.out.printf("%d", 123); outputs 123 |
%f | Prints a floating-point number | System.out.printf("%.2f", 12.3456); outputs 12.35 |
%s | Prints a string | System.out.printf("%s", "Hello"); outputs Hello |
%c | Prints a single character | System.out.printf("%c", 'A'); outputs A |
%n | Inserts a platform-independent newline | System.out.printf("%n"); outputs a newline |
%b | Prints a boolean value | System.out.printf("%b", true); outputs true |
Explanation:
%.2f
to round the piValue
to 2 decimal places.%d
to print the integer count
.%s
to include the message
variable.%f
, %d
, and %s
in a single statement to print all the variables together in a formatted manner.These methods form the basis of console output in Java, enabling you to display data, variables, and even formatted messages efficiently. Experiment with these examples in your code editor to see how each method works and how you can combine them with variables and concatenated strings.
.....
.....
.....