wiki:ControlSystems/SoftwareTeam/Training/GettingStarted/Variables

Let's try a slightly more complex program that will introduce variables. A variable is like a box that can hold something for you. In Java, you can put only one type of thing in a given box. Different types of variables can hold different things like:

  • int can hold an integer number (e.g. 42)
  • double can hold a real number (e.g. 3.141592)
  • char can hold a character (e.g. 'a' or '0' or '!')
  • String can hold a string of characters (e.g. "Howdy")
  • boolean can hold values with two states: true or false

Variables are an important part of every program because they allow the program to do different things depending on what's in the box.

  1. Close your current project if you have one open (File->Close Folder)
  2. Make a new folder in your Java Projects folder named VariablesExample
  3. Open the folder (File->Open Folder)
  4. Create a new file: (File->New File)
  5. Cut and paste the program below into the editor window:
    public class VariablesExample {
        public static void main(String args[]) {
            int a;  // create a variable that can hold an integer number
            int b;  // create another integer variable named b
            int c;
    
            a = 3;
            b = 4;
            c = a * b;
            System.out.println(c);
        }
    }
    
  6. Save the file as VariablesExample.java (File->Save)
  7. Run the program
  8. In the output terminal window, observe that the number 12 is output.

Understanding the program

Our example program:

  • Creates 3 variables (boxes) named a, b, c. They are all integer variables (they can only hold integer numbers).
  • The program then places the number 3 in variable a, the number 4 in variable b, and the product of whatever is in a and b into variable c.
  • Finally, the program prints whatever value is in variable c.

Extra Credit

  1. Change the program: adding more variables, change numbers and formulas and run it again.
  2. Read more about Java variables here
Last modified 5 years ago Last modified on Aug 3, 2020, 5:06:51 PM

Attachments (1)

Download all attachments as: .zip