Lecture Note on Declaration of Variables, Scope of
Variables, Symbolic Constants, and Type Casting in Java
1. Declaration of Variables
In Java, a variable is a named storage location used to hold data that can be manipulated during
program execution. Variables must be declared before use, specifying their data type and name.
Syntax:
dataType variableName;
or with initialization:
dataType variableName = value;
Key Points:
Data Types: Java supports primitive types ( int , double , char , boolean , etc.) and reference
types (e.g., String , arrays, objects).
Variable Naming: Names must start with a letter, underscore ( _ ), or dollar sign ( $ ), followed by
letters, digits, _ , or $ . Names are case-sensitive and should follow camelCase convention (e.g.,
myVariable ).
Examples:
int age = 25; // Integer variable
double salary = 50000.75; // Floating-point variable
char grade = 'A'; // Character variable
String name = "Alice"; // String variable
2. Scope of Variables
The scope of a variable defines where it can be accessed within a program. Java variables have
different scopes based on where they are declared.
Types of Variable Scopes:
1. Class Scope (Instance Variables):
Declared inside a class but outside any method.
Accessible to all methods in the class, depending on access modifiers ( public , private ,
etc.).
Exists as long as the object exists.
Example:
class Student {
int rollNo = 101; // Instance variable
void display() {
System.out.println("Roll No: " + rollNo);
}
}
2. Method Scope (Local Variables):
Declared inside a method or block.
Accessible only within that method or block.
Must be initialized before use.
Example:
void calculate() {
int sum = 10 + 20; // Local variable
System.out.println("Sum: " + sum);
}
3. Block Scope:
Variables declared within a block (e.g., inside {} in loops or conditionals).
Accessible only within that block.
Example:
for (int i = 0; i < 5; i++) { // i is block-scoped
System.out.println(i);
}
// System.out.println(i); // Error: i is not accessible here
4. Static Scope (Class Variables):
Declared with the static keyword inside a class.
Shared across all instances of the class.
Example:
class Example {
static int count = 0; // Static variable
}
3. Symbolic Constants
Symbolic constants are variables whose values cannot be changed once assigned. In Java, they are
declared using the final keyword.
Syntax:
final dataType CONSTANT_NAME = value;
Key Points:
By convention, constant names are in UPPER_CASE with underscores separating words.
Constants must be initialized at declaration or in a static block for static final fields.
Used to define values that remain unchanged, e.g., mathematical constants or configuration
values.
Example:
final double PI = 3.14159;
final int MAX_STUDENTS = 100;
// MAX_STUDENTS = 200; // Error: cannot reassign a final variable
4. Type Casting
Type casting is the process of converting a variable from one data type to another. Java supports
two types of casting: implicit and explicit.
a. Implicit Casting (Widening Conversion)
Automatically performed when converting a smaller data type to a larger one (no data loss).
Example:
int num = 100;
double d = num; // Implicit casting: int to double
System.out.println(d); // Output: 100.0
b. Explicit Casting (Narrowing Conversion)
Required when converting a larger data type to a smaller one (potential data loss).
Use the target type in parentheses before the value.
Example:
double d = 123.456;
int num = (int) d; // Explicit casting: double to int
System.out.println(num); // Output: 123 (decimal part truncated)
Key Points:
Widening Order: byte → short → int → long → float → double .
Narrowing Risks: Loss of precision or data (e.g., truncating decimals in double to int ).
Casting with Objects:
Use instanceof to check type before casting to avoid ClassCastException .
Example:
Object obj = "Hello";
if (obj instanceof String) {
String str = (String) obj; // Explicit casting
System.out.println(str);
}
Example Program Combining All Concepts
public class VariableDemo {
static final int MAX_SCORE = 100; // Symbolic constant
int instanceVar = 10; // Instance variable
public void demonstrate() {
int localVar = 20; // Local variable
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Local Variable: " + localVar);
System.out.println("Constant: " + MAX_SCORE);
// Type casting
double d = 45.67;
int castedVar = (int) d; // Explicit casting
System.out.println("Casted double to int: " + castedVar);
}
public static void main(String[] args) {
VariableDemo demo = new VariableDemo();
demo.demonstrate();
}
}
Output:
Instance Variable: 10
Local Variable: 20
Constant: 100
Casted double to int: 45