Jump to content

3.2.3 Variable Declaration and Initialization

From Computer Science Knowledge Base

3.2.3 Variable Declaration and Initialization

Imagine you're setting up those labeled boxes for your information. Before you can put anything into a box, you first need to:

  1. Declare the box (give it a name and say what kind of stuff will go in it).
  2. Initialize the box (put a starting piece of information in it).

Variable Declaration

  • This is where you tell the computer: "Hey, I'm going to need a storage spot, and here's what I'm going to call it, and what kind of data it will hold."
  • You typically specify the data type first, then the variable name. Example (in plain English):
    • Number called age
    • Text called username
    • True/False called is_active

Variable Initialization

  • This is where you give the variable its very first value. It's like putting the first item into your labeled box.
  • You do this using the assignment operator, which is usually an equals sign (=). Example (in plain English):
    • age = 12
    • username = "CoderKid"
    • is_active = true

Putting it Together (Declaration and Initialization):

You can declare a variable and initialize it on the same line, which is very common:

  • For Primitive Data Types:
    • int score = 0; (A whole number variable named score starts at 0)
    • double pi = 3.14; (A decimal number variable named pi starts at 3.14)
    • boolean game_over = false; (A true/false variable named game_over starts as false)
    • char first_initial = 'J'; (A character variable named first_initial starts as 'J')
  • For Reference Data Types (like Strings and Objects):
    • String greeting = "Hello!"; (A text variable named greeting stores "Hello!")
    • Car myCar = new Car(); (An object variable named myCar now points to a brand new Car object) Important Note for Reference Types: When you declare a reference variable but don't initialize it (e.g., String message;), it usually starts with a special value called null. null means "no object is being pointed to right now." If you try to use a null variable to do something, your program will likely crash!

Understanding how to declare and initialize variables is the first step to making your programs store and work with information effectively.

Bibliography: