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
Variables modified with final can only be assigned once and are often called constants.
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 byte (64 bit) | -2^63 ~ 2^63 - 1 |
Integer literals default to type int. Integer literals that exceed the range of int must be added L or l at the end. It is recommended to use clearer L in actual development.
int age = 20;
long population = 3_000_000_000L;
When the integer range exceeds long, BigInteger can be used according to business needs.
floating-point type
| Type | Storage Space | Description |
|---|---|---|
float | 4-byte (32 bit) | single precision floating point number, approximately 7 decimal significant digits |
double | 8-byte (64-bit) | double precision floating point number, approximately 15 - 16 decimal significant digit |
Floating-point literals default to type double. When assigning floating point literals to a float variable, you need to add a 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 required, BigDecimal should be used.
character type
char occupies two bytes and is used to store a 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 | Line Break |
\t | Tab |
\\ | Backslash |
\" | Double quotes |
\' | Single quote |
System.out.println("\\a\\");
System.out.println("d:\\lesson\\java2601");
System.out.println("这两个字符串\"相等\"");
boolean type
boolean has only two values, true and false, which are mainly used for condition judgment. The Java language specification does not specify how many bytes ordinary boolean variables must occupy, so their specific storage size should not be relied on.
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); // 4
Modifying 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 %=.
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
The comparison operators include ==, !=, >, <, >=, and <=, and the expression result is boolean.
logical operators
Logical operators are used to handle boolean values.
!Represents logical negation.- ’&’ means 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 XOR |
<< | left shift |
>> | Signed right shift |
>>> | unsigned right shift |
When << moves left, zeroes are added on the right side; when >> moves right, symbol bits are added on the left side; when >>> moves right, zeroes are added on the left side.
System.out.println(-1 >>> 1);
System.out.println(~(-1 >>> 1));
For integers without overflow, shifting n bits to the left 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 ||Can only be used in Boolean expressions and has a short circuit property.& and |Can be used for both integer bit operations and Boolean operations; when used for Boolean operations, both expressions will be 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); // 4
XOR operation
In bit-by-bit exclusive-OR, the result for the same bit is 0, and the result for the different bit is 1.
System.out.println(3 ^ 5); // 6
An 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 Operations
parity judgment
boolean odd = (value & 1) == 1;
times a power of two
value << n is equivalent to value * 2^n without overflow.
Taking modulo the power of two
When value is a non-negative integer and the divisor is 2^n, value % 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, using (x + y) / 2 directly may overflow during the addition stage. x + (y - x) / 2 can be used according to the value range, or converted to a larger range of types first.
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 -> double
System.out.println(5.0 / 2); // 2.5
System.out.println('a' + 1); // 98
System.out.println(2.0 % 5); // 2.0
Dividing an integer by zero throws ArithmeticException; dividing a floating point number by 0.0 may yield infinite or non-numeric results.
System.out.println(17.0 / 0.0); // Infinity
Forced 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)); // b
Except for boolean, 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~