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:
But all I get is this:
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:
System.out.print(message);
System.out.println(message);
System.err.print(message);
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:
java.lang.System
, java.io.PrintWriter
and java.io.Console
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With