What is the difference between local and instance variables in Java?
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).
What is the difference between a local variable, an instance field, an input parameter, and a class field?
A local variable is defined within the scope of a block. It cannot be used outside of that block.
Example:
if(x > 10) {
String local = "Local value";
}
I cannot use local
outside of that if
block.
An instance field, or field, is a variable that's bound to the object itself. I can use it in the object without the need to use accessors, and any method contained within the object may use it.
If I wanted to use it outside of the object, and it was not public
, I would have to use getters and/or setters.
Example:
public class Point {
private int xValue; // xValue is a field
public void showX() {
System.out.println("X is: " + xValue);
}
}
An input parameter, or parameter or even argument, is something that we pass into a method or constructor. It has scope with respect to the method or constructor that we pass it into.
Example:
public class Point {
private int xValue;
public Point(int x) {
xValue = x;
}
public void setX(int x) {
xValue = x;
}
}
Both x
parameters are bound to different scopes.
A class field, or static field, is similar to a field, but the difference is that you do not need to have an instance of the containing object to use it.
Example:
System.out.println(Integer.MAX_VALUE);
I don't need an instance of Integer
to retrieve the globally known maximum value of all ints.
Java local vs instance variable access speed
Ok, I've written a micro-benchmark (as suggested by @Joni & @MattBall) and here are the results for 1 x 1000000000 accesses for each a local and an instance variable:
Average time for instance variable access: 5.08E-4
Average time for local variable access: 4.96E-4
For 10 x 1000000000 accesses each:
Average time for instance variable access:4.723E-4
Average time for local variable access:4.631E-4
For 100 x 1000000000 accesses each:
Average time for instance variable access: 5.050300000000002E-4
Average time for local variable access: 5.002400000000001E-4
So it seems that local variable accesses are indeed faster that instance var accesses (even if both point to the same object).
Note: I didn't want to find this out, because of something I wanted to optimize, it was just pure interest.
P.S. Here is the code for the micro-benchmark:
public class AccessBenchmark {
private final long N = 1000000000;
private static final int M = 1;
private LocalClass instanceVar;
private class LocalClass {
public void someFunc() {}
}
public double testInstanceVar() {
// System.out.println("Running instance variable benchmark:");
instanceVar = new LocalClass();
long start = System.currentTimeMillis();
for (int i = 0; i < N; i++) {
instanceVar.someFunc();
}
long elapsed = System.currentTimeMillis() - start;
double avg = (elapsed * 1000.0) / N;
// System.out.println("elapsed time = " + elapsed + "ms");
// System.out.println(avg + " microseconds per execution");
return avg;
}
public double testLocalVar() {
// System.out.println("Running local variable benchmark:");
instanceVar = new LocalClass();
LocalClass localVar = instanceVar;
long start = System.currentTimeMillis();
for (int i = 0 ; i < N; i++) {
localVar.someFunc();
}
long elapsed = System.currentTimeMillis() - start;
double avg = (elapsed * 1000.0) / N;
// System.out.println("elapsed time = " + elapsed + "ms");
// System.out.println(avg + " microseconds per execution");
return avg;
}
public static void main(String[] args) {
AccessBenchmark bench;
double[] avgInstance = new double[M];
double[] avgLocal = new double[M];
for (int i = 0; i < M; i++) {
bench = new AccessBenchmark();
avgInstance[i] = bench.testInstanceVar();
avgLocal[i] = bench.testLocalVar();
System.gc();
}
double sumInstance = 0.0;
for (double d : avgInstance) sumInstance += d;
System.out.println("Average time for instance variable access: " + sumInstance / M);
double sumLocal = 0.0;
for (double d : avgLocal) sumLocal += d;
System.out.println("Average time for local variable access: " + sumLocal / M);
}
}
Why Are the Instance Variables Declared in the Main Method?
Variables defined within a method are local variables, they belong to an invocation of the method, not to an instance of an object.
The intent seems to be to provide an example that is understandable to beginners who haven't been introduced to constructors, instance variables, and methods. They want to teach local variable declaration, some simple calculating and if-statements, and printing to the console before getting into that other stuff.
As an exercise it would be fine for you to change the CarLoan class to give it instance variables, just to see another way to do it. Keep the variable values hard-coded, make an instance method that calculates the monthly payment, and have the main method print the result to the console.
local variable and instance variable. Java
The local variable phoneNumber
shadows the instance variable with the same name.
void setNumber(){
String phoneNumber;
phoneNumber = "4321";
}
So this code sets the local variable, doesn't change the instance variable.
If you wanted to change the instance variable, you would have to disambiguate,
using the this.
prefix, like this:
void setNumber(){
String phoneNumber;
this.phoneNumber = "4321";
}
... or better yet, just remove the pointless local variable entirely... (like you said @RobP!)
Related Topics
How to Sort Arraylist<Long> in Decreasing Order
How to View Tomcat Log Files in Eclipse
Comparing Time Is Incorrect When Picking 12:00
Boolean Expression Parser in Java
How to Calculate the Difference Between Two Arraylists
How to Check If a Url Exists or Returns 404 with Java
Should a "Static Final Logger" Be Declared in Upper-Case
Comparing and Thencomparing Gives Compile Error
What Is the "Default" Implementation of Method Defined in an Interface
Make a File/Folder Hidden on Windows with Java
Modifying Local Variable from Inside Lambda
Improvednamingstrategy No Longer Working in Hibernate 5
Spring Boot Redirect Http to Https
Throw Checked Exceptions from Mocks with Mockito