What is the difference between local and instance variables in Java? - java

Except the scope and the storage differences, are there any other major difference between instance and local variables in Java?

The main differences that I see are in their:
Scope: Local variables are visible only in the method or block they are declared whereas instance variables can been seen by all methods in the class.
Place where they are declared: Local variables are declared inside a method or a block whereas instance variables inside a class, but outside a method.
Existence time: Local variables are created when a method is called and destroyed when the method exits whereas instance variables are created using new and destroyed by the garbage collector when there aren't any reference to them.
Access: You can't access local variables, whereas instance variables can be accessed if they are declared as public.
Where they are declared: Local variables are declared in a method or a block before they are called, whereas instance variables can be declared anywhere in the class level (even after their use).
Instance variables always have value, even if they are not assigned by the code (then they will have for example null, 0, 0.0, and false). For local variables, there must be an assigned value by the code. Otherwise the compiler generates an error.

One extra thing I can think of:
Instance variables are given default values, i.e., null if it's an object reference, and 0 if it's an int.
Local variables don't get default values, and therefore need to be explicitly initialized (and the compiler usually complains if you fail to do this).

One other difference is you don't have to worry about concurrent access to local variables; whereas you do with instance variables in a multi-threaded environment.

No, you pretty much covered it. An instance variable belongs to an instance of a class, and a local variable belongs to a stack frame.
Instance variables are initialized to default values, but it's generally good practice to use explicit initializations anyway.

A local variable:
is declared inside a method/constructor or within a block (enclosed in braces)
must be initialized before use. Otherwise it won't compile.
An instance variable:
is declared inside a class.
initialization is not compulsory: if omitted, it contains the default value (0, 0.0, false, null, etc.)

-> local variable is declared in the body of a method and can be used
only from the point at which it’s declared through the end of the method
declaration.
-> An instance variable is declared in a class, but not in the body
of any of the class’s methods. Also, instance variables are accessible to all
methods of the class.

Aside from all that is already mentioned here, I would like to point out that local variables are a bit faster to access for the JVM. The JVM has got more work to do to read or write an instance variable compared to a a local variable.
This is still true for the current HotSpot server JVM, because it's not a VM optimization problem. It's rather caused by the fact that an instance variable is visible outside of the method and could thus be accessed from other threads while the method is executed.

Aside from all the differences mentioned in previous answers, I would like to point out one more difference that, instance variables can have access modifiers (like private, public, protected, etc.), but local variables will not have any access modifiers.

Local variables are on the stack, but member variables (instance variables) are on the heap.

Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.
Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.

Local variables are declared within a method.
Instance variables are declared inside a class but not within a method.
Local variables do not get a default value. The compiler complains if you try to use a local variable before before the variable is initialised.
However, instance variables always get a default value. If you don't explicitly assign a value to an instance variable, the instance variable still has a value.
integers 0
floating points 0
Boolean false
references null

The main difference is instance variables get default values. Like an int value gets zero and a char gets a null, but not the local variables.
You can leave uninitialized instance variable, but where as local variables must be initialized otherwise you will get compiler error.

Existence time:
I would like to tell you the major important difference between these variables is that when I encountered a problem where my instance variable during my software development worker life. Problem was occurring when user log in I have to return a username of user, who log in, but there is a problem, where for example one user log in it work successful but when another user log in while program run it return again a username, which log in before. I did run the program like debug mode and I could see a problem within my instance variable, which it could be local variable in my authentication method. The reason I tell that be careful when you work local and instance variable in programming language. All programmers don't take enough time simply topics, but small problems create great complexity.

Related

Why unnecessarily initialize a variable?

We know that there is a default of each primitive data type in Java(For e.g.:- The default value of double data type is 0.0d.).Then if we want the value of a variable(suppose double a) to be equal to the default value,why should we need to specify the value as:
double a=0.0d;
Why can't we not just use the default value of the variable anywhere as its default value is the same as the value we want to assign?
Different types do have default values that will be assigned to any unassigned fields of that type. However, this does not apply to local variables, as shown in the Language Specification §4.12.5:
A local variable (§14.4, §14.14) must be explicitly given a value
before it is used, by either initialization (§14.4) or assignment
(§15.26), in a way that can be verified using the rules for definite
assignment (§16 (Definite Assignment)).
I speculate that this is to make your code clearer. In a method, you would want readers of your code know what each and every variable's value is, instead of relying on the reader remembering facts like "a booleans default value is false". Since what you are writing is likely an algorithm of some sort, you want to write it as clearly as possible for other people.
In fields however, this is not required. I think this is because you are not describing a set of steps to do something. Instead, you are just saying that this object has some property. The semantics are a little different here.
As per Java language specification local variable must be initilized before use. Let's see why would such rule would have been made for local variables and not for instance variables.
Compiler tries to eliminate as much errors as possible during compile time only thereby making the application runtime more stable. For this it detects the issues it can at compile time and throws compile time exceptions.
Non final instance variables can be initilized in constructor (which may be multiple, overloaded) or in one of the methods of the class. Before using such a variable compiler does not complain as it assumes programmer would have provided the initial value in some method or constructor. The initilization depends on run time of the application as during run time a method can be invoked which does the initilization and hence compile time detection if value is not provided by the programmer is not possible and hence compiler chooses the safe option of allowing usuage and provides the default value in case method or constructor which handles the initilization is not invoked.
Non final local variable can only be initilized within it's method. There is not much point of making a non final variable if user wants to use the default value. It makes more sense to use the value directly or use a final keyword. If a non final local variable has been used then compiler forces the user to provide the initial value which may or may not be the default value.
For final fields both instance level and local, compiler forces the user to provide the initial value.
You need to initialise only local variables or class level variables declared final as per the java language spec. They won't be initialised with default values.

