Home > Java > Java Tutorial > body text

What is the difference between global variables and local variables in java?

青灯夜游
Release: 2019-12-27 15:48:15
Original
5607 people have browsed it

What is the difference between global variables and local variables in java?

Global variables are a type of programming terminology, derived from variables. Global variables can be created by an object function or anywhere in the program. Global variables can be referenced by all objects or functions in this program.

Local variables: Variables defined within a method (including the main() method) are local variables. All local variables are allocated space on the stack when the method is called. The system will not automatically assign values ​​to them, so local variables must be assigned initial values ​​before they can be used.

The difference between global variables and local variables:

1. Different scopes

Global variables have global scope. Global variables only need to be defined in one source file to apply to all source files. Of course, other source files that do not contain global variable definitions need to declare this global variable again using the extern keyword.

Local variables have only local scope. They are automatic objects (auto). They do not always exist during the running of the program, but only exist during the execution of the function. After a call to the function is executed, the variable is revoked. , the memory occupied by it is also reclaimed.

2. Different initial values ​​

Global variables = with initial values ​​

Local variables = no initial values ​​

3. Different declarations

Global variables = declaration of variables with the same name is not allowed in a class

Local variables = declaration of variables with the same name is not allowed in a method

(You can declare variables with the same name in different methods of the same type)

4. Different priorities

When two types of variables have the same name, the local variable has a higher finite level

(proximity principle)

Recommended learning: Java video tutorial

The above is the detailed content of What is the difference between global variables and local variables in java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!