Lesson Overview
A computer program works with information called data. Java programs store data in memory using variables.
In this lesson, you will learn how to create variables, store information inside variables, change their values, and display their contents.
Learning Objectives
By the end of this lesson, you should be able to:
- Explain what a variable is.
- Declare a Java variable.
- Assign a value to a variable.
- Initialize a variable.
- Use several Java data types.
- Change the value stored in a variable.
- Display variables using
System.out.println(). - Follow Java variable naming rules.
1. What Is a Variable?
A variable is a named location in the computer's memory that stores information.
Think of a variable as a labeled box. The label is the variable's name, and the information inside the box is the variable's value.
For example:
int age = 16;
This statement creates a variable named age and stores
the number 16 inside it.
2. Declaring a Variable
Before Java can use a variable, the variable must normally be declared.
The general format is:
dataType variableName;
Example:
int score;
This tells Java to create a variable named score
that can store an integer.
3. Assigning a Value
The = symbol is called the
assignment operator.
It places a value into a variable.
int score; score = 95;
The variable score now contains the value
95.
4. Initializing a Variable
When a variable is given its first value at the same time that it is created, the variable is being initialized.
int score = 95;
This single statement both declares and initializes the variable.
5. Common Java Data Types
| Data Type | Stores | Example |
|---|---|---|
int |
Whole numbers | int age = 16; |
double |
Decimal numbers | double price = 19.99; |
boolean |
true or false | boolean passed = true; |
char |
A single character | char grade = 'A'; |
String |
Words or text | String name = "Alex"; |
Important
A char uses single quotation marks.
char grade = 'A';
A String uses double quotation marks.
String name = "Alex";
6. Displaying Variables
Variables can be displayed using
System.out.println().
int age = 16; System.out.println(age);
Output:
16
Combining Text and Variables
Use the + operator to combine text with a variable.
int age = 16;
System.out.println("My age is " + age);
Output:
My age is 16
7. Variable Values Can Change
The word variable means the value can vary or change.
int score = 80; System.out.println(score); score = 95; System.out.println(score);
Output:
80 95
The variable is still named score, but its value changed
from 80 to 95.
8. Variables and Math
Variables can be used in mathematical expressions.
int num1 = 10; int num2 = 5; int total = num1 + num2; System.out.println(total);
Output:
15
Another Example
double price = 4.50;
int quantity = 3;
double total = price * quantity;
System.out.println("Total Cost: $" + total);
Output:
Total Cost: $13.5
9. Java Variable Naming Rules
A Java variable name:
- May contain letters.
- May contain numbers.
- May contain an underscore
_. - Cannot begin with a number.
- Cannot contain spaces.
- Cannot be a Java reserved word.
- Is case-sensitive.
| Variable Name | Valid? | Reason |
|---|---|---|
age |
Yes | Valid name |
studentAge |
Yes | Uses camelCase |
score2 |
Yes | Numbers may appear after the first character |
2score |
No | Cannot begin with a number |
student age |
No | Spaces are not allowed |
class |
No | class is a Java keyword |
10. camelCase
Java programmers normally use camelCase when naming variables.
Examples:
studentName studentAge testScore favoriteGame numberOfStudents totalPrice
The first word begins with a lowercase letter. Each additional word begins with a capital letter.
11. Complete Java Example
public class VariableExample
{
public static void main(String[] args)
{
String studentName = "Jordan";
int age = 16;
double gpa = 3.75;
char grade = 'A';
boolean passing = true;
System.out.println("Student Name: " + studentName);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
System.out.println("Grade: " + grade);
System.out.println("Passing: " + passing);
}
}
Programming Assignment
PX_lastname_Variable.java
Create a new Java program demonstrating your understanding of variables and data types.
Replace lastname with your own last name.
Example:
P2_Cusack_Variable.java
Your teacher may replace PX with your class period.
Program Requirements
Your program must create and display at least the following variables:
- A
Stringcontaining your first name. - A
Stringcontaining your last name. - An
intcontaining your age. - An
intcontaining your grade level. - A
doublecontaining a decimal number. - A
charcontaining one letter. - A
booleancontaining eithertrueorfalse.
Display every variable using
System.out.println().
Starter Program
public class PX_lastname_Variable
{
public static void main(String[] args)
{
// Create a String variable
String firstName = "YourName";
// Create another String variable
String lastName = "YourLastName";
// Create an integer variable
int age = 0;
// Create an integer for grade level
int gradeLevel = 0;
// Create a decimal variable
double favoriteNumber = 0.0;
// Create a character variable
char favoriteLetter = 'A';
// Create a boolean variable
boolean likesProgramming = true;
// Display the variables
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Age: " + age);
System.out.println("Grade Level: " + gradeLevel);
System.out.println("Favorite Number: " + favoriteNumber);
System.out.println("Favorite Letter: " + favoriteLetter);
System.out.println("Likes Programming: " + likesProgramming);
}
}
Example Program
public class P2_Cusack_Variable
{
public static void main(String[] args)
{
String firstName = "Joe";
String lastName = "Cusack";
int age = 17;
int gradeLevel = 11;
double favoriteNumber = 7.5;
char favoriteLetter = 'J';
boolean likesProgramming = true;
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Age: " + age);
System.out.println("Grade Level: " + gradeLevel);
System.out.println("Favorite Number: " + favoriteNumber);
System.out.println("Favorite Letter: " + favoriteLetter);
System.out.println("Likes Programming: " + likesProgramming);
}
}
Example Output
First Name: Joe Last Name: Cusack Age: 17 Grade Level: 11 Favorite Number: 7.5 Favorite Letter: J Likes Programming: true
Part 2 - Change a Variable
After displaying your information, change the value of at least one variable.
Example:
int score = 75;
System.out.println("Original Score: " + score);
score = 95;
System.out.println("New Score: " + score);
Output:
Original Score: 75 New Score: 95
Part 3 - Perform a Calculation
Create at least two numeric variables and use them in a calculation.
Example:
int test1 = 90;
int test2 = 80;
int totalPoints = test1 + test2;
System.out.println("Total Points: " + totalPoints);
Output:
Total Points: 170
Challenge
Create three test score variables.
double test1 = 85; double test2 = 92; double test3 = 88;
Calculate the average:
double average = (test1 + test2 + test3) / 3;
Display the result:
System.out.println("Average: " + average);
Common Mistakes
Mistake #1 - Forgetting quotation marks
Incorrect:
String name = Joe;
Correct:
String name = "Joe";
Mistake #2 - Using double quotes with char
Incorrect:
char grade = "A";
Correct:
char grade = 'A';
Mistake #3 - Putting a decimal into an int
Incorrect:
int price = 19.99;
Correct:
double price = 19.99;
Mistake #4 - Forgetting the semicolon
Incorrect:
int age = 16
Correct:
int age = 16;
Knowledge Check
- What is a variable?
- What Java data type stores whole numbers?
- What Java data type stores decimal numbers?
- What Java data type stores
trueorfalse? - What is the difference between
charandString? - What does the
=operator do? - What does it mean to initialize a variable?
- Can the value stored in a variable change?
Assignment Checklist
Before submitting your program, make sure:
- Your program compiles without errors.
- Your filename follows the required naming convention.
- Your class name matches your filename.
- You created at least one
String. - You created at least one
int. - You created at least one
double. - You created at least one
char. - You created at least one
boolean. - You displayed each variable.
- You changed the value of at least one variable.
- You performed at least one calculation.
- Your code is properly indented.
- Your code contains comments.
What You Learned
In this lesson you learned that variables allow Java programs to store and manipulate information.
You practiced:
- Declaring variables
- Initializing variables
- Assigning values
- Using
int - Using
double - Using
boolean - Using
char - Using
String - Changing variable values
- Performing calculations
- Displaying variables with
System.out.println()