Introduce Java Print Variables and give examples
In Java, printing variables is a common task that allows developers to display the values of variables to the console or standard output. This is typically done using the System.out.print()
, System.out.println()
, or System.out.printf()
methods. Each of these methods has its own use case:
System.out.print()
: This method prints the text to the console without adding a new line at the end.System.out.println()
: This method prints the text to the console and adds a new line at the end, moving the cursor to the next line.System.out.printf()
: This method allows for formatted output, similar to the printf
function in C. It provides more control over how the output is displayed.Here are some examples demonstrating how to print variables in Java:
System.out.print()
public class PrintExample {
public static void main(String[] args) {
int number = 10;
String message = "The number is: ";
System.out.print(message); // Prints without a new line
System.out.print(number); // Prints the number
}
}
Output:
The number is: 10
System.out.println()
public class PrintExample {
public static void main(String[] args) {
int number = 10;
String message = "The number is: ";
System.out.println(message); // Prints with a new line
System.out.println(number); // Prints the number on a new line
}
}
Output:
The number is:
10
System.out.printf()
public class PrintExample {
public static void main(String[] args) {
double price = 19.99;
String item = "Book";
System.out.printf("The price of the %s is $%.2f%n", item, price);
}
}
Output:
The price of the Book is $19.99
printf
Format Specifiers%s
: This is a format specifier for strings.%.2f
: This is a format specifier for floating-point numbers, where .2
indicates that two decimal places should be displayed.%n
: This is a platform-independent newline character.Printing variables in Java is straightforward and can be done using different methods depending on the desired output format. The choice between print
, println
, and printf
depends on whether you want to control line breaks and formatting.