Getting Started
All useful computer programs need to process information, such as a user's score in a game, the price of an item, or whether a task is complete. To manage this information, programs must have a way to store it in memory. In Java, we use variables as the fundamental building blocks for holding, accessing, and manipulating data.
What You Should Be Able to Do
Declare a variable of a given data type (
int,double,boolean).Initialize a variable by assigning it a value using the assignment operator.
Choose the most appropriate primitive data type for a specific piece of information.
Identify and correct common errors in variable declaration and assignment statements.
Use the
finalkeyword to create a named constant whose value cannot be changed.
Key Concepts & Java Implementation
The Core Idea
A variable is a named location in a computer's memory that stores a value. Think of it as a labeled box where you can place a single piece of information. To create a variable, you must perform a declaration, which involves specifying two things: its data type and its name.
A data type is a classification that tells Java what kind of data the variable can hold. This is crucial because the type determines how much memory to reserve and what operations are allowed. For now, we will focus on three of Java's fundamental primitive types:
int: Used for storing integers (whole numbers), like-5,0, or42.double: Used for storing floating-point numbers (numbers with decimal points), like-3.14,0.5, or99.99.boolean: A special type that can only hold one of two values:trueorfalse. It is often used to represent a condition or state.
Once a variable is declared, you can give it a value using the assignment operator (=). The act of giving a variable its first value is called initialization.
Syntax & Implementation
The syntax for working with variables is straightforward. A variable must be declared with its type before it can be used.
Syntax Table: Variable Declaration & Assignment
| Component | Purpose | Java Example |
|---|---|---|
Data Type | Specifies the kind of data a variable can hold. | int, double, boolean |
Variable Name | The identifier used to access the variable's value. | score |
Assignment (=) | Assigns the value on the right to the variable on the left. | = |
Semicolon (;) | Marks the end of a Java statement. | ; |
Annotated Java Examples
Declaration and Assignment
You can declare a variable and assign it a value in two separate steps or combine them into a single initialization statement.
// Example 1: Separate declaration and assignment int gameScore; // Declares an integer variable named gameScore. gameScore = 100; // Assigns the value 100 to gameScore. // Example 2: Declaration and initialization in one line double price = 24.99; // Declares a double named price and initializes it to 24.99.Using Different Data Types
The value you assign must be compatible with the variable's declared type.
// An integer for counting items int numberOfStudents = 28; // A double for precise measurements like GPA double gradePointAverage = 3.7; // A boolean to represent a state (e.g., is the light on?) boolean isEnrolled = true;Creating Constants with
finalIf you have a value that should never change during program execution (like the value of Pi), you can declare it as a constant using the
finalkeyword. By convention, constant names are written in all-uppercase letters.final int MAX_LIVES = 3; // Declares a constant for maximum lives. // The following line would cause a compile-time error because a final // variable's value cannot be changed after initialization. // MAX_LIVES = 4; // ERROR!
Tracing & Analysis
Execution Trace
It's important to understand that a variable holds only its most recent value. Let's trace the value of the
countvariable through a sequence of operations.Java Code Value of countExplanation int count = 5;5 countis initialized to 5.count = 10;10 The value 5 is replaced with 10. count = count + 1;11 The expression count + 1(10 + 1) is evaluated, and the result (11) is assigned back tocount.Analysis: Type Compatibility
Java is a "statically-typed" language, which means it strictly enforces data types. You can only assign a value to a variable if the value's type is compatible with the variable's declared type. For example, assigning a
doublevalue to anintvariable is not allowed because it could result in a loss of precision (the decimal part would be truncated).int wholeNumber; double decimalNumber = 75.8; // This is a valid assignment. An int can fit inside a double. decimalNumber = 100; // decimalNumber is now 100.0 // This causes a compile-time error: "incompatible types". // You cannot store a double in an int variable without a special operation. // wholeNumber = decimalNumber; // ERROR!
Java Syntax Quick-Reference
int: A primitive data type for storing 32-bit signed whole numbers (e.g.,-100,0,45).double: A primitive data type for storing 64-bit floating-point (decimal) numbers (e.g.,-0.25,3.14159).boolean: A primitive data type that holds one of two literal values:trueorfalse.=: The assignment operator. It evaluates the expression on its right and stores the result in the variable on its left.final: A keyword used to declare a variable as a constant, preventing its value from being changed after initialization.
Core Code Examples & Terminology
Variable: A named location in computer memory used to store a value that can be referenced and manipulated by a program.
Data Type: A classification that specifies the type of value a variable can hold (e.g.,
int,double) and the operations that can be performed on it.Primitive Type: A fundamental data type that is not an object, built directly into the Java language. Examples include
int,double, andboolean.Declaration: The act of creating a new variable by specifying its data type and name. A declaration reserves memory for the variable.
Initialization: The act of assigning an initial value to a variable, often done at the same time as its declaration.
Core Snippet 1: Integer Declaration & Assignment
int playerScore; // Declaration playerScore = 1500; // AssignmentThis code first declares an integer variable
playerScoreand then assigns it the value 1500 in a separate statement.Core Snippet 2: Double Initialization
double accountBalance = 199.95;This code declares a
doublevariableaccountBalanceand initializes it with a decimal value in a single statement.Core Snippet 3: Boolean Flag
boolean isGameOver = false;This code initializes a
booleanvariableisGameOvertofalse, which can be used to control program logic.Core Snippet 4: Final Constant
final int MAX_ATTEMPTS = 3;This code creates a constant named
MAX_ATTEMPTSwhose value (3) cannot be changed after this initialization.
Core Skill Check
Code Tracing: What is the final value of
xafter this Java code runs:int x = 10; x = x - 3; x = x * 2;?Debugging: Identify the compile-time error in this Java code:
double price = 9.99; int cost = price;.Application: Write a single line of Java code that declares a constant variable named
PIof typedoubleand initializes it to3.14159.
Common Misconceptions & Errors
Type Mismatch Errors: Trying to store a value of an incompatible type in a variable, such as
int num = 10.5;. This will cause a compile-time error because anintcannot hold a decimal value.Using a Variable Before Initialization: A local variable must be assigned a value before you can use it in a calculation or print it. The Java compiler will flag this as an error.
Confusing
=and==: The single equals sign (=) is the assignment operator used to store a value. The double equals sign (==) is a comparison operator used to check if two values are equal (covered in a later topic).Forgetting the Semicolon: Every Java statement, including variable declarations and assignments, must end with a semicolon (
;). Forgetting it is a common syntax error.
Summary
Variables are the foundation of data storage in Java. Every variable must be declared with a specific data type, which determines the kind of information it can hold. The three essential primitive types are int for whole numbers, double for decimal numbers, and boolean for true/false values. Variables are given values using the assignment operator (=), and this must be done before they are used. By using the final keyword, we can create constants whose values are fixed, making our code safer and more readable. Mastering variables is the first critical step toward writing any meaningful Java program.