In this lesson, we will explore how to use the println()
and print()
methods to output values or text in Java.
Print Text with println()
You learned from the previous lesson that you can use the println()
method to print text in Java. The println()
method prints the text and then moves to a new line.
Example:
System.out.println("Hello, Java!");
You can add multiple println()
methods to print several lines of text. Each println()
method will add a new line to the output.
Example:
System.out.println("Hello, Java!"); System.out.println("I am mastering Java."); System.out.println("It's fascinating!");
Double Quotes
Text to be printed must be enclosed within double quotation marks (""
). If you forget the double quotes, Java will throw an error.
Example:
System.out.println("This will work!"); System.out.println(This will cause an error);
The print() Method
The print()
method is similar to println()
, but it does not add a new line at the end of the output. This means that the next text will be printed on the same line.
Example:
System.out.print("Hello, Java! "); System.out.print("This will print on the same line.");
In the example above, an extra space is added after “Hello, Java!” for better readability.
Additional Information
- Escape Characters: To include special characters in your text, such as a newline (
\n
) or tab (\t
), you can use escape sequences. For example,System.out.println("First Line\nSecond Line");
will print:
First Line Second Line
- Combining Text and Variables: You can combine text and variables in the
println()
orprint()
methods using the+
operator. Example:
int age = 25; System.out.println("I am " + age + " years old.");