how to print in java

how to print in java

12 hours ago 6
Nature

In Java, you can print text or other values to the console using the following methods:

  1. System.out.println():
    • This method prints the text or value and moves the cursor to a new line after printing.

    • Example:

      java
      
      System.out.println("Hello World!");
      System.out.println("I am learning Java.");
      
    • Each call to println() results in output on a new line.

  2. System.out.print():
    • This method prints the text or value but does not move to a new line afterward. The cursor stays on the same line.

    • Example:

      java
      
      System.out.print("Hello ");
      System.out.print("World!");
      
    • The output will be on the same line: "Hello World!"

  3. System.out.printf():
    • This method is used to print formatted text using format specifiers.

    • Example:

      java
      
      double value = 5.984;
      System.out.printf("%.2f", value);  // Prints value with 2 decimal places: 5.98
      

For printing variables along with text:

java

String name = "John";
System.out.println("Hello " + name);

For numeric calculations:

java

int x = 5;
int y = 6;
System.out.println(x + y);  // Outputs 11

In summary:

  • Use println() to print with a newline.
  • Use print() to print without a newline.
  • Use printf() for formatted output.

These methods are part of the System.out object which is an instance of PrintStream class in Java used for console output.

Read Entire Article