Print Function in Java
The humble print function forms the backbone of basic program debugging. By printing out selected strings to the terminal, it allows you to monitor the program's execution as it runs. The syntax of this function is different in Java than in many other programming languages. It is "System.out.print(String str)", where "str" is the string you want to print. You can also print characters, objects and numbers.
-
"System.out.print"
-
The basic command for printing in Java is "System.out.print(String str)". This command outputs the contents of the given character string onto the main console window. You can also use "System.out.println(String str)", which prints the characters and then prints a newline character, ensuring that the next print statement you make is on a new line.
How the print function works
-
"System.out" is a static variable, a PrintStream object which always refers to the basic output String, often corresponding to a console window. The Java runtime environment opens this stream before the program's execution.The method "PrintStream.print()" then prints the characters it specifies into the stream. In addition, when you print out an object, you automatically call that object's "toString()" method. By default, this method returns a string that identifies the object's class, name and hashcode value, though some classes override the default method.
-
String Formatting
-
When you use Java's print function to print a string of characters, you can either refer to an existing String variable or determine the message when you call the function. Surround the message you want to print in quotes; and if you want to include variables in the print statement, link the strings and variables together with a "+" sign. For instance, if you wanted to print a particular variable called "numRevolutions," and you wanted to put a label "Number of Revolutions" on it, it would be something like this:
System.out.println("Number of Revolutions" + numRevolutions);
Other Print Statements
-
Though "System.out.println()" is the default print statement in Java, you can use "System.err.println()". System.err is a PrintStream similar to System.out, used to print out information related to errors encountered during execution. Depending on the execution environment, error statements may be routed to a log or formatted differently from ordinary print statements.
-