Write a program to print message without using println() method in java?

Java 8Object Oriented ProgrammingProgramming

The println() method of the System class accepts aStringas parameter an prints the given String on the console.

Example

public class PrintData {
   public static void main(String args[]) {
      System.out.println("Hello how are you");
   }
}

Output

Hello how are you

In addition to this you can print data on the console in several other ways, some of them are −

Using Output Streams

Using output stream classes, you can write dat on the specified destination. You can print data on the screen/console by passing the standard output Stream object System.out as source to them.

Example

import java.io.IOException;
import java.io.OutputStreamWriter;
public class PrintData {
   public static void main(String args[]) throws IOException {
      //Creating a OutputStreamWriter object
      OutputStreamWriter streamWriter = new OutputStreamWriter(System.out);
      streamWriter.write("Hello welcome to Tutorialspoint . . . . .");
      streamWriter.flush();
   }
}

Output

Hello welcome to Tutorialspoint . . . . .

Using the printf() and print() methods

The PrintStream class of Java provides two more methods to print data on the console (in addition to the println() method).

The print() − This method accepts a single value of any of the primitive or reference data types as a parameter and prints the given value on the console.

(double value or, a float value or, an int value or, a long value or, a char value, a boolean value or, a char array, a String or, an array or, an object)

The printf() − This method accepts a local variable, a String value representing the required format, objects of variable number representing the arguments and, prints data as instructed.

Example

public class PrintData {
   public static void main(String args[]) {
      System.out.print("Hello how are you");
      System.out.printf(" "+"welcome to Tutorialspoint");
   }
}

Output

Hello how are you Welcome to Tutorialspoint

Using log4j

The Logger class of the log4j library provides methods to print data on the console.

Dependency

<dependencies>
   <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.4</version>
   </dependency>
   <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.4</version>
   </dependency>
</dependencies>

Example

import java.util.logging.Logger;
public class PrintData{
   static Logger log = Logger.getLogger(PrintData.class.getName());
   public static void main(String[] args){
      log.info("Hello how are you Welcome to Tutorialspoint");
   }
}

Output

Jun 28, 2019 2:49:25 PM Mypackage.PrintData main
INFO: Hello how are you Welcome to Tutorialspoint
raja
Published on 01-Aug-2019 15:57:57
Advertisements