Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why variable defined in a class is not a local variable but instance variable in java?

Tags:

java

According to the doc Local variables in java are declared in methods, constructors, or blocks.

In the below Class A isn't x a local variable too since it is in blocks({}) i know they are called as instance variable but i am confused? If yes Access modifiers cannot be used for local variables but i am sure i can add public private protected ? It also says that local variable are stored in stack but as per the below code x will be stored in heap right since they are part of the instance?

class A{

private int x = 5; // Isn't this a local varibale too since it is in blocks 

}

.

class A{

public void function(){
int x = 5; // this is a local variable since it is declared in a function
private int x2=5; // Error Access modifiers cannot be used for local variables
}

}
like image 468
dev_marshell08 Avatar asked May 20 '26 04:05

dev_marshell08


1 Answers

In the below Class A isn't x a local variable too since it is in blocks({})

No. It's not in a block. It's in a class declaration, but that's not a block as such. "Block" isn't synonymous with "text in braces".

To be a bit clearer, local variables are declared in:

  • Methods
  • Constructors
  • Static initializers
  • Instance initializers

If you look at the production for a class declaration, that's not a Block (unlike the production for static initializers and instance initializers).

like image 103
Jon Skeet Avatar answered May 21 '26 18:05

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!