Java Learning to organize notes (c) data types

Source: Internet
Author: User
Tags mathematical functions

Data type:

The data type determines how much storage space the data occupies in memory and how it is stored. Each data type has its range of values, and the compiler allocates memory space for each variable or constant based on its data type.

The Java language data types can be divided into two categories: a simple data type (or basic data type), such as an integer type, a floating-point type, a character type and a Boolean type, and a reference type, such as an array type, class, interface, and so on.

I. Basic data types

There are 8 basic data types, byte (byte), short, Integer (int), long, character (char), float (float), double type (double), Boolean (bool), respectively.

1. Integer type:

Java uses 4 types of integers: Byet, short, int, and long, all of which are signed integers.

(An unsigned integer corresponding to a signed integer, the difference between converting a binary number to a decimal number is different.) The signed number takes the first digit of the binary as the symbol bit, and when the first number is 0 o'clock, corresponds to a positive integer of decimal, and when the first is 1 o'clock, it corresponds to a negative integer of decimal. unsigned integers convert all binary bits to positive integers when making a binary conversion. )

Note: Java does not support an unsigned integer that is just positive.

(1) byte type (byte): the smallest integer type. A signed 8-bit type with a range of -128~127. Variables of byte types are particularly useful when processing data streams from a network or file.

Declaring a byte variable: a byte variable name;

(2) Short integer: A signed 16-bit type with a range of -32768~32767. Because it is defined as high-byte precedence (known as the Big-endian format), it is probably the best type to use in Java.

Declare a short variable name;

(3) integer type (int): Most commonly used integer types. The signed 32-bit type, the number range is-2147 483 648~2147 483 647. Variables of type int are often used to control loops and subscript as arrays.

At any time, if an integer expression contains a byte, short, int, and integer constant. The type of all expressions is promoted (auto-converted) to integer until the calculation is performed.

Declaring integer variables: int variable name;

(4) Long: A signed 64-bit type, which is useful for those integral types that are not sufficient to hold the required values. The range of long integers is quite large.

Declare a long variable name;

2. Float Type:

Java uses two types of floating-point numbers: float and double. The double type is twice times the storage space of the float type, so the double type is also known as dual precision, and the float type is also called single precision. Floating-point data is required when the value of a data or expression has a precision requirement.

(1) Single-precision float (float): Refers to single-precision values (single-precision) that occupy 32-bit storage space. Single precision is faster than double precision on some processors and occupies only double-precision space, but it becomes imprecise when the value is large or small. Single-precision floating-point variables are useful when the fractional part is required and the accuracy requirement is not high.

Declaration single-precision floating-point variable: float variable name;

(2) Double-precision floating-point type (double): consumes 64 bits of storage space. All mathematical functions beyond human experience, such as sin (), cos (), and sqrt (), return double-precision values. Double is the best choice when it is necessary to keep the calculation of the iteration back multiple times accurate, or when the operand is of a large number.

Declaring a double-precision floating-point variable: double variable name;

3. Character type (char):

In a computer, all data is stored and used in binary notation (because the computer uses high and low levels to represent 1 and 0). The process of mapping a character to its binary form is called encoding (Encoding).

In order to be able to communicate with each other without causing confusion, you must use the same encoding rules or coding methods. The two most widely used encoding methods are uniform code (UNICODE) and US standard Information Interchange Code (ASCII) codes.

In Java, character data is defined with the Char keyword, which represents characters using Unicode codes and 16-bit data to represent character sets.

4. Boolean Type (Boolean):

A simple type in Java that represents a logical value. Its value can only be true (true) or False (false) One of these two values. It is the return type of all relational operations such as A<b. Boolean types are also required for conditional expressions that manage control statements such as if, for.

Second, define constants

In the course of a program's operation, the amount of its value cannot be changed is called a constant. Constants must be declared and assigned in the same statement, andfinal is the Java keyword that declares the constants .

In the program, the constant name of all letters preferably in uppercase, words and words can be separated by an underscore.

Constants commonly used in Java are Boolean constants, integer constants, floating-point constants, character constants, and string constants.

1. Boolean Constants:

A Boolean constant is used to represent a value of one of two logical states: true (True) or False (false). Unlike the C + + language, the Java language specifies that a Boolean type cannot be considered an integer value.

Note: In the Java language, the value of the true constant is not equal to the value of the 1,false constant that is not equal to 0, they can only be assigned to a defined Boolean variable, or used in a Boolean operator expression.

2. Integral type constants:

The value of any integer is an integer constant. Integer constants can be used to assign values to integer variables. There are 3 representations of integer constants:

(1) Decimal integral type constant: such as 1,25,-37.

(2) Octal integer constants: In the Java language, integers that begin with 0 represent octal integer constants, such as 010 for decimal 8, and 015 for decimal-13.

(3) Hexadecimal integer constants: In the Java language, integer constants that begin with 0x or 0X represent hexadecimal integer constants, such as 0x10 for Decimal, and -0x15 for decimal-21.

In the Java language, the default type of an shaping constant is an int value, represented by 4 bytes. When the value of an integral constant is assigned to a variable of type byte or short, no error occurs if the value of the constant does not exceed the range of the corresponding type. Therefore, integer constants can always be assigned to a long variable. However, if you want to represent a long type of constant, be specific, that is, by adding an uppercase or lowercase L to the following constant, such as 1234567L.

3. Floating-point constants:

A floating-point constant is a numeric constant that can have a decimal point. Depending on the length of memory used, 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 after the value, and D and D after the value if you want to represent a double-precision constant.

Note: floating-point constants in Java are double-precision by default.

The default double type consumes 64 bits of storage space, while the exact lower floating-point type requires only 32 bits.

