3.2.3 Variable Declaration and Initialization
Appearance
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:
- Declare the box (give it a name and say what kind of stuff will go in it).
- 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 namedscore
starts at 0)double pi = 3.14;
(A decimal number variable namedpi
starts at 3.14)boolean game_over = false;
(A true/false variable namedgame_over
starts as false)char first_initial = 'J';
(A character variable namedfirst_initial
starts as 'J')
- For Reference Data Types (like Strings and Objects):
String greeting = "Hello!";
(A text variable namedgreeting
stores "Hello!")Car myCar = new Car();
(An object variable namedmyCar
now points to a brand newCar
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 callednull
.null
means "no object is being pointed to right now." If you try to use anull
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:
- GeeksforGeeks - Variables in Java: https://www.geeksforgeeks.org/variables-in-java/
- W3Schools - JavaScript Variables: https://www.w3schools.com/js/js_variables.asp (Good for general concept, even if JavaScript specific)
- Wikipedia - Variable (computer science): https://en.wikipedia.org/wiki/Variable_(computer_science)