Java-- data types

Overview of basic types

  • boolean Boolean
  • byte byte
  • short / int / long short integer / integer / long integer
  • float / double floating point
  • char character

1, boolean boolean:
Only true, false, or two kinds of value, default is false

2 byte Type byte:
byte byte, 1 byte = 8 bits (8 bits)
stored in a signed integer two's complement code representation
minimum -128, a maximum value 127, a default value 0
byte type used in large arrays can be significant savings in space, instead of mainly small integers, because the space occupied by only byte variable of type int quarter
byte binary files use more reading and writing

3, the integer type:
Short, 16 bits, 2 bytes, complement binary integers represented by symbols
int, 32-bit, 4-byte, signed integer two's complement code representation
long, 64 bits 8 byte signed integer two's complement code representation

4, floating point numbers:
a float, single-precision, 32-bit, 4-byte
double, double, 64 bits, 8 bytes

5, the character type char:
a single 16-bit Unicode character
minimum value is \ u0000 (ie 0)
maximum is \ uFFFF (ie 65,535)
char data type can be stored any character

First, the basic type

1.1 Integer

In Java, integer range independent of the machine to run Java code, which would address the software migration from one platform to another, or to migrate to the programmer bring between different operating systems with a platform of many problem

  • The most common type is an int
  • Suffix have a long integer value L or l, as 4000000000L
  • Hexadecimal value has a prefix 0x or 0X, such 0xCAFE. Octal value has a prefix 0, such as 017
  • Java7 from the beginning, prefixed 0b or 0B may represent a binary, such as 0b1001; literal numbers can also be underlined, as 1_000_000, represents one million

1.2 Float

Numerical precision float double double type, and thus rarely the case of using a float, such as the need to single-precision data database, and the like need to store large amounts of data

  • Floating point values ​​does not apply to unacceptable financial calculations rounding errors, if not allowed in numerical rounding errors should be used in any type BigDecimal
  • It can be expressed in hexadecimal floating point data, such as 0.125 = 2 ^ (- 3) can be expressed as 0x1.0p-3. In hexadecimal notation, the index is denoted by p, rather than E; mantissa in hexadecimal, decimal index; Index base 2 is not 10
  • Is used to indicate an overflow error condition, and three special floating point values: positive infinity, negative infinity, NaN (Not a Number), respectively, and Double.NEGATIVE_INFINITY Double.NaN (Float.NaN) Double.POSITIVE_INFINITY as represented by a constant, divided by a positive integer, for example, 0 to positive infinity result, the square root of the result 0/0 or plural for a NaN

Special Note:

  1. Such a specific value can not be detected is equal Double.NaN:if(x == Double.NaN) // is never true
  2. All values ​​"non-value" are considered to be different, but you can use Double.isNaN method:if(Double.isNaN(x)) // check whether x is "not a number"

1.3char type

char type literal value to use single quotes; which can be expressed in hexadecimal values, ranging from \ u0000 to \ uFFFF

caveat!

  1. Unicode escape sequences will be processed before parsing code, such as "\ u0022 + \ u0022" is composed of a string plus quoted, in fact, \ u0022 is converted before parsing ", which will be" "+" ", i.e., an empty string
  2. Beware annotation \ u:
  • Notes  // \u00A0 is a newlinewill generate a syntax error, because the reading program \ u00A0 will be replaced with a line break
  • Notes  // Look inside c:\usersgenerates a syntax error because \ u did not follow after four hexadecimal digits

highly recommended:

  1. Do not use a char type (described because it can not meet the needs of all Unicode characters), unless absolutely need to handle UTF-16 code units in the program
  2. Preferably the processing string as abstract data types

1.4 enumerated types

Sometimes, the values of variables only in a limited collection. If there are certain risks of its coding, variable probably saved a wrong value, set the enumerated type
for example, pizza sizes small, medium, large, large four kinds, customizable enumerated type:
enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
statement this type of variables:
Size s = Size.MEDIUM;
Size of the type of a variable can hold only given this type of an enumeration, or a null value (null means that the variable is not set to any value)

1.5 Large value

If the basic integer and floating point accuracy can not meet the demand, use Java.math package BigInteger BigDecimal class and classes, the processing sequence of digital values include any length of
special attention, not in a large numerical calculation using simple operator, and using the method

import java.util.*;
import java.math.*;
 
/**
 * This program discribes big number that is about luck draw
 * @version 11:27 2019-09-29
 * @auther xxwang1018
 */
 
public class BigNumberTest{
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("总共几个数?");
        int total=in.nextInt();
        System.out.println("要抽几个数?");
        int number=in.nextInt();
 
        BigInteger lotteryOdds=BigInteger.valueOf(1);
        for(int i=1; i<=number; ++i)
            lotteryOdds=lotteryOdds.multiply(BigInteger.valueOf(total-i+1)).divide(BigInteger.valueOf(i));
        /**
         * 中奖概率 n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
         */
        System.out.println("你的中奖率为1/"+lotteryOdds);
    }
}

