Java Output
Java Output: In Java, you can produce output using the System.out.print, System.out.println, and System.out.printf methods. Here are some examples to illustrate how each of these works:
Using System.out.print
The print method prints the text to the console without adding a new line at the end.
public class PrintExample {
public static void main(String[] args) {
System.out.print("Hello, ");
System.out.print("world!");
}
}
Output:
Hello, world!
Using System.out.println
The println method prints the text to the console and adds a new line at the end.
public class PrintlnExample {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println("This is a new line.");
}
}
Output:
Hello, world!
This is a new line.
Using System.out.printf
The printf method allows you to format strings using format specifiers. It’s useful for creating formatted output.
public class PrintfExample {
public static void main(String[] args) {
int age = 25;
String name = "Alice";
System.out.printf("Name: %s, Age: %d", name, age);
}
}
Output:
Name: Alice, Age: 25
Summary
System.out.print: Prints text without a newline.System.out.println: Prints text with a newline.System.out.printf: Prints formatted text using format specifiers.
By using these methods, you can control how output is displayed in your Java programs.