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 ageText called usernameTrue/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 = 12username = "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 namedscorestarts at 0)double pi = 3.14;(A decimal number variable namedpistarts at 3.14)boolean game_over = false;(A true/false variable namedgame_overstarts as false)char first_initial = 'J';(A character variable namedfirst_initialstarts as 'J')
- For Reference Data Types (like Strings and Objects):
String greeting = "Hello!";(A text variable namedgreetingstores "Hello!")Car myCar = new Car();(An object variable namedmyCarnow points to a brand newCarobject) 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.nullmeans "no object is being pointed to right now." If you try to use anullvariable 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)