Variables
A variable in Java is a named storage location in memory that holds a value which can be changed during program execution. Variables allow you to store, retrieve, and manipulate data in your programs.
Properties
Section titled “Properties”- Has a specific data type (e.g.,
int,double,String) - Has a name (identifier)
- Can store a value (which may change during program execution)
- Has a scope (where it can be accessed in the code)
Declaration vs. Definition
Section titled “Declaration vs. Definition”| Term | Description | Example |
|---|---|---|
| Declaration | Introducing a variable’s name and type to the compiler, without necessarily assigning a value | int x; |
| Definition | Both declaring a variable and assigning it an initial value | int x = 10; |
Basic Assignment
Section titled “Basic Assignment”The basic way to assign a value is with the assignment operator (=):
// Simple variable declaration and assignmentint age = 25;double salary = 75000.50;char grade = 'A';boolean isActive = true;String name = "John Smith";Assignment with Expressions
Section titled “Assignment with Expressions”You can assign the result of an expression to a variable:
int a = 5;int b = 10;int sum = a + b; // sum equals 15int product = a * b; // product equals 50double result = (a + b) / 2.0; // result equals 7.5Best Practices
Section titled “Best Practices”- Initialize variables when declaring them, unless there’s a specific reason not to
- Use meaningful variable names that describe what the variable represents
- Limit variable scope to where it’s needed
- Use
finalfor values that shouldn’t change - Be careful with type conversions to avoid data loss