OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 1 : Part-8: Variables in Java
What is a Variable in Java?
A variable in Java is a named memory location that stores data values of a specific type. It acts as a container for values that can change during program execution.
Variable Declaration and Initialization
Syntax:
Example:
Types of Variables in Java
Java variables are classified based on their scope and position in the program:
| Type | Declared Inside | Scope | Memory Location |
|---|---|---|---|
| Local Variable | Method or block | Within method/block only | Stack |
| Instance Variable | Inside class (outside methods) | Whole object (per instance) | Heap |
| Static Variable | Inside class using static | Shared across all instances | Method Area (static memory) |
1. Local Variable
-
Exists only within methods, constructors, or blocks.
-
Must be initialized before use.
2. Instance Variable (Non-static Field)
-
Declared in a class but outside any method.
-
Each object gets its own copy.
3. Static Variable (Class Variable)
-
Declared with
statickeyword. -
Shared among all instances of the class.
Variable Naming Rules and Conventions
Rules (enforced by compiler):
-
Must begin with a letter,
$, or_. -
Cannot start with a digit.
-
No spaces or special characters (except
$and_). -
Can't use Java keywords (like
int,class).
Conventions (good practices):
| Element Type | Naming Style | Example |
|---|---|---|
| Variable | camelCase | studentName |
| Constant | UPPER_CASE | MAX_SPEED |
Data Types for Variables
Java is strongly typed, so every variable must have a type.
➤ Primitive Types:
-
Integer types:
byte,short,int,long -
Floating types:
float,double -
Character:
char -
Boolean:
boolean
➤ Reference Types:
-
Arrays
-
Objects
-
Strings
-
Interfaces
Variable Scope and Lifetime
| Type | Scope | Lifetime |
|---|---|---|
| Local | Method/block only | During method execution |
| Instance | Whole class (per object) | As long as object exists |
| Static | Class-wide | Till end of program |
Example Program Showing All Types
Best Practices for Variable Usage
-
Use meaningful names (
balance, notb). -
Initialize variables before using them.
-
Keep variable scope as small as possible.
-
Use constants (
final) for fixed values.
Comments
Post a Comment