Java Study Notes (3) data types, java Data Types

Source: Internet
Author: User
Tags mathematical functions

Java Study Notes (3) data types, java Data Types

Data Type:

The data type determines the storage space occupied by the data in the memory and the storage method. Each data type has its value range. The Compiler allocates memory space for each variable or constant data type.

Java data types can be classified into two types: simple data type (or basic data type), such as integer, floating point, numeric, and Boolean; the other is the reference type, such as the array type, class, interface, etc.

I. Basic Data Types

8 basic data types: byte, short, int, long, char, float) double and boolean ).

1. Integer type:

Java uses four types of integers: byet, short, int, and long. They are all signed integers.

(An unsigned integer corresponds to an unsigned integer. The difference between the two is that the conversion of binary numbers into decimal numbers is different. The number of symbols takes the first digit of the binary as the symbol bit. When the first digit is 0, it corresponds to a positive integer in decimal format. When the first digit is 1, it corresponds to a negative integer in decimal format. An unsigned integer converts all bits in binary to a positive integer in the hexadecimal notation .)

Note: Java does not support only positive unsigned integers.

(1) byte: The smallest integer. The signed 8-bit type. The value range is-128 ~ 127. Byte variables are particularly useful when processing data streams from networks or files.

Declare the byte variable name;

(2) short: A signed 16-bit type. The value range is-32768 ~ 32767. Because it is defined as a high byte priority (known as the big-endian format), it may be the best type used in Java.

Declare short integer variable: short variable name;

(3) INTEGER (int): The most common Integer type. The signed 32-bit type. The value range is-2147, 483, and 648 ~ 2147 483 647. Int type variables are usually used to control loops and serve as the subscript of arrays.

At any time, if an integer expression contains byte, short, int, and Integer constants. Before calculation, the types of all expressions are upgraded (automatically converted) to integers.

Declare an integer variable: int variable name;

(4) long integer (long): A signed 64-bit type. It is useful for integer types that are insufficient to save the required values. The range of long integers is quite large.

Declare long integer variable: long variable name;

2. floating point:

Java uses two types of floating point numbers: float and double. The double type has twice the storage space of the float type, so the double type is also called double precision, and the float type is also called single precision. When the values of data or expressions have precision requirements, floating point data is required.

(1) float: the Single-Precision value that occupies 32-bit storage space ). Single precision is faster than dual precision in some processors and only takes up space for dual precision. However, when the value is very large or small, it will become inaccurate. A single-precision floating-point variable is useful when the fractional part is required and the precision requirement is not high.

Declare a single-precision floating point variable: float variable name;

(2) double: occupies 64-bit storage space. All mathematical functions that exceed human experience, such as sin (), cos (), and sqrt (), return double-precision values. Double-precision is the best choice when you need to maintain the accuracy of Multiple Return iterations or when there are numbers with large operation values.

Declare double-precision floating-point variables: double variable name;

3. character type (char ):

In a computer, all data is stored and computed in Binary Notation (because the computer uses a high level and a low level to represent 1 and 0 ). The process of ing a character into its binary form is called Encoding ).

In order to achieve mutual communication without confusion, the same encoding rules or encoding method must be used. Currently, the two most widely used encoding methods are Unicode and American standard information interchange code (ASCII.

In Java, character data is defined by the char keyword, Unicode code is used to represent characters, and 16-bit data is used to represent character sets.

4. boolean ):

Java represents a simple type of logical values. The value can only be one of the true or false values. It is the return type of all relational operations such as a <B. Boolean is also required for conditional expressions that manage control statements such as if and.

 

Ii. Define Constants

A constant is a constant that cannot change the value of a program. Constants must be declared and assigned values in the same statement,Final is the Java keyword for declaring constants..

It is best to use uppercase letters for all constant names in the program. Words and words can be separated by underscores.

Common constants in Java include Boolean constants, Integer constants, floating-point constants, character constants, and string constants.

1. boolean constants:

Boolean constants are used to indicate values of one of the two logical states: true or false ). Unlike C/C ++, the Java language stipulates that boolean values cannot be regarded as integer values.

Note: in Java, values of true constants are not equal to 1, and values of false constants are not equal to 0. They can only be assigned to defined Boolean variables, or use it in a Boolean expression.

2. Integer constants:

The value of any integer is an integer constant. An integer constant can be used to assign values to an integer variable. There are three forms of Integer constants:

(1) decimal Integer constants: such as and-37.

(2) octal constants: in Java, integers starting with 0 represent octal constants. For example, 010 represents 8 in decimal format and-015 represents-13 in decimal format.

(3) hexadecimal integer constant: in Java, an integer constant starting with 0x or 0X represents a hexadecimal integer constant, for example, 0x10 represents a decimal 16, -0X15 indicates-21 in decimal format.

In Java, the default type of an integer constant is int, which is expressed in four bytes. When the value of an integer constant is assigned to a byte or short type variable, no error is generated if the value of the constant does not exceed the range of the corresponding type. Therefore, an integer constant can always be assigned to a long variable. However, if you want to represent a long type constant, you must specify it by adding an uppercase or lowercase L after the constant, such as 1234567L.

3. Floating Point constants:

Floating-point constants are numeric constants with decimal points. According to the memory length, it can be divided into general floating point constants and Double Precision constants. If you want to represent a general floating-point constant, you can add f or F to the value. If you want to represent a double-precision constant, you can add d and D to the value.

Note: Float constants in Java are double precision by default.

The default double-precision type occupies 64-bit storage space, while the precise floating-point type is only 32-bit.

4. character constants:

Java uses the Unicode Character Set to represent characters. The Java character is a 16-bit value, which can be converted to an integer and can be used for integer operations such as addition (+) or subtraction.