4. Character constants:

Java uses the Unicode character set to represent characters. Java characters are 16-bit values that can be converted to integers and can perform integer operations like plus (+) or minus (-).

In the Java language, there are two types of character constants in the following ways:

(1) Ordinary characters: a character enclosed in single quotation marks, such as ' a ', ' 0 ', ' $ ', etc. cannot be written as ' AB ' or ' 12 '.

Note: Single quotes are only bounds, and character constants can only be one character, excluding single quotes. ' A ' and ' a ' denote different character constants.

(2) escape character: A sequence of characters beginning with the character \. This is a "control character" that cannot be displayed on the screen, nor can it be represented in a general form by a character in a program, but only in such a special form.

escape character and its function
Escape character Name Unicode Output results
\b Backspace key \u0008 Backs up the current position by one character
\ t TAB key \u0009 Move the current position to the next tab position
\ n Line break symbol \u0009a Move the current position to the beginning of the next line
\f Page change \u000c Move the current position to the beginning of the next page
\ r Enter \u000d Move the current position to the beginning of the bank
\\ Back slash \u005c Output this character
\‘ Single quotation marks \u0027 Output this character
\" Double quotes \u0022 Output this character

5. String constants:

A sequence of characters enclosed in double quotation marks ("") in the Java language represents a string. The string can contain an escape character, and the double quotation marks of the start and end of the flag string must be on the same line.

You can use the Join operator (+) to concatenate two or more string constants together to form a new string, such as "Welcome" + "to-China", which results in the equivalent of "Welcome to China".

NOTE: "ABC" cannot be incorrectly written as ' abc '. Only one character can be included in a single quotation mark, and a double quotation mark may contain a string. In addition, ' a ' and ' a ' represent two different quantities, the former is a character constant, and the latter is a string constant.

In most computer languages, such as C + +, strings are implemented as arrays of characters. In Java, however, strings are actually object types.

Iii. defining variables and their scopes

A variable is a basic storage unit of a Java program that represents a small amount of space in memory that is used to store the data that will be in the program. In memory can have a lot of such small space, in order to distinguish, for them to different names, the name is called variable name, usually referred to as the variable. They are called variables because their values can be changed in the execution of the program.

Variable names follow the definition rules for identifiers, each of which has its own specific type, and the compiler can allocate the appropriate storage space for variables based on the data type of the variable.

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

1. Define variables:

In Java, each variable must be defined before it is used, that is, to follow the principle of first-defined use.

To define the syntax for a variable:

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

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

The variable name is the name used to identify the variable, and you can specify an equal sign and a value to initialize the variable.

An initialization expression must produce the same (or compatible) variable as the specified variable type.

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

Example:

int count;                    // declare count as an integer variable Double radius = 2.0;        // declares that radius is a double variable and assigns an initial value of 2.0 char ch = ' A ';             // declare ch as a character type variable and assign the initial value to the character ' A '

2. Initialization of variables:

Variables usually have an initial value. In Java, you can initialize variables at the same time as they are defined, and also allow any valid expression to be used for dynamic initialization of variable declarations.

An initialization expression can use any valid element, including a method call, other variable, or literal.

3. Scope and lifetime of variables:

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

Like the C language, Java uses braces to make a statement block of statements, where the scope of the variable is the block of statements that define its statement, and once the execution of the program leaves the block of statements, the variable becomes meaningless and cannot be reused.

The life cycle of a variable is the process of starting from a variable that is created and allocating memory space to that variable and destroying and erasing the occupied memory space. The scope of a variable determines the life cycle of the variable.

Java allows you to define variables in any program block.

Depending on the scope, variables can be divided into the following types:

(1) member variable: declared in a class, its scope is the entire class.

(2) Local variables: internally declared within a method or within a code block of a method. If declared within a method, its scope is the entire method, and if it is declared inside a code block of a method, its scope is the block of code.

(3) Method parameter: The method or the parameter of the construction method, its scope is the whole method or the construction method.

(4) Exception handling parameters: Exception handling parameters and method parameters are very similar, the difference is that the former is to pass parameters to the exception processing code block, and the latter is to pass parameters to the method or construction method. An exception handling parameter is an exception parameter "E" in a catch (Exception e) statement whose scope is followed by a block of code following the catch (Exception e) statement.

(as a general rule, variables defined in a scope are not visible (that is, accessed) for programs that are outside the scope.) Therefore, when a variable is defined in a scope, the variable should be localized and protected from unauthorized access and/or modification. In fact, scope rules provide the basis for encapsulation. )

scopes can be nested. For example, a new nested scope is created each time a block is created. In this way, the outer scope contains the internal scope. This means that the objects defined by the outer scope are visible to the programs in the internal scope. However, the reverse is wrong, and an internal scope-defined object is not visible to the outside.

Example:

classscope{ Public Static voidMain (string[] args) {intX//defines the local variable x, which is valid throughout the main () methodx = 10; if(x==10) {//start a new scope            inty = 20;//defines the local variable y, which is valid in the current statement blockSystem.out.println ("X and y:" +x+ "" +y);//both x and Y are valid herex = y*2; }        //y=100; //error, beyond the scope of Yx=15;//right, X is still valid hereSystem.out.println ("x is" +x); }}    

Also, when a variable is created at its scope and is withdrawn from its scope, it means that once a variable leaves its scope, its value is no longer saved. Therefore, the lifetime of a variable is scoped to its scope. If a variable definition includes an initialization, the variable is reinitialized each time it enters the block that defines it.

Although a block can be nested, you cannot duplicate a variable declared by an inner scope with its outer scope. In this regard, Java differs from C and C + +.

Java Learning to organize notes (c) data types

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.