Basic Output
Java Output
You can simply use System.out.println()
, System.out.print()
or System.out.printf()
to send output to standard output (screen).
System
is a class and out
is a public static
field which accepts output data. Don't worry if you don't understand it. Classes
, public
, and static
will be discussed in later chapters.
Let's take an example to output a line.
class AssignmentOperator {
public static void main(String[] args) {
System.out.println("Java programming is interesting.");
}
}
When you run the program, the output will be:
Java programming is interesting.
Here, println
is a method that displays the string inside quotes.
What's the difference between println(), print() and printf()?
-
print()
- prints string inside the quotes. -
println()
- prints string inside the quotes similar likeprint()
method. Then the cursor moves to the beginning of the next line. -
printf()
- it provides string formatting (similar to printf in C/C++ programming).
Example: print() and println()
class Output {
public static void main(String[] args) {
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
When you run the program, the output will be:
1. println 2. println 1. print 2. print
Visit this page to learn about Java printf().
To display integers, variables and so on, do not use quotation marks.
Example: Printing Variables and Literals
class Variables {
public static void main(String[] args) {
Double number = -10.6;
System.out.println(5);
System.out.println(number);
}
}
When you run the program, the output will be:
5 -10.6
You can use + operator to concatenate strings and print it.
Example: Print Concatenated Strings
class PrintVariables {
public static void main(String[] args) {
Double number = -10.6;
System.out.println("I am " + "awesome.");
System.out.println("Number = " + number);
}
}
When you run the program, the output will be:
I am awesome. Number = -10.6
Consider: System.out.println("I am " + "awesome.")
;
Strings "I am "
and "awesome."
is concatenated first before it's printed on the screen.
Consider: System.out.println("Number = " + number)
;
The value of variable number
is evaluated first. It's value is in double
which is converted to string by the compiler. Then, the strings are concatenated and printed on the screen.