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.
- 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.
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
- Change the program: adding more variables, change numbers and formulas and run it again.
- Read more about Java variables here
Last modified 5 years ago
Last modified on Aug 3, 2020, 5:06:51 PM
Attachments (1)
- JavaVariables.jpg (83.6 KB) - added by 6 years ago.
Download all attachments as: .zip