Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the java variable

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The content of this article mainly focuses on how to understand java variables. The content of the article is clear and well-organized. It is very suitable for beginners to learn and is worth reading. Interested friends can follow the editor to read together. I hope you can get something through this article!

Variable is a basic storage unit of Java program. Variables are defined by a combination of an identifier, a type, and an optional initial value. In addition, all variables have a scope that defines the visibility and lifetime of the variable. Let's discuss these elements of the variable.

1 declare a variable

In Java, all variables must be declared before they are used. The basic variable declaration method is as follows: type identifier [= value] [, identifier [= value].]

Type is one of the basic types of Java, or the names of classes and interface types (discussed later in part 1 of this book). The identifier (identifier) is the name of the variable, specifying an equal sign and a value to initialize the variable. Remember that the initialization expression must produce variables that are the same (or compatible) as the specified variable type. When multiple variables of the specified type are declared, the variables are separated by commas.

Here are a few examples of various variable declarations. Note that some include initialization.

Int a, b, c; / declares three ints, a, b, and c.int d = 3, e, f = 5; / / declares three more ints, initializing / / d and f.byte z = 22; / / initializes z.

Double pi = 3.14159; / / declares an approximation of pi.char x = "x"; / / the variable x has the value "x".

The identifier names you choose do not have anything to indicate their type. Many readers remember that FORTRAN presupposes that all identifiers from I to N are integers and that other identifiers are real. Java allows any legal identifier to have any type they declare.

2 dynamic initialization

Although the previous example only takes the literal quantity as its initial value, Java also allows any valid expression to initialize the variable dynamically when the variable is declared.

For example, the following short program calculates the oblique length of a right triangle given the length of its two right sides.

/ / Demonstrate dynamic initialization.

Class DynInit {

Public static void main (String args []) {

Double a = 3.0, b = 4.0

/ / c is dynamically initialized

Double c = Math.sqrt (a * a + b * b)

System.out.println ("Hypotenuse is" + c)

}

}

Here, three local variables are defined: a _ line _ b _ p _ c. The first two variables an and b are initialized to constants. However, the beveled edge c of a right triangle is initialized dynamically (using the Pythagorean theorem). The program uses another Java built-in method, sqrt (), which is a member of the Math class and calculates the square root of its parameters. The key point here is that initialization expressions can use any valid element, including method calls, other variables, or literals.

3 scope and lifetime of variables

So far, all the variables we have used have been declared after the method main (). However, Java allows variables to be declared in any block. As explained in Chapter 2, the block is included in a pair of curly braces. A block defines a scope. This way, every time you start a new block, you create a new scope. You may know from previous programming experience that a scope determines which objects are visible to other parts of the program, and it also determines the lifetime of those objects.

Most other computer languages define two main categories of scope: global and local. However, these traditional scopes are not suitable for Java's strict object-oriented model. Of course, it is possible to define a variable as a global variable, but this is an exception, not a rule. The two main scopes in Java are defined by classes and methods. Although the difference between the scope of a class and the scope of a method is somewhat artificial. Because the scope of a class has several unique features and attributes, and these features and attributes cannot be applied to the scope of a method definition, these differences are significant. Because of the difference, the scope of the class (and the variables defined in it) will be deferred to Chapter 6 when the class is discussed. So far, we will only consider the scope defined by the method or within a method.

The scope of a method definition begins with its opening brace. However, if the method has parameters, they are also included in the scope of the method. Parameters are further discussed in Chapter 5 of this book, so they can now be considered to have the same scope as other variables in the method.

As a general rule, variables defined in a scope are invisible (that is, accessible) to programs outside that scope. Therefore, when you define a variable in a scope, you localize the variable and protect it from unauthorized access and / or modification. In fact, scope rules provide the basis for encapsulation.

Scopes can be nested. For example, every time you create a block, you create a new nested scope. In this way, the outer scope contains the internal scope. This means that objects defined by the external scope are visible to programs in the internal scope. However, the reverse is wrong. Objects defined by the internal scope are not visible to the outside.

To understand the effects of nested scopes, consider the following procedure:

/ / Demonstrate block scope.

Class Scope {

Public static void main (String args []) {

Int x; / / known to all code within main

X = 10

If (x = = 10) {/ / start new scope

Int y = 20; / / known only to this block

/ / x and y both known here.

System.out.println ("x and y:" + x + "" + y)

X = y * 2

}

/ / y = 100; / / Error! Y not known here

/ / x is still known here.

System.out.println ("x is" + x)

}

}

As indicated in the comment, the variable x is defined at the beginning of the method main (), so it is visible to all subsequent code in main (). The variable y is defined in the if block. Because a block defines a scope, y is visible only to other code within its block. This is why the program line yquote 100; outside its block is commented out. If you remove the comment symbol in front of the line, there will be an error when compiling the program because the variable y is not visible outside its block. The variable x can be used in an if block because a program in a block (that is, a nested scope) can access variables defined in its enclosed scope.

Variables can be declared anywhere within the block, but they are valid only after they have been declared. Therefore, if you define a variable at the beginning of a method, it is available to all programs within that method. On the other hand, if you declare a variable at the end of a block, it is of no use because no program will access it. For example, the following section is invalid because the variable count cannot be used until it is defined.

/ / This fragment is wrong!

Count = 100; / / oops! Cannot use count before it is declared!

Int count

Another important thing to keep in mind is that variables are created within their scope and undone when they leave their scope.

This means that once a variable leaves its scope, its value will no longer be saved. Therefore, variables defined within a method will no longer hold their values between several calls to the method. Similarly, a variable defined within a block discards its value when it leaves the block. Therefore, the lifetime of a variable is limited to its scope.

If a declaration definition includes an initialization, the variable is reinitialized each time you enter the block in which it is declared. For example, consider this program:

/ / Demonstrate lifetime of a variable.

Class LifeTime {

Public static void main (String args []) {

Int x

For (x = 0; x < 3; x +) {

Int y =-1; / / y is initialized each time block is enteredSystem.out.println ("y is:" + y); / / this always prints-1y = 100scape system. Out.println ("y is now:" + y)

}

}

}

The output of the program is as follows:

Y is:-1

Y is now: 100

Y is:-1

Y is now: 100

Y is:-1

Y is now: 100

As you can see, every time you enter the internal for loop, y is re-initialized to-1. Even if it is subsequently assigned a value of 100, the value is discarded.

One last point: although blocks can be nested, you cannot rename variables declared in the internal scope with variables declared in the external scope. Java is different from C and C++ in this respect. The following example attempts to give two independent variables the same name. In Java, this is illegal. But in C _ bar +, it will be legal, and the two variables will be independent.

/ / This program will not compile

Class ScopeErr {

Public static void main (String args []) {

Int bar = 1

{/ / creates a new scope

Int bar = 2; / / Compile-time error-bar already defined!

}

}

}

Thank you for your reading. I believe you have some understanding of "how to understand java variables". Go ahead and practice it. If you want to know more about it, you can follow the website! The editor will continue to bring you better articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report