/*
测试结果:
总共几个数?
490
要抽几个数?
60
你的中奖率为1/716395843461995557415116222540092933411717612789263493493351013459481104668848

1.6 data operations

1.6.1 Data type conversion

1, implicit type conversions
when two different types of data values for the binary operators, is first converted to the same data type and then computes

  • If both operands have a type double, the other will be converted into a double
  • Otherwise, if one operand is of type float, the other will be converted into float type
  • Otherwise, if one operand is long type, will be converted into another type of long
  • Otherwise, both operands are converted to type int

2, cast
floating-point convert integer type is achieved by truncating the fractional part
If trying to tell a cast from one value type to another type, and beyond the range of the target type of representation, the result will be very different, such as (byte) 300 is the actual value 44

1.6.2 Bit Operations

Processing integer type, for each integer value bits directly operate; masking techniques may be used in each bit of the integer
bitwise operators comprises:

  • &Operator: the corresponding bits are 1, the result value of the corresponding bit is 1, such as: 0110 & 1011 = 0010
  • |Operator: the corresponding bits are 0, the resulting value of the corresponding bit is 0, such as: 0110 | 1011 = 1111

When used in a Boolean value, and & | operator will obtain a Boolean value
thereof && and || operator similar, but the former does not use a "short" evaluation mode, i.e., both operators are required operand is calculated

  • ^Operator: corresponding bit result value corresponding to the same bit is 0, the corresponding bit corresponding to a different result value is 1 bit, such as: 0110 ^ 1011 = 1101
  • ~Operator: The results of the initial value on the contrary, such as: - 1011 = 0100
  • <<Operator: left, the value of N is << S N S bits to the left, to the right vacated bit stuffing 0, S is equivalent to multiplying the power of two, such as: 11111000 = 11110000 << 1
  • >>Operator: the right, the value of N is N >> S S bits to the right, left vacant is positive if the bit 0 is populated, if the filling is an negative number, the equivalent of dividing the power of S 2, such as : 00010111 00000101,11110110 >> >> 2 = 3 = 1111110
  • >>>Operator: unsigned shift right, whether positive or negative, left vacant after the bit unsigned right shift are padded with zeros, such as: 11111000 = 00111110 2 >>>

Right operand shift operator 32 to complete the operation mode (unless the left operand type long, then the need for the right operand modulo 64), as the value << 1 << 1 32 3 equal or 8

Second, the string

Java has no built-in string type, but provides a predefined String class in the standard Java library

2.1 splicing

Unlike most programming languages, using the Java language allows connecting two string + number
when a string concatenation with a non-string value, which is converted into a string (any Java object can be converted into string)

2.2 empty string and a null string

Java object is a null string, the string has its own length (0) and the content (blank)
String variable can hold a special value called NULL, indicating that no variable is currently associated with that variable
to check a string is neither null nor is it an empty string, use the statement if (str! = 0 && str.length ()! = 0), we should first check str is not null

Third, the array

There are two ways to declare an array, int [] a or int a [], most people prefer to use the first, it will type int [] (array of integers) is separated from the variable name

Java, the length of the array may be variable: new int [n] represents the creation of an array of a length n; may also be 0, but with a different null

  1. When you create an array of numbers, all the elements are initialized to 0 by default
  2. When you create a boolean array, all elements initialized by default false
  3. When you create an array of objects, all the elements initialized by default to null, indicates that these elements did not store any objects

3.1for each cycle

1, one-dimensional arrays

for(value: collection)
    //do something with value

collection class object set expression must be an array or an implement Iterable interface
2, a two-dimensional array

for(double[] row : a)
    for(double value : row)
        //do something with value

for each statement can not be processed automatically each element of the two-dimensional array, which is in accordance with the line, which is one-dimensional array processing

3.2 one-dimensional array

3.2.1 Initialization

1, static initialization: explicitly specify the initial value of each array element at initialization time, the system determines the length of the arrayarrayName = new type[]{ element1, element2, element3... };

int[] intArr;
intArr = new int[]{1,2,3,4,5,9};

2, a simplified static initializationtype[] arrayName =  {element1, element2, element3... };

String[] strArr = {"张三","李四","王二麻子"};

3, dynamic initialization: Specifies the length of the array initialization, the default value by the system initialization each array elementarrayName = new type[length];

int[] price = new int[4];

NOTE: Do not use static and dynamic initialization initialization, i.e. not during initialization array, specify both a length of the array, and the initial value assigned to each array element

3.2.2 copy

Java allows to copy an array variable to another array variable, then the two variables refer to the same array

int[] luckNumber=intArr; //接上面的数组
luckNumber[5]=12; //now kakaka[5] is also 12

For an array of all the values ​​copied to the new array, may be used copyOf Arrays class method, the method typically used to increase the size of the array

int[] copyLuckNumber= Arrays.copyOf(luckNumber, luckNumber.length);

3.3 Multidimensional Arrays

import java.util.*;
 
/**
 * This program demonstrates a YanghuiTriangle arrey
 * @version 12:29 2019-09-29
 * @auther xxwang1018
 */
 
public class YanghuiTriangle{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("请输入杨辉三角的行数:");
        int n = in.nextInt();
 
        int[][] triangle = new int[n][];
        for (int i=0; i<triangle.length; i++) {
            triangle[i] = new int[i+1];
 
            for (int j = 0; j < triangle[i].length; j++) {
            if (i == 0 || j == 0 || i == j) {
                    triangle[i][j] = 1;
                } else {
                    triangle[i][j] = triangle[i - 1][j] + triangle[i - 1][j - 1];
                }
                System.out.print(triangle[i][j] + " ");
            }
            System.out.println();
        }
    }
}

/*
测试结果:
请输入杨辉三角的行数:8
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 
1 6 15 20 15 6 1 
1 7 21 35 35 21 7 1 

Guess you like

Origin www.cnblogs.com/xxwang1018/p/11606876.html