Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Static
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!
A "static" object is unique; it belongs to the class rather than the instance of the class. In other words, a static variable is only allocated to the memory once: when the class loads. No matter how many instances you create from a class, the static variable is only allocated to the memory once, making your program memory efficient. When a program is running and there's only one instance of something, it is "static". Take a look at the program below for examples of static methods and variables, and how we can call them without the use of an object.
StaticFieldsExample.java
package exlcode;
public class StaticFieldsExample {
public static void main(String[] args) {
// static variables and methods can be accessed
// without creating an object
System.out.println(StaticFieldsTest.exampleVariableOne);
StaticFieldsTest.print();
}
}
StaticFieldsTest.java
package exlcode;
public class StaticFieldsTest {
public static String exampleVariableOne = "Java";
private static String exampleVariableTwo= "Hello World!";
public static void print() {
System.out.println(exampleVariableTwo);
}
}
We don't need to create a new object to access "static" members of a class. We call the class name and use "dot notation" to specify the member we want to access. Static members are attached to a class rather than an object or an instance of the class.
As a programmer, it is important to note that since there is only one version of the "static" members, when the variable's value is changed, the value of that variable is changed for every object in the class.
Also, keep in mind that the main method of each class is static because there are no objects that exist for the class when the JVM calls the main method. Objects are usually created inside the main method, which is why the method itself has to be static.