Loading content...
Loading content...
A variable is a memory location used to store data.
Each variable has a data type and stores value accordingly.
java
<data_type> <variable_name> = <value>;
int age = 25;
String name = "Anil";final is used to make a variable constant
Once assigned → value cannot be changed
java
final int a = 10;
// a = 20; ErrorDeclared inside class but outside methods
Accessible throughout the class
Stored in Heap Memory
JVM provides default values if not initialized
Instance Variable
Static Variable
Declared inside class without static keyword
Each object has its own copy
Created when object is created
Stored in Heap memory
java
class Student {
int sid;
String sname;
String semail;
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.sid = 101;
s1.sname = "Anil";
Student s2 = new Student();
s2.sid = 102;
s2.sname = "Rahul";
System.out.println(s1.sid + " " + s1.sname);
System.out.println(s2.sid + " " + s2.sname);
}
}Each object stores different data
Declared using static keyword
Shared among all objects
Created once at class loading time
Common for all objects
Stored in method area (JVM memory)
java
class Student {
int sid;
String sname;
static String nationality = "Indian";
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
System.out.println(s1.nationality);
System.out.println(s2.nationality);
}
}Both objects share the same static variable
Declared inside method / block / constructor
Must be initialized before use
Accessible only within their block
Stored in Stack Memory
No default value
java
class Test {
void m1() {
int b = 30; // local variable
System.out.println(b);
}
}When JVM starts, it divides memory into parts. Important ones:
Stores objects and class variables
Shared memory
Stores local variables and method calls
Each method has its own stack frame
After method execution → stack frame is removed
java
class Test {
// Class level variables
int a = 10;
byte b;
short s;
int i;
long l;
float f;
double d;
boolean bl;
char c;
void m1() {
int b = 30; // local variable
System.out.println(b);
}
}
public class Main {
public static void main(String[] args) {
int b = 29; // local variable
Test t1 = new Test();
System.out.println(t1.a);
System.out.println(t1.b);
System.out.println(t1.s);
System.out.println(t1.i);
System.out.println(t1.l);
System.out.println(t1.f);
System.out.println(t1.d);
System.out.println(t1.bl);
System.out.println(t1.c);
t1.m1();
System.out.println("Hello I am Java");
}
}Class variables → get default values
Local variables → must be initialized
Object (t1) → stored in Heap
Reference → stored in Stack
java
Student.nationality;java
Student s = null;
System.out.println(s.nationality);java
Student s1 = new Student();
System.out.println(s1.nationality);