Output using System.out.

From CompSciWiki
Revision as of 20:28, 20 March 2007 by Umhalle1 (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > More About Computer Science


Introduction

Java uses System.out. for program output. This section will show you how to use System.out.println and System.out.print to print to the screen.

   

{{{Body}}}

Printing text to the screen

To print text to the screen you can use:

System.out.println("text");

or

System.out.print("text");

Whatever you put inside of the quotes will be printed to the screen. The difference between System.out.println() and System.out.print() is that System.out.println() will print a newline after the text unlike System.out.print() which just prints the text.

Example 1

This program prints the message "Go Bisons!" to the screen.

public class Output1
{
  public static void main(String args[]) 
  {
    System.out.println("Go Bisons!");
  }
}

Example 2

This program prints the message "Go Bisons!" to the screen three times.

public class Output2
{
  public static void main(String args[]) 
  {
    System.out.println("Go Bisons!");
    System.out.println("Go Bisons!");
    System.out.println("Go Bisons!");
  }
}

Output

Go Bisons!
Go Bisons!
Go Bisons!

Example 3

Now, lets compare this program to the one in example 2. This program also prints the message "Go Bisons!" to the screen three times. However, it does not print a new line after each message.

public class Output3
{
  public static void main(String args[]) 
  {
    System.out.print("Go Bisons!");
    System.out.print("Go Bisons!");
    System.out.print("Go Bisons!");
  }
}

Output

Go Bisons!Go Bisons!Go Bisons!

Using Variables with System.out.println()

You can also print the contents of a variable by using System.out.println()

Example 1

public class PrintVariable
{
  public static void main(String args[]) 
  {
    int num;

    num = 5;

    System.out.println(num);
  }
}

Output

5

In this example we create an integer called num and use it to store the number 5. We then print the contents of num by using System.out.println(). Notice that we did not put quotes around num. Variables do not need to be put in quotes. Only a string of text needs to be put inside of quotes.

Example 2

In this example we will show you how to print a string of text and a variable.

public class PrintTemp
{
  public static void main(String args[]) 
  {
    int temp;

    temp = 25;

    System.out.println("The temperature is currently " + temp);
  }
}

Output

The temperature is currently 25

Example 3

We can also put the variable in the middle of a sentence.

public class PrintTemp
{
  public static void main(String args[]) 
  {
    int temp;

    temp = 25;

    System.out.println("The temperature is currently " + temp + " degrees Celsius.");
  }
}

Output

The temperature is currently 25 degrees Celsius.

We use a + sign to join a string of text and a variable.