Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Variable Types

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:

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:

}

}

}

}

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, ...) {
    // 方法体
}

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.

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;

Explanation:

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)

The declaration syntax for member variables is:

accessModifier type variableName;

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.

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:

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.