Assignment Statements and Input
Why this matters
Imagine you're at a build-your-own-salad bar in downtown Dallas. You grab a bowl. First, you tell the server your name for the order—let's say it's "Priya." They write "Priya" on the lid. Then, you choose your base: spinach. They put spinach in the bowl. You add some toppings: chicken, tomatoes, and feta. Each choice updates the contents of your bowl.
In programming, your variables are like that bowl and its label. You need a way to put things in the bowl (like spinach), change what's inside (add chicken), and know whose bowl it is (the name "Priya"). You also need a way for the program to ask you what you want in the first place.
Today, we'll explore how to give our programs these fundamental abilities: storing values with assignment statements and getting information from the user with input.
Concept overview
flowchart LR
subgraph Assignment Statement: x = 5 + 10
A[Start] --> B{Evaluate expression on the right};
B --> C[5 + 10];
C --> D{Result is 15};
D --> E[Store the single value '15' in the variable 'x' on the left];
E --> F[End];
end
Core explanation
Hello! I'm Saavi, and I'm so glad you're here. Let's dive into how we make our programs remember and interact with things.
The Assignment Operator: Your Program's Memory
Think of a variable as a labeled box. When you declare a variable, like int score;, you're creating an empty box with the label "score" on it, and you're telling the computer that only integers can go inside.
But an empty box isn't very useful. We need to put something in it. This is called assignment.
The assignment operator in Java is the single equals sign (=). It tells the computer: "Take the value on the right and store it in the variable on the left."
int score; // Declares an integer variable named 'score' (an empty box)
score = 100; // Assigns the value 100 to 'score' (puts 100 in the box)
The first time a variable is given a value, we call that initialization. You can declare and initialize in one step, which is very common:
int score = 100; // Declares AND initializes the variable 'score'
The Golden Rule: Right-to-Left
Always evaluate the right side of the = first. The computer calculates everything on the right until it becomes a single value. Then, and only then, does it store that single value in the variable on the left.
Consider this:
int newScore = score + 5 * 2;
- The computer looks at the right side:
score + 5 * 2. - It knows
scoreis 100. So, it's100 + 5 * 2. - It follows the order of operations (PEMDAS):
100 + 10. - It evaluates this to a single value:
110. - Now, it takes that
110and stores it in thenewScorevariable.
The value of the variable on the left is always overwritten. If score was 90 before, after score = 100;, the 90 is gone forever, replaced by 100.
Type Compatibility is Key
Your labeled box has rules. You can't put a basketball in a shoebox. Similarly, you must assign a value of a compatible data type.
int userAge = 21; // Good! 21 is an int.
double price = 19.99; // Good! 19.99 is a double.
// int tax = 8.25; // BAD! This will cause an error. 8.25 is a double, not an int.
For object references, you can assign a new object or a special value called null. null is a keyword that means "this reference doesn't point to any object." It's like having a label for a box, but the box itself doesn't exist yet.
String name = "Marcus"; // 'name' refers to a String object with the value "Marcus"
name = null; // Now, 'name' refers to nothing at all.
Getting User Input with the Scanner Class
So far, all our data has been hard-coded by us, the programmers. But what if we want to write a program that calculates the tip for a bill at a restaurant in Seattle? The bill amount changes every time! We need to get that information from the user.
This is where the Scanner class comes in. Think of it as a tool that listens for input from the keyboard.
To use it, you need to do two things:
- 1Import itAt the very top of your file, you need to tell Java where to find the
Scannertool.import java.util.Scanner; - 2Create itInside your
mainmethod, you need to create aScannerobject and connect it to the standard system input (the keyboard).
import java.util.Scanner; // Step 1: Import
public class Greeter {
public static void main(String[] args) {
// Step 2: Create a Scanner object
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello! What's your name?");
// Use the Scanner to read the user's next line of text
String userName = keyboard.nextLine();
System.out.println("Nice to meet you, " + userName + "!");
System.out.println("How old are you?");
// Use the Scanner to read the user's next integer
int userAge = keyboard.nextInt();
System.out.println("You'll be " + (userAge + 10) + " in a decade!");
keyboard.close(); // Good practice to close the scanner when you're done.
}
}
The Scanner class has different methods to read different types of data:
nextLine(): Reads a whole line of text as aString.nextInt(): Reads the next whole number as anint.nextDouble(): Reads the next decimal number as adouble.
By combining user input with assignment statements, you can create dynamic programs that respond to user needs. You ask for information, store it in variables, and then use those variables to calculate, decide, and produce new results. This is the foundation of interactive software.
See it in action
Worked examples
Let's walk through a couple of examples to make these concepts solid.
Swapping Variable Values
Problem: You have two variables, a and b. You need to write code that swaps their values. For example, if a starts as 10 and b starts as 20, your code should make a become 20 and b become 10.
Step-by-Step Solution:
- 1Initial StateLet's set up our variables.
int a = 10; int b = 20;Think of two boxes. Box
ahas10in it. Boxbhas20in it. - 2The Wrong MoveA common first thought is to do this:
a = b; // a becomes 20 b = a; // b becomes... 20
-
The Correct Approach: To avoid losing a value, we need a third, temporary box to hold one of the values while we make the swap. Let's call it
temp.int a = 10; int b = 20; int temp; // Our extra, empty box // Step 1: Store the value of 'a' in 'temp' so we don't lose it. temp = a; // Now: temp is 10, a is 10, b is 20 // Step 2: Overwrite 'a' with the value from 'b'. a = b; // Now: temp is 10, a is 20, b is 20 // Step 3: Put the stored original value from 'temp' into 'b'. b = temp; // Now: temp is 10, a is 20, b is 10. Success! System.out.println("a is now: " + a); // Prints "a is now: 20" System.out.println("b is now: " + b); // Prints "b is now: 10"This pattern is a classic and perfectly illustrates how assignment overwrites data and how you must plan your steps carefully.
Calculating Sales Tax
Problem: Write a program that asks a user for the price of an item and the sales tax rate for their city (like Boston, which is 6.25%). Then, calculate and display the total cost.
Step-by-Step Solution:
- 1
Set up the
Scanner: We need input, so we need aScanner. Don't forget the import!import java.util.Scanner; public class SalesTaxCalculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); - 2Get Input from the UserWe need to prompt the user for the price and store it. Since price can have cents,
doubleis the right type.System.out.print("Enter the price of the item: $"); double price = input.nextDouble();Here, the program pauses. The user types
50.00and hits Enter. ThenextDouble()method reads that, and the value50.0is assigned to thepricevariable. - 3Get the Second InputNow, let's get the tax rate.
System.out.print("Enter the sales tax rate (e.g., 6.25): "); double taxRate = input.nextDouble();The user types
6.25. That value is assigned totaxRate. - 4Perform the CalculationNow we use our variables in an expression. Remember, the right side is evaluated first.
// Convert percentage to a decimal for calculation double taxDecimal = taxRate / 100.0; double taxAmount = price * taxDecimal; double totalCost = price + taxAmount;- First,
taxRate / 100.0(e.g.,6.25 / 100.0) is calculated, resulting in0.0625. This is stored intaxDecimal. - Next,
price * taxDecimal(50.0 * 0.0625) is calculated, resulting in3.125. This is stored intaxAmount. - Finally,
price + taxAmount(50.0 + 3.125) is calculated, resulting in53.125. This is stored intotalCost.
- First,
- 5Display the Result
System.out.println("Total cost: $" + totalCost); // This will print "Total cost: $53.125" input.close(); // Clean up } }This example combines getting input (
Scanner) with using expressions in assignment statements to produce a useful result.
Try it yourself
Ready to try it yourself?
- 1Temperature ConverterWrite a program that asks the user for a temperature in Fahrenheit (as an integer). Convert this temperature to Celsius using the formula
C = (F - 32) * 5 / 9and print the result.- Hint: Be careful with integer division! To get an accurate decimal result, you might want to use
5.0 / 9.0in your formula and store the result in adouble.
- Hint: Be careful with integer division! To get an accurate decimal result, you might want to use
- 2Simple Mad LibsCreate a program that asks the user for a name (String), an adjective (String), and a verb (String). Store these in three different variables. Then, use them to print a silly sentence like, "[Name] [verb]s to the [adjective] store."
- Hint: You'll need to create a
Scannerand use thenextLine()method three times to get the user's words.
- Hint: You'll need to create a
Practice — 8 questions
In simple terms, assignment statements are about storing and updating information in your program's memory, while input is how your program gets that information from a user.
int score; // Declares an integer variable named 'score' (an empty box)
score = 100; // Assigns the value 100 to 'score' (puts 100 in the box)
- 1.4.A: Develop code for assignment statements with expressions and determine the value that is stored in the variable as a result of these statements.
- 1.4.B: Develop code to read input.
- 1.4.A.1
- Every variable must be assigned a value before it can be used in an expression. That value must be from a compatible data type. A variable is initialized the first time it is assigned a value. Reference types can be assigned a new object or null if there is no object. The literal null is a special value used to indicate that a reference is not associated with any object.
- 1.4.A.2
- The assignment operator = allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.
- 1.4.A.3
- During execution, an expression is evaluated to produce a single value. The value of an expression has a type based on the evaluation of the expression.
- 1.4.B.1
- Input can come in a variety of forms, such as tactile, audio, visual, or text. The Scanner class is one way to obtain text input from the keyboard.
flowchart LR
subgraph Assignment Statement: x = 5 + 10
A[Start] --> B{Evaluate expression on the right};
B --> C[5 + 10];
C --> D{Result is 15};
D --> E[Store the single value '15' in the variable 'x' on the left];
E --> F[End];
end
Read what Saavi narrates
Hello! I'm Saavi. I'm so glad you're here.
Think about ordering a custom salad. You tell the server your name, your base, and your toppings. Each choice you make updates what's in your bowl. In programming, we do the same thing. We need to store information, like your name on the order, and we need a way for the program to ask you what you want in the first place.
Today, we're learning two key actions. First, how to store information in a variable using an assignment statement. And second, how to make our programs interactive by reading input from the user.
Let's look at a classic problem. Imagine you have two variables, 'a' and 'b'. 'a' holds the number 10, and 'b' holds 20. How do you swap their values?
Your first instinct might be to say 'a' gets 'b', and 'b' gets 'a'. But if you do that, you'll run into a problem. When you set 'a' to the value of 'b', the original value of 10 in 'a' is gone forever. It's overwritten. Now both variables hold 20.
The solution is to use a third, temporary variable. Think of it as an extra empty cup. First, you pour the contents of 'a' into the temporary cup. Now 'a' is free. You can pour the contents of 'b' into 'a'. Finally, you take the value you saved in your temporary cup and pour it into 'b'. And just like that, you've swapped them! This shows how assignment is an action that overwrites data.
A very common mistake here is confusing the single equals sign, which is for assignment, with the double equals sign, which is for comparison. A single equals sign is an action... it says "put this value here". A double equals sign is a question... it asks "are these two values the same?". We'll use the double equals sign later, but for now, just remember that the single equals sign is your tool for storing and updating values.
You're building the fundamental skills of a programmer. Keep practicing, stay curious, and you'll be building amazing things before you know it.
`x = 5;` is an action that *puts* 5 into `x`. `x == 5;` is a question that *asks* if `x` is currently equal to 5 (it evaluates to `true` or `false`). Using `=` in a condition is a common bug.
Use `=` only when you want to store a value. Use `==` when you want to compare two values (which we'll cover more in Unit 3).
`100 = score;` will cause a compiler error. The left side of an assignment *must* be a variable (a storage location). The right side is the value to be stored.
Always remember the flow: `variable = value;`. The destination is on the left.
`int height; int newHeight = height + 10;` will fail. The computer doesn't know what's in the `height` "box" yet, so it can't do math with an unknown value.
Ensure every variable has a value assigned to it before you try to read from it in an expression. `int height = 70; int newHeight = height + 10;`
In Java, when you divide two integers, the result is also an integer; any remainder is thrown away. `int result = 5 / 2;` will store `2` in `result`, not `2.5`.
If you need a decimal result, make sure at least one of the numbers in the division is a `double`. `double result = 5.0 / 2;` or `double result = (double) 5 / 2;`.
After you call `nextInt()`, the "Enter" keypress (a newline character) is left behind in the input stream. If your next call is `nextLine()`, it immediately reads that leftover newline and gives you an empty string, seemingly "skipping" your prompt.
A simple fix is to place an extra `keyboard.nextLine();` after your `nextInt()` call to consume the leftover newline character before you try to read the next line of text.
`int age = "25";` is a type mismatch. `"25"` is a `String` (text), not an `int` (number). The compiler will stop you.
Pay close attention to your variable types. If you need to convert a `String` to an `int`, you must use a method like `Integer.parseInt("25")`.