How to declare a variable then store a value for it later in a method?

If I declare a variable early on in a class, say double answer, can I assign it a value later on in another method, then recall that variable with that value in another instance? I'm unsure since it seems that the variable would be a local variable, and thus I can't recall it later in another method
Sounds like two questions:
(1) If you declare a variable early in a class, and then later assign it a value inside a method, the assignment from the method will be effective.
(2) However it will not be effective to another instance of the class, unless the variable is static. (Read about static variables here: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html) You need to read about all the details, but the short versions is: if your variable is static it will have one value shared between all instances of your class.

Why local variable MUST be initialized and why instance variables MUST NOT be initialized before using?

I've noticed that the JAVA allows to use uninitialized instance variable but it blocks to use uninitialized local variables. I want to know why the language is saying so?
Note : This is not the first post of this kind. I've visited below questions too. But couldn't find the exact reason for WHY?
This question may be a duplicate one of the following:
Uninitialized variables and members in Java
Why are local variables not initialized in Java?
As I know,
Instance variable: will be initial at the run time when class initial and default of instance variable is null => instance variable will error at run time.
Local variable: Unlike class and instance variables, a local variable is fussy about where you position the declaration for it: You must place the declaration before the first statement that actually uses the variable. => local variable error with syntax error.
ref: Local variable in java
I've noticed that the JAVA allows to use uninitialized instance
variable.
No, the compiler initialize instance variables, if you don't initialize.

Local variables or member variables in Java

I have a question about local and member variables in Java. The situation is: Sometimes if I define a local variable, that variable has to be passed around into several levels of method calls. I often think, why should I just define a member variable for the class so that the variable is available everywhere in the class. A member variable of a class is like a global variable accessible everywhere in the class.
What's the best practice for this scenario? OR what's the right thing to do?
If I define it as a member variable, should it be a static or non-static variable?
Member variables hold characteristics -- attributes is another term -- for the 'thing' in your program represented by the class. If your variable holds something like that, make it a member variable; if it doesn't, don't.
Static variables hold characteristics of the class itself, as opposed to characteristics of objects of that class.
Don't make the decision based on whether you "pass ... into several levels of method calls.
Thinking about your general question, I came up with these guidelines from my experience:
Use the smallest poosible scope. If a local variable is fine, then why use a member variable?
Model the class according to the domain. If you have a value and it is part of the class responsibility, then modeling it as a class member seems to be appropiate.
To your second question: I do generally define static variables as final which make them constants. Non-final static members in a multi-threaded environment may easily introduce race conditions. It is easier to make access to non-static member thread-safe if needed.
It's behavioral. If your variable is part of your class attribute i.e. characterizes the class behavior then define it as the class member variable otherwise define a local variable inside the method.
In my opinion, passing the argument doesn't contribute in the attribute type definition.
It depends.
If you want all (or several), of your methods to access the same member variable, then declare it in the class.
Static or not depends on wether that information belongs to the Class (static), or to an instance of the class (non-static).
1.) If you are going to use it in multiple methods and need to pass it around make its member variable. If it is just for that method make it local.
2.) static means their is only one instance of that variable that is shared among everything. So for example I have a totalGameScore variable that will keep my score for the whole game no matter what. You'd want to make that variable static. Other than that lets say I have a health variable for my enemy. Each enemy will have its own health so I would NOT make that variable static.
You can also declare member variables private so that other classes cannot access them.
Constants should normally always be member variables.
If you decide to declare a member variable then you should consider the variables scope. If you are just reducing the number of parameters on internal method calls I would consider declaring the variable as private.
You should be careful of using Static because every instance of the class will use the same copy of the variable.

Default values of instance variables and local variables

I read that Java provides default values to class properties, but not to local variables. Is that correct?
If so, what is the reason behind this? When you are doing something good, why not do it all the way?
Standard local variables are stored on the stack and aren't actually created until they are initialized. If a local variable isn't used, it doesn't go on the stack. Member variables, however, are allocated in the heap, and thusly have a default placeholder (null reference or default primitive).
The non-technical reason behind may also be the following one:
If you declare a local variable, you do this in order to use it. And usage is connected with assigning a value. Therefore, accessing a declared, but not initialized, variable does not make that much sense - the programmer might simply have forgotten to initialize the variable.
Fields, however, might only be used until or after a specified point in the object's lifetime. Forcing the programmer to initialize them all would not be good.

Categories

Resources