Making Java Speak: Understanding Output
So far, we’ve explored the basic syntax, variables and data types. In this blog we’ll see how and where Java displays information to us with a few fun exercises waiting for you at the end.
What is output?
Output is the information displayed by a program, either in a terminal, a browser, or another interface.
In the example below, I’m printing the output(result) in my terminal. If you’re wondering what a terminal is, then consider it like your notebook but only text based. For me it is the playground where I experiment with and test my code.
Now, let’s decode each keyword in line 5, for the remaining code we’ve covered in the previous blog.
- System — A built-in Java class that provides access to standard input, output and error streams.
- out — The standard output stream used to display information on the screen.
- println() — A method that prints whatever is inside the parentheses and then moves the cursor to the next line (ln is new line).
Let’s take a look at the example above, (‘a’) represents a character hence the single quotes. (“Learning Java …”) is a string hence the double quotes. Now look carefully (“I ate 2 apples”) here 2 is an integer but since it is within the double quotes it gets represented as a string and lastly (2) has no quotes since we want it to be printed as integer.
Get ScriptedMind’s stories in your inbox
Join Medium for free to get updates from this writer.
You might be wondering why not represent the integer 2 within the quotes like a string, apart from the memory allocation what else matters here. Well there is more to it, let’s take a look at the example below:
One might wonder how (2 + 2) returns 4 and (“2” + “2”) returns 22 and not 4 or 2 2, this concept is called Concatenation. The + operator behaves differently depending on the data type involved. When used with numbers, it performs addition. When used with strings, it joins them together.You can think of it as a glue that sticks pieces of text together.
Let’s practice this concept, what would be the output of
String name = "Mickey";
System.out.print(name + " Mouse");Now, we’ll see what’s the difference between print() and println(). print() will print the output on the same line whereas, println() will print the output on a new line.
Exercises:
What is the output of the following:
int age = 18;
System.out.println("The eligible age to cast a vote is " + age);System.out.println(5 + 5);
System.out.println("5" + 5);
System.out.println("5" + "5");System.out.print("Hello ");
System.out.print("World");Don’t run the code just yet. Try predicting the output first and then verify your answers by running the program. Programming becomes much more fun when you guess before you execute.









