Skip to main content
Engineering LibreTexts

10.2: Assignment

  • Page ID
    15215
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Now that we have declared variables, we want to use them to store values. We do that with an assignment statement.

    message = "Hello!";  // give message the value "Hello!"
    hour = 11;           // assign the value 11 to hour
    minute = 59;         // set minute to 59
    

    When you declare a variable, you create a named storage location. This example shows three assignments, and the comments illustrate different ways people sometimes talk about assignment statements. The vocabulary can be confusing here, but the idea is straightforward:

    • When you declare a variable, you create a named storage location.
    • When you make an assignment to a variable, you update its value.

    As a general rule, a variable has to have the same type as the value you assign to it. For example, you cannot store a string in minute or an integer in message. We will see some examples that seem to break this rule, but we’ll get to that later.

    A common source of confusion is that some strings look like integers, but they are not. For example, message can contain the string "123", which is made up of the characters '1', '2', and '3'. But that is not the same thing as the integer 123.

    message = "123";     // legal
    message = 123;       // not legal
    

    Variables must be initialized (assigned for the first time) before they can be used. You can declare a variable and then assign a value later, as in the previous example. You can also declare and initialize on the same line:

    String message = "Hello!";
    int hour = 11;
    int minute = 59;
    

    This page titled 10.2: Assignment is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?