Java: define terms initialization, declaration and assignment

后端 未结 7 709
轻奢々
轻奢々 2020-11-22 16:12

I find the defs circular, the subjects are defined by their verbs but the verbs are undefined! So how do you define them?

The Circular Definitions

7条回答
  •  旧巷少年郎
    2020-11-22 16:51

    I come from a C/C++ background, but the ideas should be the same.

    Declaration - When a variable is declared, it is telling the compiler to set aside a piece of memory and associate a name (and a variable type) with it. In C/C++ it could look like this:

    int x;
    

    The compiler sees this and sets aside an address location for x and knows what methods it should use to perform operations on x (different variable types will use different access operations). This way, when the compiler runs into the line

    x = 3 + 5;
    

    It knows to put the integer value 8 (not the floating point value 8) into the memory location also known as 'x'.

    Assignment - This is when you stuff a value into the previously declared variable. Assignment is associated with the 'equals sign'. In the previous example, the variable 'x' was assigned the value 8.

    Initialization - This is when a variable is preset with a value. There is no guarantee that a variable will every be set to some default value during variable declaration (unless you explicitly make it so). It can be argued that initialization is the first assignment of a variable, but this isn't entirely true, as I will explain shortly. A typical initialization is a blend of the variable declaration with an assignment as follows:

    int x = 6;
    

    The distinction between initialization and assignment becomes more important when dealing with constants, such as this...

    const int c = 15;
    

    When dealing with constants, you only get to assign their value at the time of declaration/initialization. Otherwise, they can't be touched. This is because constants are often located in program memory vs data memory, and their actual assignment is occurring at compile time vs run time.

提交回复
热议问题