This code invokes the println method of the object out that is a static data member of the class System. The object out is of type java.io.PrintStream. PrintStream provides both a println method and a print method. Both methods can take as input strings (as shown above) or ints, chars, doubles, floats, longs, and booleans. The print method prints the data and does not advance to the next line. The println method prints the data given and then prints a newline.
The code above demonstrates the difference between print and println. It also demonstrates string concatenation. Two strings can be concatenated using the + operator.
Scanner class. An example follows:
A few things to note:
import java.util.Scanner;The Scanner also provides method nextInt, nextDouble, and so on. You can use these methods to retrieve data of a particular type.
It becomes a bit tricky, however, to retrieve different types of data.
In the example above, the scanner will retrieve the number entered by the user, but will leave a newline character in the buffer. When the scanner retrieves the next line of text, it thinks that there is already a line in the buffer, and will not wait for the user to enter new data.
One way to deal with this is to clear the buffer after the nextInt call by calling nextLine until the method hasNext of the Scanner returns false. Another option is to read all input as text and convert Strings to ints or doubles where appropriate.