Differencebetween a Local Variable, an Instance Field, an Input Parameter, and a Class Field

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.

What's the difference between a class variable and a parameter in a constructor?

The class variable is the one defined by the class as a static field, and the parameter is the one defined by the method. It's just that simple. There are also instance variables (defined at the class level but not static) and local variables (defined within a method, but not as input parameters).

public class Foo {
private static String someName; // this is a class variable
private String someOtherName; // this is an instance variable

public Foo(String anotherName) { // anotherName is a constructor parameter
int yetAnother = 1; // yetAnother is a local variable
someOtherName = "foo"; // assign a value to someOtherName
}

These two variables are completely distinct. They don't even have to have the same type! The only complication in your example is that both variables happen to have the same name. When that happens, the compiler will favor the constructor parameter (or method parameter, or local variable) over the class variable. In order to "force" it to use the class variable, you prefix it with this..

The thing to keep in mind is that the two variables are totally separate, regardless of their names.

So this:

class NewClass {

private String Variable = "";

Public NewClass (String Variable)
{
NewClass.Variable = Variable;
}
}

is exactly the same as this:

class NewClass {

private String Variable = "";

Public NewClass (String someOtherVariableName)
{
NewClass.Variable = someOtherVariableName;
}
}

... and it's also exactly the same as this:

class NewClass {

private String Variable = "";

Public NewClass (String Var)
{
NewClass.Variable = Var;
}
}

The convention of using the same name for a parameter as for the class variable just means you don't have to come up with pointless variants on the variable name.

Initialization of instance fields vs. local variables

For local variables, the compiler has a good idea of the flow - it can see a "read" of the variable and a "write" of the variable, and prove (in most cases) that the first write will happen before the first read.

This isn't the case with instance variables. Consider a simple property - how do you know if someone will set it before they get it? That makes it basically infeasible to enforce sensible rules - so either you'd have to ensure that all fields were set in the constructor, or allow them to have default values. The C# team chose the latter strategy.

assign instance field to local variable

To expand slightly on Michael's answer, I expect it is there to ensure that the keySet() method never returns null, possibly in addition to providing performance benefits noted.

Given this code:

public Set<K> keySet() {
return (keySet == null ? (keySet = new KeySet()) : keySet;
}

It would be at least theoretically possible in multi-threaded code that the keySet field could be set to null between the first read (keySet == null) and the second read, where it is returned. I haven't looked at the rest of the code, but I assume there are other places where keySet is potentially assigned null. Whether this is as a result of an issue seen in the wild, or a defensive measure would be a question for the authors.

The actual code:

public Set<K> keySet() {
Set<K> ks;
return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
}

...doesn't have this problem as the field is only read once.

What is the difference between field, variable, attribute, and property in Java POJOs?

From here: http://docs.oracle.com/javase/tutorial/information/glossary.html


  • field

    • A data member of a class. Unless specified otherwise, a field is not static.

  • property

    • Characteristics of an object that users can set, such as the color of a window.

  • attribute

    • Not listed in the above glossary

  • variable

    • An item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. See also class variable, instance variable, local variable.

When is it appropriate to assign values to an instance variable in Java?

The second version seems okay. But with the constant indeed as static final String.

public class CCipher {

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
private final String shiftedAlphabet;
private final int mainKey;

public CCipher(int key) {
mainKey = key;
shiftedAlphabet = ALPHABET.substring(mainKey)
+ ALPHABET.substring(0, mainKey);
}

Christopher Schneider pointed out that in for encrypting and decrypting different shiftedAlphabets are used. As a CCipher object in reality probably either encrypts or decrypts, make it a local variable.

One would need two different non-final lazily initialized fields which is cumbersome.

public class CCipher {

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
//private final String shiftedEncryptAlphabet;
//private final String shiftedDecryptAlphabet;
private final int mainKey;

public CCipher(int key) {
mainKey = key;
shiftedAlphabet = ALPHABET.substring(mainKey)
+ ALPHABET.substring(0, mainKey);
}

public String encrypt(String input){
String shiftedAlphabet = alphabet.substring(mainKey)
+ alphabet.substring(0, mainKey);
// ... code to encrypt input ...
}

public String decrypt(String input){
String shiftedAlphabet = alphabet.substring(26 - mainKey)
+ alphabet.substring(0, 26 - mainKey);
// ... code to decrypt input
}

Difference between field and this.field in Java

this keyword refers to the current object.
usually we use this.memberVariable to diffrentiate between the member and local variables

private int x=10;

public void m1(int x) {
sysout(this.x)//would print 10 member variable
sysout(x); //would print 5; local variable
}

public static void main(String..args) {
new classInst().m1(5);

}

Off from the concrete question,
the use of this In Overloaded constructors:

we can use this to call overloaded constructor like below:

public class ABC {
public ABC() {
this("example");to call overloadedconstructor
sysout("no args cons");
}
public ABC(String x){
sysout("one argscons")
}

}


Related Topics



Leave a reply



Submit