In Java, there are two types of character constants:

(1) common characters: A character enclosed in single quotes, such as 'A', '0', and '$. It cannot be 'AB' or '12 '.

Note: single quotes are only delimiters. character constants can only be one character, excluding single quotes. 'A' and 'A' indicate different character constants.

(2) Escape Character: a sequence of characters starting. This is a kind of "Control Character" that cannot be displayed on the screen. It cannot be expressed by a common character in the program. It can only be expressed in this special form.

Escape characters and their functions
Escape characters Name Unicode Output result
\ B Return key \ U0008 Returns a character from the current position.
\ T Tab key \ U0009 Move the current position to the next Tab
\ N Line feed symbol \ U0009A Move the current position to the beginning of the next line
\ F Form feed \ U000C Move the current position to the beginning of the next page
\ R Enter key \ U000D Move the current position to the beginning of the line
\\ Backslash \ U005C Output this character
\' Single quotes \ U0027 Output this character
\" Double quotation marks \ U0022 Output this character

 

 

5. string constants:

In Java, character sequences enclosed by double quotation marks ("") are used to represent strings. A string can contain escape characters, which indicate that the double quotation marks starting and ending must be in the same line.

You can use the join operator (+) to connect two or more string constants to form a new string, for example, the result of "Welcome" + "to China" is equivalent to "Welcome to China ".

Note: you cannot mistakenly write "ABC" as 'abc '. A single quotation mark can contain only one character, while a double quotation mark can contain one character string. In addition, 'A' and "A" indicate two different quantities. The former is A character constant, and the latter is A String constant.

In most computer languages such as C/C ++, strings are implemented as character arrays. However, in Java, strings are actually object types.

 

3. Define variables and their scopes

A variable is a basic storage unit of a Java program. It represents a small space in the memory and is used to store the data used in the program. There can be many such small pieces of space in the memory. to distinguish them, give them different names. This name is called the variable name, usually referred to as the variable. Variables are called variables because their values can be changed during program execution.

Variable names follow the definition rules of identifiers. Each variable has its own specific type. The compiler can allocate suitable storage space for the variable based on its data type.

All variables have a scope that defines the visibility and survival of variables.

1. Define variables:

In Java, each variable must be defined before use, that is, it must follow the principle of first definition and then use.

Syntax for defining variables:

 

Data type variable name [= initial value] [, variable name [= initial value]…];

 

The data type can be one of the basic types of Java, or the name of the class and interface type.

A variable name is the name used to identify the variable. You can specify an equal sign and a value to initialize the variable.

The initialization expression must generate a variable of the same (or compatible) type as the specified variable.

When declaring multiple variables of the specified type, use commas to separate the variables.

Example:

Int count; // declare count as an integer Variable double radius = 2.0; // declare radius as A double variable and assign the initial value 2.0 char ch = 'a '; // declare the ch variable as A character type and assign the initial value as 'A'

2. Variable initialization:

Variables usually have initial values. In Java, You can initialize a variable while defining it, or use any valid expression to dynamically initialize the variable during variable declaration.

The initialization expression can use any valid element, including method call, other variables, or literal.

3. Scope and lifetime of variables:

In Java, each variable has a certain life cycle and effective range. The scope of a variable is the valid range of the variable. only within this range can the program code access it.

Similar to the C language, Java uses braces to make several statements into statement blocks. The scope of the variables is the block where the statements are defined. Once the execution of the program leaves the block, variables become meaningless and cannot be used any more.

The life cycle of a variable starts when a variable is created and allocated with memory space, and ends with the variable and destroys and clears the occupied memory space. The scope of the variable determines the lifecycle of the variable.

Java allows variables to be defined in any program block.

Variables can be divided into the following types based on different scopes:

(1) member variable: declares in the class that its scope is the entire class.

(2) local variables: Internal declarations within a method or a code block of a method. If it is declared inside a method, its scope is the whole method; if it is declared inside a code block of a method, its scope is the code block.

(3) method parameters: parameters of a method or constructor. Its scope is the whole method or constructor.

(4) exception handling parameters: the exception handling parameters are similar to the method parameters. The difference is that the former is to pass the parameters to the exception handling code block, and the latter is to pass the parameters to the method or constructor. The Exception handling parameter refers to the Exception parameter "e" in the catch (Exception e) statement. Its scope is the code block that follows the catch (Exception e) Statement.

(As a general rule, variables defined in a scope are invisible (ACCESS) to programs outside the scope. Therefore, when defining a variable in a scope, the variable should be localized and protected from unauthorized access and/or modification. In fact, the scope rules provide the foundation for encapsulation .)

The scope can be nested. For example, each time a program block is created, a new nested scope is created. In this way, the external scope includes the internal scope. This means that the objects defined in the external scope are visible to the programs in the internal scope. However, the opposite is false. The objects defined in the internal scope are invisible to the outside.

Example:

Class Scope {public static void main (String [] args) {int x; // defines the local variable x, which is valid for x = 10 in the entire main () method; if (x = 10) {// start a new scope int y = 20; // defines the local variable y, which is effective in the current statement block. out. println ("x and y:" + x + "" + y); // here both x and y are valid x = y * 2;} // y = 100; // error. x = 15 is out of the range of y. // correct. x is still valid here. out. println ("x is" + x );}}

 

Also, when a variable is created in its scope and removed from its scope, it means that once a variable leaves its scope, its value will no longer be saved. Therefore, the lifetime of a variable is limited to its scope. If a variable definition includes an initialization, the variable will be reinitialized every time it enters the program block that defines it.

Although the program block can be nested, the variables declared in the internal scope cannot be renamed with the variables declared in the external scope. Java is different from C and C ++.

Related Article

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.