Version 3 (modified by 6 years ago) (diff) | ,
---|
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:
- An integer number (e.g. 42)
- A real number (e.g. 3.141592)
- A character (e.g. 'a' or '0' or '!')
- A string of characters (e.g. "Howdy")
- Something you define
Variables are an important part of every program because they allow the program to do different things depending on what's in the box.
- Close your current project if you have one open (File->Close Folder)
- Make a new folder in your Java Projects folder named VariablesExample
- Open the folder (File->Open Folder)
- Create a new file: (File->New File)
- 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); } }
- Save the file as VariablesExample.java (File->Save)
- Run the program
- In the output terminal window, observe that the number 12 is output.
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
Change the program, adding more variables, changing numbers and formulas and run it again.
Attachments (1)
- JavaVariables.jpg (83.6 KB) - added by 6 years ago.
Download all attachments as: .zip