In this lesson, we will explore how to use the println()
method to print numbers in Java, as well as how to perform basic arithmetic operations within the println()
method.
Printing Numbers with println()
You can use the println()
method to print numbers in Java. Unlike text, numbers do not need to be enclosed in double quotes.
Example:
System.out.println(7); System.out.println(123); System.out.println(45678);
Performing Mathematical Calculations
You can also perform basic arithmetic operations directly inside the println()
method. This allows you to print the result of the calculation.
Example:
System.out.println(5 + 5);
Example:
System.out.println(4 * 6);
In the examples above, the println()
method evaluates the expressions 5 + 5
and 4 * 6
and prints their results, which are 10
and 24
respectively.
Additional Information
- Combining Text and Numbers: You can combine text and numbers in the
println()
method using the+
operator. Example:
int apples = 5; System.out.println("I have " + apples + " apples.");
- Escape Characters: To include special characters such as newlines (
\n
) or tabs (\t
) in your text, you can use escape sequences. Example:
System.out.println("First Line\nSecond Line");
This will print:
First Line Second Line
- The print() Method: Similar to
println()
, theprint()
method does not add a new line at the end of the output. Use it when you want to continue printing on the same line. Example:
System.out.print("Numbers: "); System.out.print(10); System.out.print(", "); System.out.print(20);
This will print:
Numbers: 10, 20