Java Variable Types
In the Java language, all variables must be declared before use.
The basic format for declaring a variable is as follows:
type
identifier
[
=
value
]
[
,
identifier
[
=
value
]
...
]
;
Format description:
- type -- The data type.
- identifier -- The variable name; you can use commas to separate multiple variables of the same type.
Below are some examples of variable declarations. Note that some include initialization.
int
a
,
b
,
c
;
//
Declare three int integers: a, b, c
int
d
=
3
,
e
=
4
,
f
=
5
;
//
Declare three integers and assign initial values
byte
z
=
22
;
//
Declare and initialize z
String
s
=
"
runoob
"
;
//
Declare and initialize the string s
double
pi
=
3
.14159
;
//
Declares the double-precision floating-point variable pi
char
x
=
'
x
'
;
//
Declares the variable x with the value of the character 'x'.
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 after the method, constructor, or block in which they are declared finishes executing. Local variables must be initialized when declared, otherwise a compilation error occurs.
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 has its own copy. If not explicitly initialized, instance variables are assigned default values (0 for numeric types, false for boolean, null for object references).
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, and all instances of the class share the same class variable value. Class variables are initialized when the class is loaded, and only once.
public class ExampleClass { static int classVar; // 类变量
}
-
Parameters:Parameters are variables in a method or constructor declaration, used to receive values passed when the method or constructor is called. The scope of a parameter variable is limited to the inside of the method.
public void exampleMethod(int parameterVar) { // Parameter variables // ...
}
The following example defines a RunoobTest class containing a member variable instanceVar and a static variable staticVar.
The method() method defines a parameter variable paramVar and a local variable localVar. 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 the values of these variables.
In the main() method, we create a RunoobTest object and call its method() method.
Example
public
class
RunoobTest
{
//
Member Variable
private
int
instanceVar
;
//
Static variable
private
static
int
staticVar
;
public
void
method
(
int
paramVar
)
{
//
local variables
int
localVar
=
10
;
//
Using variables
instanceVar
=
localVar
;
staticVar
=
paramVar
;
System
.
out
.
println
(
"
Member variable:
"
instanceVar
)
;
System
.
out
.
println
(
"
Static variable:
"
staticVar
)
;
System
.
out
.
println
(
"
Parameter variable:
"
paramVar
)
;
System
.
out
.
println
(
"
Local variable:
"
localVar
)
;
}
public
static
void
main
(
String
[
]
args
)
{
RunoobTest
v
=
new
RunoobTest
(
)
;
v
.
method
(
20
)
;
}
}
Running the above code produces the following output:
成员变量: 10
静态变量: 20
参数变量: 20
局部变量: 10
Java Parameter Variables
Parameter variables in Java are variables declared in a method or constructor, 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 of a Java method is as follows:
accessModifier returnType methodName(parameterType parameterName1, parameterType parameterName2, ...) {
// 方法体
}
- parameterType -- Indicates the type of the parameter variable.
- parameterName -- Indicates the name of the parameter variable.
When calling a method, we must pass values for the parameter variables; these values can be constants, variables, or expressions.
There are two ways to pass the values of method parameter variables:Pass by valueandPass by reference.
-
Pass by value:When a method is called, a copy of the actual argument's value is passed. When the parameter variable is assigned a new value, only the copy is modified, not the original value. In Java, primitive data types all pass parameter values by value.
-
Pass by reference:When a method is called, the reference (i.e., memory address) of the actual argument is passed. When the parameter variable is assigned a new value, the content of the original value is modified. In Java, object types pass parameter values by reference.
Here is a simple example demonstrating the use of method parameter variables:
Example
public
class
RunoobTest
{
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
;
}
}
Running the above code produces the following output:
a = 10, b = 20
Java Local Variables
Java local variables are variables declared inside a method, constructor, or statement block, and their scope is limited to the block of code in which they are declared.
The declaration syntax for local variables is:
type variableName;
- type -- Indicates the type of the variable.
- variableName -- Indicates the name of the variable.
Explanation:
-
Scope: The scope of a local variable is limited to the method, constructor, or block in which it is declared. Once execution leaves this scope, the local variable is no longer accessible.
-
Lifetime: The lifetime of a local variable begins when it is declared and ends when the method, constructor, or block finishes executing. After that, the local variable is garbage collected.
-
Initialization: Local variables must be initialized before use. If not initialized, the compiler reports an error because Java does not provide default values for local variables.
-
Declaration: The declaration of a local variable must occur at the beginning of the method or block. The declaration 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 direct, or through a method call or expression.
-
Limitation: Local variables cannot be accessed directly by other methods of the class; they are private to the method or block that declares them.
-
Memory management: Local variables are stored on the stack of the Java Virtual Machine (JVM), unlike instance variables or objects stored on the heap.
-
Garbage Collection: Because the lifetime of a local variable is strictly limited to the execution of the method or block, it is no longer referenced after the method or block finishes, so the JVM's garbage collector automatically reclaims the memory it occupies.
-
Reuse: The name of a local variable can be reused in different methods or blocks because its scope is local and does not cause naming conflicts.
-
Parameters and Return Values: A method's parameters can be regarded as a special kind of local variable; they are initialized when the method is called and their lifetime ends when the method returns.
Example
Here is a simple example demonstrating the use of local variables:
Example
public
class
LocalVariablesExample
{
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 reports an error
// int c;
// System.out.println("c = " + c);
}
}
In the above example we declare and initialize two local variables a and b, then print their values. Note that if a local variable is not initialized before use, the compiler reports an error.
In the following example, age is a local variable defined in the pupAge() method, and its scope is limited to this method:
package
com
.
runoob
.
test
;
public
class
Test
{
public
void
pupAge
(
)
{
int
age
=
0
;
age
=
age
7
;
System
.
out
.
println
(
"
The puppy's age is:
"
age
)
;
}
public
static
void
main
(
String
[
]
args
)
{
Test
test
=
new
Test
(
)
;
test
.
pupAge
(
)
;
}
}
The compilation and execution results of the above example are as follows:
小狗的年龄是: 7
In the following example, the age variable is not initialized, so a compilation error occurs:
package
com
.
runoob
.
test
;
public
class
Test
{
public
void
pupAge
(
)
{
int
age
;
age
=
age
7
;
System
.
out
.
println
(
"
The puppy's age is :
"
age
)
;
}
public
static
void
main
(
String
[
]
args
)
{
Test
test
=
new
Test
(
)
;
test
.
pupAge
(
)
;
}
}
The compilation and execution results of the above example are 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.
- After 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 value of a member variable should be referenced by at least one method, constructor, or block so that the outside can obtain instance variable information through these means.
- Member variables can be declared before or after use.
- Access modifiers can modify member variables.
- Member variables are visible to methods, constructors, or blocks in the class. Generally, 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 of numeric variables is 0, of boolean variables is false, and of reference type variables is null. The value of a variable can be specified at declaration or in a constructor;
- Member variables can be accessed directly by variable name. However, in static methods and other classes, the fully qualified name should be used: 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 explicitly specified access modifier).
- type -- Indicates the type of the variable.
- variableName -- Indicates the name of the variable.
Unlike local variables, member variable values are allocated when the object is created; even if not initialized, they are assigned default values, for example the default value of an int variable is 0 and of a boolean variable is 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 assigned default values. Member variables can be initialized in a constructor or other methods, or accessed and set through an object or class name.
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 static member variables through the class name.
Example
public
class
RunoobTest
{
private
int
a
;
// Private member variable a
public
String
b
=
"Hello"
;
// Public member variable b
public
static
void
main
(
String
[
]
args
)
{
RunoobTest obj
=
new
RunoobTest
(
)
;
// Create an 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 compilation and execution results of the above example are as follows:
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:
import
java
.
io
.*;
public
class
Employee
{
//
This member variable is visible to subclasses
public
String
name
;
//
Private variable, visible only within this class
private
double
salary
;
//
Assign a value to name in the constructor
public
Employee
(
String
empName
)
{
name
=
empName
;
}
//
Set the value of salary
public
void
setSalary
(
double
empSal
)
{
salary
=
empSal
;
}
//
Print information
public
void
printEmp
(
)
{
System
.
out
.
println
(
"
Name :
"
name
)
;
System
.
out
.
println
(
"
Salary :
"
salary
)
;
}
public
static
void
main
(
String
[
]
args
)
{
Employee
empOne
=
new
Employee
(
"
RUNOOB
"
)
;
empOne
.
setSalary
(
1000
.0
)
;
empOne
.
printEmp
(
)
;
}
}
The compilation and execution results of the above example are as follows:
$ javac Employee.java
$ java Employee
名字 : RUNOOB
薪水 : 1000.0
Class variables (static variables)
A static variable in Java is a variable defined in a class that is related to the class rather than to instances, i.e., no matter how many instances of the class 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 run.
Definition
Static variables are defined by modifying a variable with the static keyword in a class, commonly also called class variables.
In the following example we define a static variable count , with an initial value of 0:
Example
public
class
MyClass
{
public
static
int
count
=
0
;
// Other member variables and methods
}
Access Method
Because static variables are related to the class, they can be accessed through the class name or through an instance name.
Example
MyClass.
count
=
10
;
// Access through the class name
MyClass obj
=
new
MyClass
(
)
;
obj.
count
=
20
;
// Access through the instance name
Lifetime
The lifetime of a static variable is as long as the lifetime of the program, i.e., it is created when the class is loaded, exists throughout the program run, and is destroyed only when the program ends. Therefore, static variables can be used to store data needed by the whole program, such as configuration information and global variables.
Initialization Timing
Static variables are initialized when the class is loaded, and their initialization order depends on the definition order.
If one static variable depends on another, it must be defined afterward.
Example
public
class
MyClass
{
public
static
int
count1
=
0
;
public
static
int
count2
=
count1
1
;
// Other member variables and methods
}
In the example above, count1 must be initialized before count2, otherwise a compilation error occurs.
Differences Between Constants and Static Variables
Constants are also related to the class, but they are variables modified with the final keyword and cannot be changed once assigned. Unlike static variables, a constant's value is determined at compile time, while a static variable's value can change at runtime. In addition, constants are usually used to store fixed values such as mathematical constants and configuration information, while static variables are usually used to store mutable data such as counters and global state.
In short, static variables are class-related variables with uniqueness and sharing, and can be used to store data needed by the whole program, but you need to pay attention to initialization timing and the difference from constants.
Access Modifiers for Static Variables
The access modifier of a static variable can be public, protected, private, or the default access modifier (i.e., no access modifier written).
Note that the access permissions of static variables differ from instance variables because static variables are related to 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 simultaneously, thread safety must be considered.
There is only one copy of a static variable 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 it. This may cause concurrent access problems because multiple threads may modify the static variable at the same time, leading to uncertain results or data consistency issues.
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 static variable values can be read and modified correctly in a multithreaded environment.
Naming Conventions for Static Variables
The naming conventions for static variables (also called class variables) usually follow camel case, and often use all uppercase letters with words separated by underscores, and should be explicitly marked with the static keyword.
-
Use camel case: Static variable names should use camel case, i.e., the first letter lowercase and the first letter of each subsequent word uppercase. For example:
myStaticVariable. -
All uppercase letters: Static variables usually use all uppercase letters with words separated by underscores. This is called "Upper Snake Case". For example:
MY_STATIC_VARIABLE. -
Descriptive: Variable names should be meaningful and clearly express the variable's purpose. Avoid single characters or abbreviations without clear meaning.
-
Avoid abbreviations: Try to avoid abbreviations to improve code readability. If abbreviations are necessary, ensure they are widely understood and explain them in comments.
Example
public
class
MyClass
{
// Use camel case
public
static
int
myStaticVariable
;
// Use upper snake case
public
static
final
int
MAX_SIZE
=
100
;
// Avoid abbreviations
public
static
final
String
employeeName
;
// Descriptive variable names
public
static
double
defaultInterestRate
;
}
Use Cases for Static Variables
Static variables are typically used in the following scenarios:
- Storing global state or configuration information
- Counters or statistics
- Cached data or shared resources
- Constants or methods of utility classes
- Instance variables in the singleton pattern
Example
The following example defines an AppConfig class containing three static variables APP_NAME, APP_VERSION, and DATABASE_URL, used to store the application's name, version, and database connection URL. These variables are all declared final, indicating that they are unmodifiable constants.
In the main() method, we print the values of these static variables.
AppConfig.java file code:
public
class
AppConfig
{
public
static
final
String
APP_NAME
=
"
MyApp
"
;
public
static
final
String
APP_VERSION
=
"
1.0.0
"
;
public
static
final
String
DATABASE_URL
=
"
jdbc:mysql://localhost:3306/mydb
"
;
public
static
void
main
(
String
[
]
args
)
{
System
.
out
.
println
(
"
Application name:
"
AppConfig
.
APP_NAME
)
;
System
.
out
.
println
(
"
Application version:
"
AppConfig
.
APP_VERSION
)
;
System
.
out
.
println
(
"
Database URL:
"
AppConfig
.
DATABASE_URL
)
;
}
}
The compilation and execution results of the above example are as follows:
Application name: MyApp
Application version: 1.0.0
Database URL: jdbc:mysql://localhost:3306/mydb
As you can see, the global configuration information stored in these static variables can be used throughout the program and will not be modified. This example shows another common use of static variables, through which we can conveniently store global configuration information or implement other data that needs to be shared globally.
The following example defines a Counter class containing a static variable count, used to record how many Counter objects have been created.
Each time a new object is created, the constructor increments the counter by one. The static method getCount() is used to obtain the current counter value.
In the main() method, we create three Counter objects and print the counter value.
Counter.java file code:
public
class
Counter
{
private
static
int
count
=
0
;
public
Counter
(
)
{
count
++;
}
public
static
int
getCount
(
)
{
return
count
;
}
public
static
void
main
(
String
[
]
args
)
{
Counter
c1
=
new
Counter
(
)
;
Counter
c2
=
new
Counter
(
)
;
Counter
c3
=
new
Counter
(
)
;
System
.
out
.
println
(
"
Number of objects created so far:
"
Counter
.
getCount
(
)
)
;
}
}
The compilation and execution results of the above example are as follows:
目前为止创建的对象数: 3
As you can see, the counter records that three objects have been created. This example shows a simple use of static variables, through which we can conveniently count 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.