next up previous contents
Next: Arithmetic operators Up: 1 Programming Basics Previous: Variables declaring   Contents

Simple output

In the Hello program you used the line System.out.println("Hello") to write `Hello' to the screen. This is the standard way of outputting to the screen and it works for numbers and variables (see previous section) as well. If you want to print several things at the same time you can use the + symbol as follows.

System.out.println("Hello" + 1.234);
System.out.println("Hello " + "number " + 1.234);
System.out.println("The value of variable x is: " + x);
The first two commands result in the outputs `Hello1.234' and `Hello number 1.234' respectively. The third command will print to the screen `The value of variable x is: ' followed by whatever number, character, or string, is stored in the x.

You can add separate Strings together using +, e.g. String name = "Bob" + " Smith". Or String id = "abc" + 1.4 creates a string called id which stores `abc1.4'. Here 1.4 is a number but it is automatically converted into a string before being added to "abc". We explore strings a little more in the next section, which is on output, where you will see that it is equally possible to have instead of a number, a variable, where the value of the variable is added to the string in the same way that the number is above.

Exercise 1.4


(4 marks)



Try programming output yourself.



If you wish to print several things to the screen on the same line without using + all the time, you can use System.out.print() which works in the same way as the System.out.println() you've just been using, but will not move to the next line each time.


next up previous contents
Next: Arithmetic operators Up: 1 Programming Basics Previous: Variables declaring   Contents
RHUL Dept. of Physics