Using println with variables

 

Using the output statement println with variables is straightforward.  To display the value of a variable, we just need to place the variable name between the parentheses, but not inside quotes (putting it in quotes will treat it as a string so its name will be displayed instead of its value).  As before, we can use the + operator to attach multiple items that we’d like to display.  Here’s a program that puts everything together:

 

               public class Farm

       {

          public static void main(String[] args)

          {

              int chickens = 10;

             System.out.println(“I had “ + chickens + “ chickens.”);

             System.out.println(“Some weeks later...”);

            

chickens = 20;

System.out.println(“The number grew to “ + chickens + “ chickens.”);

          }

       }    

 

Compile and run this program and you should obtain the following output:

 

       I had 10 chickens.

       Some weeks later...

       The number grew to 20 chickens.

 

Notice how in both println statements, when we put chickens in quotes, the word chickens was displayed, whereas without the quotes, the current value of the variable chickens was displayed.  When the first println executes the value of chickens is 10, but when the second executes, the variable has already changed to 20, so 20 will be displayed.