Local (Automatic/Stack/Method) Variables

Local (Automatic/Stack/Method) Variables

Local variable is basically use for the declared within a method, Its means mainly variable is not just initialized within the method, but also declared within the method, Local variable is basically in always n the stack but its not happening in the case of heap.if the variable is an object reference the object itself will still be created on the heap.

There is no such thing as a stack object, only a stack variable.

class TestServer {
public void logIn() {
int count = 10;
}
}

The compiler will reject any code that tries to use a local variable that hasn\'t been assigned a value, because unlike instance variables local variables don\'t get default values.

class TestServer {
public void logIn() {
int count = 10;
}
public void doSomething(int i) {
count = i; // Won\'t compile! Can\'t access count outside method login()
}

It is possible to declare a local variable with the same name as an instance variable.

class TestServer {
int count = 9; // Declare an instance variable named count
public void logIn() {
int count = 10; // Declare a local variable named count
System.out.println(\"local variable count is \" + count);
}
public void count() {
System.out.println(\"instance variable count is \" + count);
}
public static void main(String[] args) {
new TestServer().logIn();
new TestServer().count();
}
}

OUTPUT is :
local variable count is 10
instance variable count is 9

By:UMANG
Date:2025-02-09 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related Java Subjective Links

Java Subjective interview questions and answers for experienced and fresher