Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a string on the console?

Tags:

java

console

Given a string value, how can I display it on the screen in my console? What do I have to write to make that happen?

As an example, this is the code I have so far:

public class Main {
    public static void main(String[] args) {
        String message = "I am a school student and just started learning Java.";
        // What to write next?
    }
}

It works, but it obviously does not display the value on the console yet. What do I have to write to show it?


I want it to look something like this: enter image description here

But all I get is this:

enter image description here

like image 484
Nifi Avatar asked Mar 02 '23 11:03

Nifi


2 Answers

By default, a Java program doesn't print anything. You need to explicitly tell your program to print output. Here are some of the ways that you can do that:

  1. To print a String to standard output:
System.out.print(message);
  1. To print a String followed by a (platform appropriate) line separator:
System.out.println(message);
  1. To print a String to the standard error stream:
System.err.print(message);
  1. To print to the console (e.g. if standard output could have been redirected to a file):
Console console = System.console();
if (console != null) { // Note that in some contexts there
                       // is not a usable `Console`...
    console.writer().print(message);
}

Note that the above print and println methods are defined by the PrintWriter class. There are convenience overloads for all of the primitive types, and also for Object. In the latter case, what is printed is the result of calling toString() on the argument.

There are also printf methods for formatting a number of arguments according to a format string.


For more information, read the following:

  • The javadocs for java.lang.System, java.io.PrintWriter and java.io.Console.
  • Oracle Java Tutorials: The Hello World Application.
like image 63
4 revs, 2 users 80% Avatar answered Mar 06 '23 10:03

4 revs, 2 users 80%


System.out.print(message);
// or
System.out.println(message); // creates a new line after print is done.

There are many great courses on YouTube or the web for free which cover all basics and also intermediate topics.

Surf the internet about a problem before asking here. I'm not telling you that you can't ask here but you should put some effort into researching before asking.

like image 44
Charan Reigns Avatar answered Mar 06 '23 11:03

Charan Reigns