Thursday, 4 August 2011

Java: Output Statements

There are 2 ways to output a statement in Java, with only a slight difference between them.
Take the following example:


int i = 0;                             // This initializes the variable "i" to 0
while ( i < 6 ) {                  // While loop beginning, loops as long as i is less than 6 

        System.out.print(i);  // System.out.print() is the output command. Note that this doesn't
                                         // automatically end line, as we will see in the output.
         i += 1;                    // Make sure to have this line to affect the conditional variable.
                                       // Otherwise, the loop will never end. "i += 1" is the same as
                                       // i = i + 1, just incrementing the variable by 1
 }                                     // End loop.

The above code returns the output: 012345
Having no separator between each printed number, whitespace of any kind (Space, tab or newline) makes it look like this. Luckily, there's another way to print things that automatically places an end of line character at the end of each passed string;


int i = 0;
while ( i < 6 ) { 

    System.out.println(i);
    i += 1;
}

The output of the above is:

0
1
2
3
4
5


But what if we want a new line in the middle of a string? The newline character is "\n", a tab is "\t" and a space is simply a space. If you wanted to separate the above output by spaces instead of newlines, you would have to concatenate the strings.

System.out.print( i + " " );

Simple!

1 comment: