Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Field Variables
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Field variables are variables that are declared as a member of a class or declared outside any method or constructor within the class. Please review the example below showing two field variables.
FieldVariableExample.java
package exlcode;
public class FieldVariableExample {
// these are field variables
public static int exampleVariableOne = 10;
public static int exampleVariableTwo = 6;
public static void main(String[] args) {
System.out.println(add(exampleVariableOne, exampleVariableTwo));
multiply();
}
public static int add(int x, int y) {
// this is a local variable
int exampleVariableThree = x + y;
return exampleVariableThree;
}
public static void multiply() {
System.out.println(exampleVariableOne * exampleVariableTwo);
}
}
Field variables, as opposed to local variables, can be called in any of the methods that exist in the same class. A field variable is available as long as the instance it belongs to is active. The class is active when any method in it is used. Therefore if the field variable belongs to the class, it can be used within any of the methods inside that class.
There are two categories of field variables: instance variables and class variables. The code we reviewed above shows examples of two class variables. We see this because they are declared with the static modifier. We will discuss the significance of static as we move further along in our courses.
Instance variables are non-static fields and therefore declared without the Java reserved word static. All of these values are unique to each instance of a class. This will be explained further when we study the concept of objects.