JAVA basics 2: variables and Data Types

Source: Internet
Author: User

JAVA basics 2: variables and Data Types

 

This article mainly introduces the basic data types in Java and how to correctly use them in programs.

1. Variables

A computer processes data. A variable is used to store the processed data. It is called a variable because you can change the stored value. More specifically, a variable points to an address that stores a specific type value. In other words, a variable has a name, type, and value. A variable has a name, such as radius, area, age, and height. The name of each variable is unique and can be used to set and obtain the value of the variable.

A variable has a type. The following is a Java column:

  • Int: an integer such as 123 and-456
  • Double: Indicates floating point numbers such as 3.1416,-55.66, 1.2e3, and-4.5E-6.
  • String: indicates text such as "Hello" and "Good Morning! ", Text is usually embedded in double quotation marks
  • Char: indicates a single character, such as 'A' and '8'. a single character is usually embedded in single quotes.

    A variable stores values of a specific type. Special attention should be paid to the variable type in programming. For example, an int variable stores an integer of 123, but cannot store a floating point number of 12.34, or the text "Hello ".
    In earlier programming languages, the concept of type was introduced to explain binary 01 data. The type defines the structure, size, range, and a series of operations on the data type.

    2. Name

    A unique identifier is required to name variables. Java follows the naming method of the following identifier:

    • An identifier consists of a string of uppercase/lowercase letters, numbers, underscores, and any length of $.
    • Blank spaces, tabs, line breaks, and other special characters (such as +-*/@ &) are not allowed. The incorrect naming method is max value and max-value.
    • An identifier cannot start with a number (0-9), must begin with a letter (a-z, A-Z), underscore (_), and $, and the system retains an identifier starting with $.
    • The identifier cannot use keywords or reserved fields (for example, class, int, double, if, else, for, true, false, null ).
    • Identifiers are case sensitive, and rose, Rose, and ROSE are three different variables.

      Use the camper to name variables: theFontSize, roomNumber, xMax, yMin, xTopLeft, and thisIsAVeryLongVariableName. For more information, see the following suggestions:

      • It is very important to select a meaningful variable name. numberOfStudents and numStudents are recommended to represent the number of students, rather than n or x.
      • These variable names a, B, c, d, I, j, k, i1, j99 are meaningless.
      • X is usually used as an exception, y and z are used to represent coordinates, and I is used to represent cyclic indexes.
      • Differentiate single and plural variables. row indicates a single row, and rows indicates multiple rows. 3. Define Variables

        You need to define the name and type of the variable to use the variable in the program. You can use one of the following syntax:

        // Define a variable of a specific type, type identifierint option; // define multiple variables of the same type, separated by commas, type identifier1, identifier2 ,..., identifierNdouble sum, difference, product, quotient; // defines and initializes the variable. type identifier = initialValueint magicNumber = 88; // defines and initializes multiple variables of the same type, type identifier1 = initValue1 ,..., identifierN = initValueNString greetingMsg = "Hi! ", QuitMsg =" Bye! ";

        Note:

        • Java is a strongly typed language. A variable corresponds to a type. After a variable is declared, other types of data cannot be stored.
        • Each variable can only be declared once.
        • Before use, you can declare it anywhere in the program.
        • After a variable is declared, its type cannot be changed.
        • A statement declared by a variable starts with a type and serves this type from the beginning and end. A statement declared by a variable can only use a single type. 4. Constants

          Naming Conventions for constants: uppercase words are used, and multiple words are connected by underscores, such as MIN_VALUE and MAX_SIZE.
          Constants are immutable and declared using the keyword final. Initialization is required after the constant is declared.

          final double PI = 3.1415926; 
          5. Expression

          An expression is composed of operators and operands. A single type of value can be output through computation, for example

          1 + 2*3 // get the 7int sum, number; sum + number // get the int value double principal, interestRate; principal * (1 + interestRate) // calculate a double value.
          6. assign values

          Assign a right operand to the left operand, for example, x = 1.
          Calculate the value of the expression and assign it to the left operand, for example, x = (y + z)/2.

          Syntax of the value assignment statement:

          // Assign a value directly, variable = literalValuenumber = 88; // assign a value after the calculation expression, variable = expressionnumber = number + 1; // calculate the expression number + 1, finally, assign the result to number8 = number; // incorrect use of number + 1 = sum; // incorrect use
          7. Basic Types

          There are two types in Java: basic type (int, double, etc.) and reference type (class and array ).

          • Byte: 8-bit signed integer value range: [-2 ^ 7, 2 ^ 7-1] = [-128,127].
          • Short: 16-bit signed integer value range: [-2 ^ 15, 2 ^ 15-1] = [-32768,327 67].
          • Int: 32-bit signed integer value range: [-2 ^ 31, 2 ^ 31-1] = [-2147483648,214 7483647] (≈ 9 digits ).
          • Long: 64-bit signed integer value range: [-2 ^ 63, 2 ^ 63-1] = [-9223372036854775808, + 9223372036854775807] (≈ 19 digits ).
          • Float: 32-Bit Single-precision floating point number (≈ 6-7 decimal places, value range: ± [≈ 10 ^-45, ≈ 10 ^ 38]).
          • Double: 64-bit double-precision floating point number (≈ accurate to 14-15 small trees, value range: ± [≈ 10 ^-324, ≈ 10 ^ 308]).
          • Char: indicates a 16-bit Unicode code. The value range is '\ u0000' to '\ uffff'. It can be considered as a 16-bit unsigned integer. The value range is [0, 65535].
          • Boolean: the boolean value can only be true or false. Although the size of the boolean data type is not defined in Java, it must be at least 1 bit.

            Built-in Basic Types

            The basic types are built in the program language. From the figure above, we can see that Java has eight basic types.

            There are four signed integer types: 8-bit byte, 16-bit short, 32-bit int, and 64-bit long.

            The value range of the 32-bit float and float is 1. 4023p846 × 10 ^-45 to ± 3. 40282347 × 10 ^ 38.

            The value range of the 64-bit double and double values is ± 4. p4065645841246544 × 10 ^-324 to ± 1. 7p76p313486231570 × 10 ^ 308.

            Char represents a single character, such as p; 0 p;, p; Ap;, p; ap;, in Java, char uses 16-bit Unicode (UCS-2 format) to support internationalization (i18n ).

            The binary boolean type is introduced in Java. It can contain only true and false values.

            Example: The program below is used to print the maximum value, minimum value, and bit length of the basic type.

            /** Maximum, minimum, and bit length of the output basic type */public class PrimitiveTypesMinMax {public static void main (String [] args) {// int (32-bit signed integer) system. out. println ("int (min) =" + Integer. MIN_VALUE); System. out. println ("int (max) =" + Integer. MAX_VALUE); System. out. println ("int (bit-length) =" + Integer. SIZE); // byte (8-bit signed integer) System. out. println ("byte (min) =" + Byte. MIN_VALUE); System. out. println ("byte (max) =" + Byte. MAX_VALUE); System. out. println ("byte (bit-length) =" + Byte. SIZE); // short (16-bit signed integer) System. out. println ("short (min) =" + Short. MIN_VALUE); System. out. println ("short (max) =" + Short. MAX_VALUE); System. out. println ("short (bit-length) =" + Short. SIZE); // long (64-bit signed integer) System. out. println ("long (min) =" + Long. MIN_VALUE); System. out. println ("long (max) =" + Long. MAX_VALUE); System. out. println ("long (bit-length) =" + Long. SIZE); // char (16-bit or 16-bit unsigned integer) System. out. println ("char (min) =" + (int) Character. MIN_VALUE); System. out. println ("char (max) =" + (int) Character. MAX_VALUE); System. out. println ("char (bit-length) =" + Character. SIZE); // float (32-bit floating point number) System. out. println ("float (min) =" + Float. MIN_VALUE); System. out. println ("float (max) =" + Float. MAX_VALUE); System. out. println ("float (bit-length) =" + Float. SIZE); // double (64-bit floating point number) System. out. println ("double (min) =" + Double. MIN_VALUE); System. out. println ("double (max) =" + Double. MAX_VALUE); System. out. println ("double (bit-length) =" + Double. SIZE) ;}} int (min) =-2147483648int (max) = 2147483647int (bit-length) = 32 byte (min) =-128 byte (max) = 127 byte (bit-length) = 8 short (min) =-32768 short (max) = 32767 short (bit-length) = 16 long (min) =-9223372036854775808 long (max) = 9223372036854775807 long (bit-length) = 64 char (min) = 0 char (max) = 65535 char (bit-length) = 16 float (min) = 1.4E-45 float (max) = 3.4028235E38float (bit-length) = 32 double (min) = 4.9E-324 double (max) = 1.7976931348623157E308double (bit-length) = 64
            String

            String is another common type that represents text content. In Java, double quotation marks are used for strings.

            String message = "Hello, world! "; // Double quotation marks for the string char gender = 'M'; // single quotation marks for the character

            Select a data type for the variable

            During development, we need to design appropriate variable types. In most cases, it is not difficult to choose. You can use int to store integer types, float to store decimal numbers, and String to store text, char is used to store a single character and boolean to store binary results.

            Rule of thumb

            Because the int type is very accurate and efficient, it is often used for counting and indexing.

            Use the int type whenever possible.

            Data Representation

            It is worth noting that char '1' is different from int 1, byte 1, short 1, float 1.0, double 1.0, and String "1, they have different precision and descriptions in computer memory, for example:

            Byte 1 indicates 00000001

            Short 1 indicates 00000000 00000001

            Int 1 indicates 00000000 00000000 00000000 00000001

            Long 1 indicates 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001

            Float 1.0 indicates 0 01111111 0000000 00000000

            Double 1.0 indicates 0 01111111111 0000 00000000 00000000 00000000 00000000 00000000 00000000

            Char '1' indicates 00000000 00110001

            String "1" indicates a complex object

            Here is an example of the variable name and type:

            Paul bought an abc-Branded Laptop with a 15 inch GHz High-speed processor, 4 GB memory, 1650.45 GB hard drive, and display. The total price is $, plan B is selected from plan A, plan B, and plan C on site, and related variables and types are defined.

            String name = "Paul"; String brand = "abc"; double processorSpeedInGHz = 3.2; // or floatdouble ramSizeInGB = 4; // or floatint harddiskSizeInGB = 500; // or optional int monitorinch = 15; // or bytedouble price = 1650.45; char servicePlan = 'B'; boolean onSiteService = true;
            Exercise:

            Suppose you are developing a software for the school to collect student information. The student information includes age, address, phone number, gender, birthday, height, weight, grade, and admission time, each student is assigned an 8-digit identifier. Use variables to define them.

            8. The literal value for the basic type and String type

            The literal and literal values used in programming are specific constants, for example, 123,-456, 3.14,-1.2e3, 'A', "Hello", which can be used as values or expressions.

            Integer (int, long, short, byte) Nominal value

            // All integers are regarded as int by default, such as 123 and-456. in Java, the 32-bit int value ranges from-2,147,483,628 (-2 ^ 31) to 2,147,483,627 (2 ^ 31-1) int number =-123; int sum = 1234567890; // This value is within the int Value Range int bigSum = 8234567890; // error: this value is out of the int value range. // no special description of the int literal value indicates that the value is in hexadecimal notation, And the number starting with 0 indicates that the value is in hexadecimal notation, A number starting with '0x 'indicates hexadecimal. Int number = 1234; // 10 hexadecimal 1234int number = 01234; // 8 hexadecimal 1234, 10 hexadecimal 668int number = 0x1abc; // 16 hexadecimal 1ABC, decimal: 6844 // starting from JDK1.7, you can use '0b' or '0b' as the prefix to represent binary. You can also use underline _ to group numbers to improve readability, however, numbers must be used at the beginning and end. Int number1 = 0b0104251010001011036910100010; int number2 = random; int number3 = 2_123_456; // The long bigNumber = 1234567890123L with the extension 'L' or 'l; long sum = 123; // int type 123 will be automatically converted to long type 123L // No suffix is required for byte and short, you can use an integer to initialize byte smallNumber = 12345; // error: byte smallNumber = 123 is out of the byte value range; short midSizeNumber =-12345; // values with decimal points, such as 55.66 and-33.44, are treated as double by default. Type, you can also use scientific notation, such as 1.2e3,-5.5E-6, uppercase E lowercase e Represents the 10 index, you can add the suffix 'D' or 'D' to the number. Float average = 55.66; // error! The right operation is of the double type, and the suffix 'F' is required to indicate float average = 55.66f;

            Character nominal value and escape sequence

            // Characters are embedded in single quotes to indicate the char type. The char type uses 16-bit Unicode encoding. The arithmetic operation is equivalent to the 16-bit unsigned integer char letter = 'A '; // equivalent to 97 char anotherLetter = 98; // equivalent to 'B' System. out. println (letter); // output 'A' System. out. println (anotherLetter); // output 'B' instead of the number anotherLetter + = 2; // 100 or 'D' System. out. println (anotherLetter); // output 'D'

            Non-printable control characters are generally called escape sequences, usually starting with backslash \. Below are common escape sequences:

            • Line Break: \ n is equivalent to 000AH (10D)
            • Carriage Return: \ r equivalent to 000DH (13D)
            • Tab: \ t equivalent to 0009 H (9D)
            • Double quotation marks: \ "equivalent to 0022 H (34D)
            • Single quotes: \ 'equivalent to 0027 H (39D)
            • Backslash: \ is equivalent to 005CH (92D)

              Note:

              • Escape sequences \ n and \ r are used to represent the linefeed (000AH) and carriage return (000DH) respectively. It is worth noting that \ n (0AH) is used in Unix and Mac to represent the line feed, in Windows, \ r \ n (0D0AH) is used.
              • Use escape sequence \ t to represent a tab (0009 H ).
              • To solve the ambiguity, backslash (\), single quotation mark ('), and double quotation mark (") are represented by escape sequences \, \' and \" respectively.
              • Other less commonly used escape sequences: \ a alarm, \ B escape, \ f form feed, \ v vertical tag, which may not be supported by some consoles.

                String Literal Value

                An indefinite string is embedded in double quotation marks to indicate the string literal value, for example, "Hello, world! "," The sum is: ", for example:

                String diremsg MSG = "Turn Right"; String greetingMsg = "Hello"; String statusMsg = ""; // empty String // The String literal value may contain an escape sequence, you need to use \ "to indicate double quotation marks. single quotation marks do not need to be escaped. Example: System. out. println ("Use \" to place \ n a \ "within \ ta \ tstring"); Use \ "to place a" withinastring

                Exercise: write a program to print out the following characters.

                    '__'          (oo)  +========\/ / || %%% ||*  ||-----||   ""     ""    

                Boolean Literal Value

                // The boolean literal value must contain two values: true and falseboolean done = true; boolean gameOver = false;

                Example of a literal value

                Public class LiteralTest {public static void main (String [] args) {String name = "Tan Ah Teck"; // String uses double quotation marks char gender = 'M '; // char use single quotes boolean isMarried = true; // true or false byte numChildren = 8; // byte value range [-127,128] short yearOfBirth = 1945; // short value range: [-32767,327 68] int salary = 88000; long netAsset = 8234567890L; double weight = 88.88; float gpa = 3.88f; // output System. out. println ("Name is" + name); System. out. println ("Gender is" + gender); System. out. println ("Is married is" + isMarried); System. out. println ("Number of children is" + numChildren); System. out. println ("Year of birth is" + yearOfBirth); System. out. println ("Salary is" + salary); System. out. println ("Net Asset is" + netAsset); System. out. println ("Weight is" + weight); System. out. println ("GPA is" + gpa );}} name is Tan Ah TeckGender is mIs married is trueNumber of children is 8 Year of birth is 1945 Salary is 88000Net Asset is 1234567890 Weight is 88.88 Height is 188.8
                 

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.