AP Computer Science - Types and Variables
AP Computer Science - Types and Variables
AP Computer Science - Types and Variables
Variable Definition
A variable stores a VALUE. Every value has a TYPE. Java creates a storage location in the computers memory to store the value. Therefore, when you want to use a variable for some value that you want to use again, you must decide:
NOTE: You CANNOT store a value in a variable with a different type. For example: You cannot store a number in a String variable, or a string ( ) in an integer variable.
(Note: String is the only type that starts with a capital letter.)
What should By convention, variable names should start with a lowercase letter. I name my variables? NOTE: In Java, all words are case sensitive and cannot begin with a digit. Spaces are not permitted, but an underscore (_) is permitted. There are many reserved words (e.g., public, static) that cannot be used for variable names. Often an uppercase letter is used in the middle of a variable name, e.g., luckyNumber, to make the name easier to read. Class names always begin with an uppercase letter, e.g., HelloPrinter. Assigning a value to a variable. See Syntax 2.2
The equal sign (=) is called the ASSIGNMENT OPERATOR. It does NOT mean the same thing as the = sign in mathematics.
//Creates a variable named luckyNumber as an int type // Assigns the integer 13 to the variable
These two statements can be combined into the following single statement: int luckyNumber = 13; // declares luckyNumber as a variable name with type int
The value stored in the storage location called luckyNumber can be re-assigned with the following statement:
luckyNumber = 12;
Typical Errors: The compiler will give an error if a variable is used without being assigned a type. luckyNumber = 12; System.out.println(luckyNumber); The compiler will also give an error if the variable is uninitialized. int luckNumber; System.out.println(luckyNumber);