| 1 | 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. Variables can hold things like: |
| 2 | * An integer number (e.g. 42) |
| 3 | * A real number (e.g. 3.141592) |
| 4 | * A character (e.g. 'a' or '0' or '!') |
| 5 | * A string of characters (e.g. "Howdy") |
| 6 | * Something you define |
| 7 | |
| 8 | Variables are an important part of every program because they allow the program to do different things depending on what's in the box. |
| 9 | |
| 10 | 1. Close your current project if you have one open (File->Close Folder) |
| 11 | 2. Make a new folder in your Java Projects folder named !VariablesExample |
| 12 | 3. Open the folder (File->Open Folder) |
| 13 | 4. Create a new file: (File->New) |
| 14 | 5. Cut and paste the program below into the editor window: |
| 15 | {{{ |
| 16 | public class VariablesExample { |
| 17 | public static void main(String args[]) { |
| 18 | int a; // create a variable that can hold an integer number |
| 19 | int b; // create another integer variable named b |
| 20 | int c; |
| 21 | |
| 22 | a = 3; |
| 23 | b = 4; |
| 24 | c = a * b; |
| 25 | System.out.println(c); |
| 26 | } |
| 27 | } |
| 28 | }}} |
| 29 | 6. Save the file as !VariablesExample.java (File->Save) |
| 30 | 7. Run the program |
| 31 | 8. In the output terminal window, observe that the number 12 is output. |
| 32 | |
| 33 | === Extra Credit === |
| 34 | Change the program, adding more variables, changing numbers and formulas and run it again. |