0

What is the difference between initialising a variable below a class and initialising below main method in java ?

https://code.sololearn.com/ceRysUNUD89f/?ref=app

3rd Jan 2020, 5:22 AM
Asharaf K
Asharaf K - avatar
4 Antworten
0
Yes it is possible and pretty common.
3rd Jan 2020, 8:07 AM
Avinesh
Avinesh - avatar
+ 2
A variable initialized inside a method is only in scope within that method. (at least in C# programming) so if i say int x = 1 in the "Main" method, then in another method called "Other" I try to call x or modify it, it wouldn't work because "Other" doesn't see what was made in "Main". Although this is only what i know from object oriented programming like C#, perhaps it's different in Java.
3rd Jan 2020, 5:41 AM
{ Aza }
{ Aza } - avatar
0
Variables declared inside a class but outside the main() are called instance variables and the one declared inside main() are called local variables. You can use any access modifier (public, private protected) for instance variables but you cannot do that for local variables. Only class variables or I should say static variables or static methods can be accessed inside main() without creating object of that class.
3rd Jan 2020, 6:49 AM
Avinesh
Avinesh - avatar
0
Is I possible to initialise variable and assign value in class
3rd Jan 2020, 7:57 AM
Asharaf K
Asharaf K - avatar