Variables and Methods in Java
1. Variables in Java
Definition:
A variable is a named memory location that stores data during program execution.
In Java, variables have a data type (like int, String, etc.), and they must be declared before
use.
Types of Variables:
1. Local Variable — Declared inside a method, constructor, or block; stored in Stack; exists
until the method/block ends.
2. Instance Variable — Declared inside a class but outside methods; stored in Heap; exists as
long as the object exists.
3. Static Variable — Declared inside a class with 'static' keyword; stored in Method area
(shared across all objects); exists for the entire program.
Example:
class Example {
static int staticVar = 100; // Static variable
int instanceVar; // Instance variable
void show() {
int localVar = 10; // Local variable
System.out.println("Local: " + localVar);
System.out.println("Instance: " + instanceVar);
System.out.println("Static: " + staticVar);
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.instanceVar = 50;
obj.show();
}
}
Output:
Local: 10
Instance: 50
Static: 100
2. Methods in Java
Definition:
A method is a block of code that performs a specific task. Methods make code reusable,
readable, and modular.
Types of Methods:
1. Instance Methods — Belong to an object; need an object to call.
2. Static Methods — Belong to the class; can be called without creating an object.
3. Abstract Methods — Declared without implementation (used in abstract classes).
4. Final Methods — Cannot be overridden in child classes.
5. Synchronized Methods — Used in multithreading for thread safety.
Method Syntax:
returnType methodName(parameters) {
// method body
return value; // if returnType is not void
}
Example:
class Calculator {
// Instance Method
int add(int a, int b) {
return a + b;
}
// Static Method
static int multiply(int a, int b) {
return a * b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
// Calling instance method
System.out.println("Sum: " + calc.add(5, 10));
// Calling static method
System.out.println("Product: " + Calculator.multiply(3, 4));
}
}
Output:
Sum: 15
Product: 12
Key Points:
- Variables store data; methods define actions.
- Instance variables → tied to objects.
- Static variables → shared across objects.
- Local variables → temporary and exist only within a method/block.
- Instance methods work on object data; static methods work on class-level data.