Pages

Sunday, June 17, 2012

Console prints


In this seccion, we are going to studie how to print messages in the console. There is two message types which can be printed in console, the error messages and the rest. The error messages normally appears with another style, in red for example, specially if you use an IDE programm to launch your application. Here is an example of the two types:
System.out.println("This is an info message");
System.err.println("This is an error message");

Both message types owns to the System class, and have the same methods to print messages. Basically, you can print in a single line (print), or have a return line at the end of your message (println). Here are some examples:
System.out.print("The next message of this one will be printed in the same line.");
System.out.println(" This message will be printed in the same line as the previous one.");
System.out.println("This will be in the second line.");

Output:
The next message of this one will be printed in the same line. This message will be printed in the same line as the previous one.
This will be in the second line.

In the case of the prints in the same line, you must take care of the spaces between the messages.

To print the values of variables in the middle of messages, you must cut the message where you want to put a variable, and then write the name of the variable inside. To cut a message you only have to close the accuotations and add the + signal to add some other stuff you want to print, like another message, variable values... Here are some examples:
int a = 5;
System.out.println("The variable a = " + a);
System.out.println("Message one " + "followed by " + "Message two");

Output:
The variable a = 5
Message one followed by Message two

The variable you want to print must be inicialized. And to print arrays or list, you must specifie which element one the collection you want to print, otherwise the direction of the object will be printed. And if the variable is not inicialized, a NullPointerException will be thrown. Here is an example:
int[] a = new int[5];
a[0] = 1; a[1] = 2; a[2] = 2; a[3] = 5; a[4] = 7;
System.out.println("The forth element of the array is " + a[3]);

Output:
The forth element of the array is 5

No comments:

Post a Comment