AP Computer Science - Types and Variables

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

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:

a) What type of variable to use. b) What name to give to the variable.

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.

What are the TYPES?

String is the type of variable to use to store a string of characters between .

(Note: String is the only type that starts with a capital letter.)

int is used to represent an integer (number).

double is used to represent a decimal.

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.

int luckyNumber; luckyNumber = 13;

//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;

(the value 13 is erased)

Sample Code: int luckyNumber; luckyNumber = 13; System.out.println(luckyNumber);

String studentName; studentName = Dino; System.out.println(studentName);

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);

You might also like