Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Assignment Statements and Input

Lesson ~10 min read 8 MCQs

In simple terms: 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.

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.

The salad bowl as a variable: contents change with assignments.

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
This flowchart diagram illustrates the process of executing an assignment statement, `x = 5 + 10`. It flows from left to right, showing that the expression `5 + 10` is first evaluated to a single value, `15`, which is then stored in the variable `x`.

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

Assignment (`=`) vs. Equality (`==`) in Java.

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.

Tracing an assignment statement with an expression.

Consider this:

int newScore = score + 5 * 2;
  1. The computer looks at the right side: score + 5 * 2.
  2. It knows score is 100. So, it's 100 + 5 * 2.
  3. It follows the order of operations (PEMDAS): 100 + 10.
  4. It evaluates this to a single value: 110.
  5. Now, it takes that 110 and stores it in the newScore variable.

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:

  1. 1
    Import it
    At the very top of your file, you need to tell Java where to find the Scanner tool. import java.util.Scanner;
  2. 2
    Create it
    Inside your main method, you need to create a Scanner object 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 a String.
  • nextInt(): Reads the next whole number as an int.
  • nextDouble(): Reads the next decimal number as a double.

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

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a couple of examples to make these concepts solid.

    Example 1

    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:

    1. 1
      Initial State
      Let's set up our variables.
      int a = 10;
      int b = 20;

      Think of two boxes. Box a has 10 in it. Box b has 20 in it.

    2. 2
      The Wrong Move
      A common first thought is to do this:
      a = b; // a becomes 20
      b = a; // b becomes... 20
    Common mistake: Attempting to swap variables without a temporary holder.
    1. 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.

    Example 2

    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. 1

      Set up the Scanner: We need input, so we need a Scanner. Don't forget the import!

      import java.util.Scanner;
      
      public class SalesTaxCalculator {
          public static void main(String[] args) {
              Scanner input = new Scanner(System.in);
    2. 2
      Get Input from the User
      We need to prompt the user for the price and store it. Since price can have cents, double is the right type.
      System.out.print("Enter the price of the item: $");
      double price = input.nextDouble();

      Here, the program pauses. The user types 50.00 and hits Enter. The nextDouble() method reads that, and the value 50.0 is assigned to the price variable.

    3. 3
      Get the Second Input
      Now, 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 to taxRate.

    4. 4
      Perform the Calculation
      Now 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 in 0.0625. This is stored in taxDecimal.
      • Next, price * taxDecimal (50.0 * 0.0625) is calculated, resulting in 3.125. This is stored in taxAmount.
      • Finally, price + taxAmount (50.0 + 3.125) is calculated, resulting in 53.125. This is stored in totalCost.
    5. 5
      Display 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.

    Tracing the correct variable swap using a temporary variable.

    Try it yourself

    Ready to try it yourself?

    1. 1
      Temperature Converter
      Write 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 / 9 and print the result.
      • Hint: Be careful with integer division! To get an accurate decimal result, you might want to use 5.0 / 9.0 in your formula and store the result in a double.
    2. 2
      Simple Mad Libs
      Create 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 Scanner and use the nextLine() method three times to get the user's words.
    Avoiding integer division pitfalls for accurate calculations.