The scope of variables and variables in Java

Source: Internet
Author: User
Tags variable scope

<title>About variables and the scope of variables in Java</title> About the variables in Java and the scope of the variables 0. The concept of variables

During a program run, the system can allocate a block of memory for the program to store various types of data. The memory units allocated by the system are identified with a marker, and the data in this memory unit can be changed. All called variables. The tag that defines the variable is the variable name, and the data that is loaded in the memory cell is the variable value. Once you define a block of memory with a variable, the program can use the variable name to represent the data in the memory. There are different types of variables depending on the type of data being stored.

1. Types of variables in Java


2. Note the range of valid values for variables

The system allocates different spatial sizes for different variable types, such as a double constant that occupies 8 bytes in memory, a variable of float to 4 bytes, and a byte type of 1 bytes.

byte b=129;//编译报错,129超出了byte类型的取值范围
float f=3.5;//编译报错,因为小数常量的默认类型为double型。double型在内存中占8个字节,而Java只为float的变量分配4个字节的空间,显然有问题
float f=3.5f;//编译通过
3. Conversions between basic data types

①. Automatic type conversion (implicit type conversion)
To implement an automatic type conversion, you need to meet two conditions: I. Two types are compatible with each other, and II. The range of destination types is greater than the source type.

byte b=3;
int x=b;//程序把b的结果自动转换成int型

②. Forcing type conversions (explicit type conversions)
When two types are incompatible with each other, or if the target type has a range of small source types, the automatic conversion is not possible, and you need to force the type conversion.

byte a;
int b;
a=(byte)b;

Cast the value of variable B of type int to a byte type, and then assign the value to variable a. At this point, the data type of the variable B itself does not change.

Cases:
Program list: Conversion.java

publicclass Conversion
{
public static void main(String[] args)
{
byte b;
int i=266;
b=(byte)i;
System.out.println("byte to int is"+" "+b);
}
}

The program output is as follows:

byteint10

Decimal 266→ binary 100001010
The byte type has a value range of -128~127, so it can only fetch 010, omit 0, so output 10
That is, using the target memory block to get the data in the source memory, how much can be set

4. The data type of an expression is automatically promoted

Let's look at an error program:
Program list: Test.java

class Test
{
public static void main(String[] args)
{
byte b=5;
b=(b-2);
System.out.println(b);
}
}

In this code, the value of 5-2 does not exceed the range of byte type, but the error

This is because when the expression evaluates, the value of the variable is automatically promoted to int, and the expression result is an int, and it must be cast to assign it to a byte variable.
Therefore, it should be changed to:

b=(byte)(b-2);

For automatic promotion of types, Java defines a number of type promotion rules that apply to an expression

    • All byte, short, and char value trophies are promoted to type int
    • If one operand is long, the result is a long type
    • If an operand is of type float, the result is a float type
    • If one operand is of type double, the result of the calculation is double type
      That is, byte, short, char→int→long→float→double.

The following is a demonstration of some types of Java automatic promotion rules:
Program list: Promote.java

 class Promote
{
Public static void main(string[] args)
{
byteb= -;
CharC=' A ';
Shorts=1024x768;
intI=50000;
floatf=5.67f;
DoubleD=. 1234;
Doubleresult= (f*b) + (I/C)-(d*s);
System.out.println ((f*b) +"+"+ (I/C) +"-"+ (d*s));
System.out.println ("result="+result);
}
}

Here's a look at the type of code line promotion:

double result=(f*b)+(i/c)-(d*s);

In the first subexpression f*b, variable B is promoted to float type, and the result of that subexpression is promoted to float type. Next, in the subexpression i/c, the variable c is promoted to the int type. The result of the subexpression is promoted to the int type.
Then the variable s in the subexpression d*s is promoted to a double type, and the result of the subexpression is promoted to a double type.
The last three result value types are float, int, double, respectively. The result of the float type plus the int type is the float type, then the float type minus the double type, and the last result of the expression is the double type.

Scope of the variable

Most programming languages provide the concept of "variable Scope" (scope). In C, C + +, Java, the middle part of a pair of braces is a block of code that determines the scope of the variables defined therein. A block of code consists of several statements, which must be enclosed in curly braces to form a compound statement, and multiple compound statements can be escaped in another pair of curly braces to form more complex compound statements.

{
int x=0;
{
int y=0;
y=y+1;
}
x=x+1;
}

The block of code determines the scope of the variable, and the scope determines the "visibility" of the variable and the "time of existence."
For example:
Program list: Testscope.java

public  class  testscope  
{
public static Span class= "Hljs-keyword" >void main (string[] args)
{
int x=12 ;
{
int q=96 ; //x and Q are available
System.out.println ( "x is" +x);
System.out.println ( "Q is" +q);
}
Q=x; /* error line, only x available, q out of scope range */
System.out.println ( "x is" +x);
}
}

Q as a variable defined in the inner block of code, only the statement after the definition of the variable in that block of code can use this variable, the Q=X statement has exceeded the scope of Q, so the compilation cannot pass.
Between the curly braces that define a variable's statement is the valid scope of the variable, but it cannot violate the principle that the variable is used before it is defined.

6. Initialization of local variables

A variable defined in a code block inside a function or function is called a local variable, and a local variable is created when a function or block of code is executed, and is destroyed when the function or block of code ends. Local variables must be initialized or assigned before a value operation is performed, or a compilation error occurs. For example:
Program list: Testvar.java

publicclass TestVar
{
public static void main(String[] args)
{
int x;//应改为int x=0;
x=x+1;//这个x由于没有初始化,编译报错
System.out.println("x is "+x);
}
}

The scope of variables and variables in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.