Java Variables
1. Variable Declaration:
int age; // Declaration of an integer variable named 'age'
double salary; // Declaration of a double variable named 'salary'
String name; // Declaration of a String variable named 'name'
2. Variable Initialization:
int age = 25; // Initialization of the 'age' variable
double salary = 50000.75; // Initialization of the 'salary' variable
String name = "John"; // Initialization of the 'name' variable
3. Variable Types:
Primitive Data Types: Hold simple values directly.
int count = 10;
double pi = 3.14;
char grade = 'A';
boolean flag = true;
Reference Data Types: Hold references to objects in memory.
String message = "Hello, World!";
MyClass myObject = new MyClass();
4. Variable Naming Rules:
- Variable names are case-sensitive.
- The first character must be a letter, underscore (
_
), or dollar sign ($
). - Subsequent characters can be letters, digits, underscores, or dollar signs.
- Avoid using Java reserved words (e.g.,
int
,double
,class
, etc.) as variable names. - Use meaningful names that describe the variable's purpose.
5. Variable Scope:
- The scope of a variable is the region of the program where the variable is accessible.
- Java has block scope, meaning a variable is only accessible within the block of code where it is declared.
- Class-level variables (fields) have class scope and are accessible throughout the class.
6. Final Variables:
You can use the final
keyword to declare a constant variable, meaning its value cannot be changed after initialization.
final double PI = 3.14159;
7. Variable Types in Methods:
- Method parameters and local variables follow the same rules as other variables.
- Method parameters receive values when the method is called.
- Local variables are declared inside a method and have block scope.
public class Example {
// Class-level variable
static int globalVar = 100;
public static void main(String[] args) {
// Method-level variable
int localVar = 42;
// Accessing class-level variable
System.out.println(globalVar);
// Accessing method-level variable
System.out.println(localVar);
}
}
Understanding and using variables effectively is fundamental to programming in Java. They allow you to store and manipulate data, making your programs dynamic and responsive.