Java data types
variables
Variables are used to hold data in memory that may change during program execution.
define variables
When defining a variable, you need to specify the data type and variable name, and you can also assign an initial value.
int age = 20;
double price;It is recommended that you complete initialization before the variable is used for the first time.
Scope of variable
Variables must be defined before they are used. The scope of a local variable starts at the location where it is declared and ends at the statement block in which it is located. Local variables with the same name cannot be defined repeatedly within the same scope.
public static void main(String[] args) {
{
int age = 20;
System.out.println(age);
// double age = 0; // 同一作用域内重复定义,编译错误
}
{
double age = 0;
System.out.println(age);
}
}constant
use final A modified variable can only be assigned once and is often called a constant.
final double PI = 3.1415926;Values such as numbers, characters, and strings written directly in code are called literals, such as 10、'A' and "Java"。
Data type classification
Java data types are divided into basic data types and reference data types. Basic data types directly represent simple values; arrays, classes, interfaces, enumerations, etc. are reference data types.
basic data types
integer type
| type | storage space | value range |
|---|---|---|
byte | 1 byte (8 bit) | -128 ~ 127 |
short | 2 bytes (16 bit) | -2^15 ~ 2^15 - 1 |
int | 4 bytes (32 bit) | -2^31 ~ 2^31 - 1 |
long | 8 bytes (64 bit) | -2^63 ~ 2^63 - 1 |
Integer literals default to int Type. beyond int The integer literal of the range must be added at the end L or l, it is recommended to use clearer ones in actual development L。
int age = 20;
long population = 3_000_000_000L;When the integer range exceeds long When you can use it according to business needs BigInteger。
floating-point type
| type | storage space | description |
|---|---|---|
float | 4 bytes (32 bit) | Single precision floating point number, approximately 7 decimal significant digits |
double | 8 bytes (64 bit) | Double-precision floating point number, approximately 15 - 16 decimal significant digits |
Floating point literals default to double Type. to float When assigning floating point literals to a variable, you need to add F or f Suffix.
float score = 3.14F;
double price = 3.1423424;There are precision errors in floating point numbers. When precise decimal operations are needed, use the BigDecimal。
character type
char Occupying two bytes, used to hold one UTF-16 Code unit. Use single quotes for character literals.
char letter = 'a';
char unicodeLetter = '\u0061';Common escape characters are as follows:
| escape character | meaning |
|---|---|
\r | enter |
\n | newline |
\t | tabs |
\\ | backslash |
\" | double quotes |
\' | single quotes |
System.out.println("\\a\\");
System.out.println("d:\\lesson\\java2601");
System.out.println("这两个字符串\"相等\"");boolean type
boolean only true and false Two values are mainly used for conditional judgment. The Java language specification does not specify general boolean How many bytes a variable must occupy, so it should not depend on its specific storage size.
boolean passed = true;operator
arithmetic operators
Common arithmetic operators include +、-、*、/、%、++ and --。
Pre-increment modifies the variable first and then generates the expression result; post-increment first generates the original value and then modifies the variable.
int i = 3;
int j = i++;
System.out.println(j); // 3
System.out.println(i); // 4Modifying the same variable multiple times in a complex expression at the same time will reduce readability, and should be split into multiple statements as much as possible.
assignment operator
Assignment operators include =、+=、-=、*=、/= and %= Wait.
int value = 3;
value += 2;The compound assignment operator implicitly performs the necessary type conversions, but still be aware of possible data truncation.
comparison operators
Comparison operators include ==、!=、>、<、>= and <=, the expression result is boolean。
logical operators
Logical operators are used to handle boolean values.
!Represents logical negation.&&Represents a short circuit and.||Represents a short circuit or.
int value = 3;
System.out.println(value > 0 && value < 10);The short-circuit operation determines whether to continue calculating the right-hand expression based on the left-hand result.
bitwise operators
Bit operations directly process the binary bits of integers.
| operator | meaning | |
|---|---|---|
~ | bit negation | |
& | bitwise AND | |
| ` | ` | bitwise OR |
^ | bitwise XOR | |
<< | left shift | |
>> | Signed right shift | |
>>> | unsigned right shift |
<< When moving left, the right side fills in zero;>> When moving right, the left complement sign bit;>>> The left side fills in zero when moving right.
System.out.println(-1 >>> 1);
System.out.println(~(-1 >>> 1));For integers without overflow, shift left n Bit is usually equivalent to multiplying by 2^n。Right shift and division may differ in negative numbers and rounding rules, and cannot be directly equivalent in all scenarios.
Short-circuit operation and bit-based operation
&& and || It can only be used in Boolean expressions and has a short circuit characteristic.& and | It can be used for both integer bit operations and Boolean operations; when used for Boolean operations, both expressions are executed.
int i = 3;
System.out.println(i > 5 && i++ < 10);
System.out.println(i); // 3
System.out.println(i > 5 & i++ < 10);
System.out.println(i); // 4XOR operation
In bitwise XOR, the result for the same bit is 0, the results of different bits are 1。
System.out.println(3 ^ 5); // 6An exclusive-OR can swap two integers without using a temporary variable, but this writing is poorly readable and an error occurs when two variables reference the same storage location. Temporary variables are recommended in actual development.
int a = 3;
int b = 4;
int temp = a;
a = b;
b = temp;Common applications of bit arithmetic
judge parity
boolean odd = (value & 1) == 1;Multiply by a power of two
Without overflowing,value << n equivalent to value * 2^n。
Taking modulo the power of two
when value is a non-negative integer, and the divisor is 2^n whenvalue % 2^n can be written as value & (2^n - 1)。Ordinary business code should still be written with clearer semantics.
Avoid average overflow
When calculating the average of two integers, use the (x + y) / 2 May overflow during the addition phase. Can be used according to the value range x + (y - x) / 2, or first convert to a wider range of types.
operator precedence
When you are uncertain about the order of operations, use parentheses to express your intention clearly, rather than relying on memorizing complex priority rules.
boolean result = (a + b) > 10 && c != 0;data type conversion
automatic type conversion
Numeric types with small value ranges can usually be automatically converted to types with large value ranges.
byte -> short -> int -> long -> float -> double
char -> int -> long -> float -> doubleSystem.out.println(5.0 / 2); // 2.5
System.out.println('a' + 1); // 98
System.out.println(2.0 % 5); // 2.0Dividing an integer by zero will throw ArithmeticException; floating point number divided by 0.0 Infinite or non-numerical results may be obtained.
System.out.println(17.0 / 0.0); // InfinityForced type conversion
When converting a type with a large range of values to a smaller type, an explicit cast is required. Forced conversions may cause loss of precision or numerical overflows.
System.out.println((int) 5.9); // 5
System.out.println((char) ('a' + 1)); // baddition to boolean In addition, basic numerical types can be converted according to rules. When writing code, try to avoid unnecessary forced conversions and check the range of values after conversion.
If you enjoyed this, leave a comment~