1.4 Assignment Statements and Input

16 阅读1分钟

1. Exam Points

  • Assign a value to a variable based on its data type.
    • int x = 10;
    • double y = 2.3;
    • boolean z = true;
    • String name = "Annabelle";
  • You’d better write clearly the value based on its type to avoid mistakes.
    • Ex. double a = 10/4; (a = 2.0)
    • Ex. int b = 10 / 2; (b = 5)

2. Knowledge Points

(1) Assignment Operator

  • The assignment operator = is used to initialize or change the value stored in a variable.
    • int x = 10;
    • double y = 2.3;
    • String name = "Annabelle";
    • boolean isEven = false;
  • Assign a proper value to each variable based on its data type.
  • Note:
    • A variable must be assigned a value before being used.
    • Reference types can be assigned a new object or null if there is no object.
      • Dog d1 = new Dog(); // d1 refers to a newly created object
      • Dog d2 = null; // d2 refers to null, not refering to any object
    • null can not be assigned to a primitive data type variable.
  • final variables: final variables can not be changed once initialized.
  • The final keyword is used to declare a constant(常量) that can not be changed.
    int x = 10;
    // x is a variable, so its value can be changed
    x = 20; 
    
    // Y is a constant, its value can not be changed
    final int Y = 20; 
    
    // we normally use all uppercase to name a constant
    final int ERROR_CODE = 404; 
    

(2) Input

  • 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.
  • Since any specific form of input from the user is outside the scope of the AP CSA exam, so we will not talk about it in details.

3. Exercises