Java Variable Types
In the Java language, all variables must be declared before they can be used.
The basic format for declaring a variable is as follows:
Format description:
- type -- the data type.
- identifier -- is the variable name, and commas can be used,to separate and declare multiple variables of the same type.
The following lists some examples of variable declarations. Note that some include an initialization process.
The variable types supported by the Java language are:
Local Variables:Local variables are variables declared inside a method, constructor, or block. They are destroyed when the method, constructor, or block in which they are declared finishes execution. Local variables need to be initialized when declared; otherwise, a compilation error will occur.
public void exampleMethod() { int localVar = 10; // 局部变量 // ... }Instance Variables:Instance variables are declared in a class but outside methods, constructors, or blocks. They belong to instances of the class, and each instance of the class has its own copy. If not explicitly initialized, instance variables are assigned default values (0 for numeric types, false for boolean, null for object reference types).
public class ExampleClass { int instanceVar; // 实例变量 }Static Variables or Class Variables:Class variables are variables declared with the static keyword in a class. They belong to the class rather than instances. All instances of the class share the same class variable value. Class variables are initialized when the class is loaded, and only initialized once.
public class ExampleClass { static int classVar; // 类变量 }Parameters:Parameters are variables in method or constructor declarations, used to receive values passed when calling the method or constructor. The scope of parameter variables is limited to within the method.
public void exampleMethod(int parameterVar) { // 参数变量 // ... }
The following example defines a ExampleTest class, which contains a member variable instanceVar and a static variable staticVar.
In the method() method, a parameter variable paramVar and a local variable localVar are defined. Inside the method, we assign the local variable's value to the member variable, assign the parameter variable's value to the static variable, and then print out the values of these variables.
In the main() method, we create a ExampleTest object and call its method() method.
Example
Run the above code, and the output is as follows:
成员变量: 10 静态变量: 20 参数变量: 20 局部变量: 10
Java Parameter Variables
Parameter variables in Java are variables declared in methods or constructors, used to receive values passed to the method or constructor. Parameter variables are similar to local variables, but they exist only when the method or constructor is called and can only be used inside the method or constructor.
The declaration syntax for a Java method is as follows:
accessModifier returnType methodName(parameterType parameterName1, parameterType parameterName2, ...) {
// 方法体
}
- parameterType -- represents the type of the parameter variable.
- parameterName -- represents the name of the parameter variable.
When calling a method, we must pass values to the parameter variables; these values can be constants, variables, or expressions.
There are two ways to pass values to method parameter variables:Pass by valueandPass by reference。
Pass by value:When a method is called, a copy of the actual parameter value is passed. When the parameter variable is assigned a new value, only the copy's value is modified, and the original value is not affected. Basic data types in Java use pass-by-value to pass parameter variable values.
Pass by reference:When a method is called, a reference (i.e., memory address) to the actual parameter is passed. When the parameter variable is assigned a new value, the content of the original value is modified. Object types in Java use pass-by-reference to pass parameter variable values.
The following is a simple example demonstrating the use of method parameter variables:
Example
public static void main(String[] args) {
int a = 10, b = 20;
swap(a, b); // Call the swap method
System.out.println("a = " + a + ", b = " + b); // Output the values of a and b
}
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
}
Run the above code, and the output is as follows:
a = 10, b = 20
Java Local Variables
Local variables in Java are variables declared inside a method, constructor, or statement block, and their scope is limited to the code block in which they are declared.
The declaration syntax for local variables is:
type variableName;
- type -- represents the type of the variable.
- variableName -- represents the name of the variable.
Description:
-
Scope: The scope of a local variable is limited to the method, constructor, or code block in which it is declared. Once the code execution flow leaves this scope, the local variable is no longer accessible.
-
Lifecycle: The lifecycle of a local variable starts when it is declared and ends when the method, constructor, or code block finishes execution. After that, the local variable will be garbage collected.
-
Initialization: Local variables must be initialized before use. If they are not initialized, the compiler will report an error because Java does not provide default values for local variables.
-
Declaration: Local variables must be declared at the beginning of a method or code block. During declaration, you can specify the data type, followed by the variable name, for example:
int count;。 -
Assignment: A local variable must be assigned a value after declaration before it can be used in the method. The assignment can be a direct assignment, or through a method call or expression.
-
Restrictions: Local variables cannot be directly accessed by other methods of the class; they are private to the method or code block in which they are declared.
-
Memory Management: Local variables are stored on the stack of the Java Virtual Machine (JVM), unlike instance variables or objects, which are stored on the heap.
-
Garbage Collection: Since the lifecycle of local variables is strictly limited to the execution of a method or code block, they are no longer referenced after the method or code block finishes execution. Therefore, the JVM's garbage collector automatically reclaims the memory they occupy.
-
Reuse: Names of local variables can be reused in different methods or code blocks because their scope is local and does not cause naming conflicts.
-
Parameters and Return Values: Method parameters can be regarded as a special kind of local variable. They are initialized when the method is called, and their lifecycle ends after the method returns.
Example
The following is a simple example demonstrating the use of local variables:
Example
public static void main(String[] args) {
int a = 10; // Declaration and initialization of local variable a
int b; // Declaration of local variable b
b = 20; // Initialization of local variable b
System.out.println("a = " + a);
System.out.println("b = " + b);
// If a local variable is not initialized before use, the compiler will report an error
// int c;
// System.out.println("c = " + c);
}
}
In the above example, we declared and initialized two local variables a and b, and then printed out their values. Note that if you do not initialize a local variable before using it, the compiler will report an error.
In the following example, age is a local variable defined in the pupAge() method, and its scope is limited to this method:
The compilation and running result of the above example is as follows:
小狗的年龄是: 7
In the following example, the age variable is not initialized, so a compilation error occurs:
The compilation and running result of the above example is as follows:
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
Member Variables (Instance Variables)
- Member variables are declared in a class, but outside methods, constructors, and statement blocks.
- When an object is instantiated, the value of each member variable is determined accordingly.
- Member variables are created when the object is created and destroyed when the object is destroyed.
- The values of member variables should be referenced by at least one method, constructor, or statement block, so that external code can obtain instance variable information through these means.
- Member variables can be declared before or after their use.
- Access modifiers can modify member variables.
- Member variables are visible to methods, constructors, or statement blocks within the class. In general, member variables should be set to private. By using access modifiers, member variables can be made visible to subclasses.
- Member variables have default values. The default value for numeric variables is 0, for boolean variables is false, and for reference type variables is null. The value of a variable can be specified at declaration time or in the constructor.
- Member variables can be accessed directly by variable name. However, in static methods and other classes, you should use the fully qualified name:ObjectReference.VariableName。
The declaration syntax for member variables is:
accessModifier type variableName;
- accessModifier -- Indicates the access modifier, which can be public, protected, private, or the default access level (i.e., no access modifier explicitly specified).
- type -- Indicates the type of the variable.
- variableName -- Indicates the name of the variable.
Unlike local variables, member variables have their values allocated when the object is created. Even if they are not initialized, they are given default values. For example, variables of type int default to 0, and variables of type boolean default to false.
Member variables can be accessed through an object, or through the class name (if they are static member variables). If member variables are not explicitly initialized, they are given default values. You can initialize member variables in constructors or other methods, or access them through an object or class name to set their values.
Example
In the following example, we declare two member variables a and b, and access and set them. Note that we can access member variables through an object, and we can also access static member variables through the class name.
Example
private int a; // Private member variable a
public String b = "Hello"; // Public member variable b
public static void main(String[] args) {
ExampleTest obj = new ExampleTest(); // Create object
obj.a = 10; // Access member variable a and set its value to 10
System.out.println("a = " + obj.a);
obj.b = "World"; // Access member variable b and set its value to "World"
System.out.println("b = " + obj.b);
}
}
The above example compiles and runs with the following result:
a = 10 b = World
In the following example, we declare two member variables name and salary, and access and set them.
Employee.java file code:
The above example compiles and runs with the following result:
$ javac Employee.java $ java Employee 名字 : EXAMPLE 薪水 : 1000.0
Class Variables (Static Variables)
A static variable in Java is a variable defined in a class. It is associated with the class rather than with instances. That is, no matter how many class instances are created, there is only one copy of the static variable in memory, shared by all instances.
Static variables are created when the class is loaded and exist throughout the entire program execution.
Definition Method
The way to define a static variable is to use thestatickeyword to modify the variable, which is also commonly called a class variable.
In the following example, we define a static variablecount, with an initial value of 0:
Example
public static int count = 0;
// Other member variables and methods
}
Access Method
Since static variables are associated with the class, you can access static variables through the class name, and you can also access static variables through the instance name.
Example
MyClass obj = new MyClass();
obj.count = 20; // Access through instance name
Lifecycle
The lifecycle of static variables is as long as the program's lifecycle. That is, they are created when the class is loaded and exist throughout the entire program execution, and are not destroyed until the program ends. Therefore, static variables can be used to store data needed by the entire program, such as configuration information, global variables, etc.
Initialization Timing
Static variables are initialized when the class is loaded, and their initialization order is related to the order of definition.
If a static variable depends on another static variable, it must be defined after the other one.
Example
public static int count1 = 0;
public static int count2 = count1 + 1;
// Other member variables and methods
}
In the above example, count1 must be initialized before count2; otherwise, a compilation error will occur.
The Difference Between Constants and Static Variables
Constants are also associated with the class, but they are variables modified with the final keyword, and once assigned, they cannot be modified. Unlike static variables, the value of a constant is determined at compile time, while the value of a static variable can be changed at runtime. In addition, constants are usually used to store fixed values, such as mathematical constants, configuration information, etc., while static variables are usually used to store mutable data, such as counters, global state, etc.
In summary, static variables are variables associated with the class, with uniqueness and sharing. They can be used to store data needed by the entire program, but attention should be paid to initialization timing and the difference from constants.
Access Modifiers for Static Variables
The access modifier for static variables can be public, protected, private, or the default access modifier (i.e., not writing an access modifier).
It should be noted that the access permission of static variables is different from that of instance variables, because static variables are associated with the class and do not depend on any instance.
Thread Safety of Static Variables
Static variables in Java belong to the class, not to object instances. Therefore, when multiple threads access a class containing static variables at the same time, their thread safety needs to be considered.
Static variables have only one copy in memory, shared by all instances. Therefore, if one thread modifies the value of a static variable, other threads will also see the modified value when accessing that static variable. This may cause concurrency issues, because multiple threads may modify the static variable at the same time, leading to uncertain results or data consistency problems.
To ensure the thread safety of static variables, appropriate synchronization measures are needed, such as synchronization mechanisms, atomic classes, or the volatile keyword, so that the values of static variables can be correctly read and modified in a multi-threaded environment.
Naming Conventions for Static Variables
The naming convention for static variables (also called class variables) usually follows camelCase, and usually uses all uppercase letters with underscores between words, and should be explicitly marked with the static keyword.
Use camelCase:The naming of static variables should use camelCase, that is, the first letter is lowercase, and the first letter of each subsequent word is uppercase. For example:
myStaticVariable。All uppercase letters:Static variables usually use all uppercase letters with underscores between words. This is called "Upper Snake Case". For example:
MY_STATIC_VARIABLE。Descriptive:Variable names should be meaningful and clearly express the purpose of the variable. Avoid using single characters or abbreviations without clear meaning.
Avoid using abbreviations:Try to avoid using abbreviations to improve code readability. If using abbreviations is necessary, ensure they are widely understood and explain them in comments.
Example
// Use camelCase
public static int myStaticVariable;
// Use Upper Snake Case
public static final int MAX_SIZE = 100;
// Avoid using abbreviations
public static final String employeeName;
// Descriptive variable names
public static double defaultInterestRate;
}
Usage Scenarios for Static Variables
Static variables are commonly used in the following scenarios:
- Storing global state or configuration information
- Counters or statistical information
- Caching data or shared resources
- Constants or methods in utility classes
- Instance variables in the singleton pattern
Example
The following example defines an AppConfig class that contains three static variables: APP_NAME, APP_VERSION, and DATABASE_URL, used to store the application name, version, and database connection URL. These variables are all declared as final, indicating that they are immutable constants.
In the main() method, we print out the values of these static variables.
AppConfig.java file code:
The above example compiles and runs with the following result:
Application name: MyApp Application version: 1.0.0 Database URL: jdbc:mysql://localhost:3306/mydb
It can be seen that the global configuration information stored in these static variables can be used throughout the entire program and will not be modified. This example demonstrates another common application of static variables, through which we can conveniently store global configuration information, or implement other data that needs to be globally shared.
The following example defines a Counter class that contains a static variable count, used to record how many Counter objects have been created.
Whenever a new object is created, the constructor increments the counter by one. The static method getCount() is used to get the current counter value.
In the main() method, we create three Counter objects and print out the counter value.
Counter.java file code:
The above example compiles and runs with the following result:
目前为止创建的对象数: 3
It can be seen that the counter records that three objects were created. This example shows a simple application of static variables, through which we can easily count the number of object creations, or record other data that needs to be shared globally.
In this chapter, we learned about Java variable types. In the next chapter, we will introduce the use of Java modifiers.
Other extensions