Java se: data types and operators

Posted by tores on Sat, 16 Oct 2021 03:25:43 +0200

Data types and operators

Variables and types

Variable refers to the variable amount when the program runs, which is equivalent to opening up a memory space to save some data, and the value of the variable can be known only when the program runs. Type is a division of variable types. Variables of different types have different characteristics

Integer variable: int

Format: int Variable name = Initial value;
give an example: int a = 2333;//Defines an integer variable named a

When we use this variable in the future, we use it through its variable name A. It is optional to initialize variable a, but we recommend that we explicitly initialize it when creating variables.

In Java, an int variable takes up 4 bytes. It has no direct relationship with the operating system. In C language, the 16 bit operating system takes up 2 bytes and the 32 / 64 bit operating system takes up 4 bytes, which is related to the operating system.

In a computer, numerical values are always stored with binary complements. The highest bit of binary is the sign bit. 0 represents a positive number and 1 represents a negative number. Each binary number occupies 1 bit when stored, and 8 bits are a byte. Therefore, int variables occupy 32 bits. In addition to the sign bit represented by the highest bit, a total of 31 bits can be used to represent numbers.

Long integer variable: long

If the result of the operation exceeds the maximum range of int, overflow will occur. In this case, we need to use a wider range of data types to define variables. Java provides long type

Format: long Variable name = Initial value;
give an example: int num = 123L;//A long integer variable named num with an initial value of 123 is defined

10 can also be used for initialization. The type of 10 is int, which is a type conversion. The assignment between variables of different numeric types means that types with a smaller range can be implicitly converted to types with a larger range, otherwise it can't. the type we write 10L / 10L (both case and case) is long, which makes the assignment better. In order to distinguish between lowercase L and 1, We usually use the capital letter L.

In Java, the long type takes up 8 bytes. The data range is * *: - 2 ^ 63 – 2 ^ 63-1**

double precision floating point variable: double

Format: double Variable name = Initial value;
give an example: double b = 1.0;

a key:

int a = 1;
int b = 2;
System.out.println(a/b);

In java, the value of int type divided by int type is still int value, and the decimal part will be directly discarded

If you want to get 0.5, you need to use the double type for calculation

double a = 1;
double b = 2;
System.out.println(a/b);

If we calculate this way, the theoretical result should be 1.21. In fact?

double num = 1.1;
System.out.println(num*num);

Why is the result we get not accurate 1.21, but 1.210000000000000 2? (understand)

  • Although the double in Java is also 8 bytes, the memory layout of floating-point numbers is very different from that of integers, and the data range cannot be simply expressed in the form of 2 ^ n. the memory layout of Java's double type complies with IEEE 754 standard (the same as C language). If you try to use limited memory space to represent possibly infinite decimal points, there will be a certain precision error

Single precision floating point variable: float

Format: float Variable name = Initial value;
give an example: float c = 2.0f;

Float type takes up four bytes in Java. Generally, double is preferred when floating-point numbers are used in engineering, so float is not recommended. The same as double is that 2.0f / 2.0f (both case and case) added after assignment is optional, but it is still recommended.

Character type variable: char

Format: char Variable name = Initial value;
give an example: char c = 'A';

In Java, the form of single quotation mark + single letter is used to represent the character literal value, while the character in the computer is essentially an integer. In C language, ASCII coding is used to represent the character, while in Java, Unicode coding is used to represent the character. In Unicode coding, a character occupies two bytes, so it represents more types of characters, Therefore, including Chinese and other languages of many countries. Examples are as follows:

char ch = 'Chinese'; 
System.out.println(ch);

Byte type character variable: byte

Format: byte Variable name = Initial value;
give an example: byte a = 1;

Byte type also represents an integer, accounting for only one byte, with a small representation range (- 128 – + 127). Although this type is similar to the name of character type, they are completely irrelevant.

Short integer variable: short

Format: short Variable name = Initial value;
give an example: short n = 10;

short takes up 2 bytes and represents a data range of (- 32768 - + 32767). This representation range is relatively small and is generally not recommended.

boolean type variable: boolean

Format: boolean Variable name = Initial value; 
give an example: boolean flag = true;

There are only two values for boolean variables: true and false. True means true and false means false. Different from C + +, true and false in Java boolean variables cannot be converted to int variables. There is no such usage as 1 means true and 0 means false. In particular, some JVM implementations of boolean types occupy 1 byte and some occupy 1 bit, No explicit provisions.

String type variable: String

Unlike the above types, String is not a basic type, but a reference type

Format: String Variable name = "Initial value";
give an example: String s = "abcdef";

The combination of characters is called string. In Java, double quotation marks and string are used to represent the literal value of string, that is, "abcdef" represents string abcdef

The same as C language, some specific characters in Java string that are not convenient for direct representation need to be escaped, and the escape rules are the same as C language, as follows:

Escape characterfunction
\nLine feed
\tHorizontal tab
\'Single quotation mark
\"Double quotation mark
\\Backslash

**String splicing: * * you can use + to splice strings

String a = "abc";
String b = "def";
System.out.println(a+b);

What happens when strings are added to other types of variables?

String a = "abc";
String b = "def";
int c = 233;
boolean flag = false;
System.out.println(a+c);
System.out.println(b+1.0);
System.out.println(a+b+flag);

It can be seen that when there is a string in the + expression, addition with other types is performed in the form of string

Scope of variable

The scope of a variable refers to the scope within which the defined variable can play a role, which is generally within the code block (curly braces) defined by the variable.

int a = 0;
{
	int b = 0;
}
System.out.println(a+b);

Obviously, variable b cannot be used outside the scope of variable b

Naming rules for variables

Hard rules:

  • Variable names can only contain numbers, letters, underscores, dollar symbols ($)
  • Cannot start with a number
  • Case is strictly distinguished, that is, variable a and variable a are two different variables

It is strongly recommended that:

  • The variable naming should be descriptive, so that the meaning can be known according to the name, preferably a noun, rather than Pinyin.

  • The small hump naming method is recommended for variable naming. When a variable name is composed of multiple words, the initials of other words are capitalized except the first word.

    int maxValue = 233; 
    String studentName = "Zhang San";
    

constant

A constant is an amount that cannot be changed when the program is running. It can only be initialized once, and the value of the constant has been determined when the program is compiled. Each type of variable also corresponds to a constant of the same type.

Constants are mainly embodied in the following two forms:

literal constant

10 //int literal constant (decimal) 
010//The int literal constant (octal) starts with the number 0, 010, which is the decimal 8 
0x10//The int literal constant (hexadecimal) starts with the number 0x, 0x10, which is the decimal 16 
10L//long literal constant, which can also be written as 10L (lowercase L) 
1.0//double literal constant, which can also be written as 1.0d or 1.0d 
1.5e2//double literal constant, expressed in scientific counting, is equivalent to 1.5 * 10 ^ 2 
1.0f//float literal constant can also be written as 1.0F 
true//boolen literal constant, and also false 
'a'//char literal constant. There can only be one character in single quotation marks
"abc"//String literal constant. There can be multiple characters in double quotation marks

Constant modified by final keyword

final double a=5.0d;
a=10.0;
System.out.println(a);

Constants cannot be modified while the program is running

Type conversion and value promotion

Type conversion

As a strongly typed programming language, Java teaches strict verification when variables of different types are assigned to each other. Examples are as follows:

int a = 5; 
long b = 10; 
a = b; // Compilation error, prompt may lose precision 
b = a; // The compilation passed 
int c = 10; 
double d = 1.0; 
c = d; // Compilation error, prompt may lose precision 
d = c; // The compilation passed 

Long indicates a larger range. You can assign int to long, but you can't assign long to int. double indicates a larger range. You can assign int to double, but you can't assign double to int.

Assigning values between variables of different numeric types means that types with smaller ranges can be implicitly converted to types with larger ranges, and vice versa.

int a = 1;
boolean b = true;
b = a; // Compilation error, prompt incompatible types
a = false; // Compilation error, prompt incompatible types

int and boolean are two unrelated types and cannot be assigned to each other

byte a = 2;
byte b =128;//Compilation error, incompatible type: conversion from int to byte may be lost
System.out.println(a);
short c = 233;
short d = 32768//Compilation error, incompatible type: conversion from int to short may be lost
System.out.println(d);

byte indicates that - 128 - + 127128 has exceeded the range, while 2 is still within the range, short indicates that - 32768 - + 3276732868 has exceeded the range, and 233 is still within the range.

When using literal constant assignment, Java will automatically perform some checks and verifications to determine whether the assignment is reasonable. This also explains why we will not report an error when using int literal constant to assign values to byte s and short with a smaller range.

Cast type

int a = 5;
long b = 10;
a = (int)b;//Compile passed
boolean c = false;
c = a;// Compilation error, prompt incompatible types
c = (boolean)a;// Compilation error, prompt incompatible types

In the above example, after the assignment, 10.5 becomes 10, the part after the decimal point is ignored, and the int type cannot be forcibly converted to boolean type.

double type can be cast to int by using cast type conversion, but cast type conversion may lead to precision loss, and cast type conversion is not necessarily successful. Cast type conversion cannot be carried out between unrelated types.

Numerical promotion

int a = 10;
long b = 20;
int c = a + b; // Compilation error, prompt that converting long to int will lose precision
long d = a + b;//Compile passed
int e =(int)(a + b);// Compile passed

When int and long are mixed, int will be promoted to long, and the result will still be of long type. You need to use variables of long type to receive the result. If you don't want to use int to receive the result, you need to use forced type conversion

byte a = 10; 
byte b = 20; 
byte c = a + b;// Compilation error, incompatible type: conversion from int to byte may be lost
System.out.println(c); 

Byte and byte are of the same type, but compilation errors still occur because although a and b are both bytes, calculating a+b will first promote both a and b to int, and then calculate. The result is int. at this time, assigning the result of int to c will cause the above error

Since the CPU of the computer usually reads and writes data from the memory in units of 4 bytes, for the convenience of hardware implementation, types less than 4 bytes, such as byte and short, will be promoted to int first, and then participate in the calculation

Conversion between int and String types

int to String

int num = 10;
String str1 = num + "";// Method 1
String str2 = String.valueOf(num); // Method 2
System.out.println(str1);
System.out.println(str2);

We have talked about the principle of method 1 when analyzing the String type. We can remember method 2 first. We will understand it later

String to int

String str = "2333";
int num = Integer.parseInt(str);
System.out.println(num);

Change the method, we can remember first, as we learn later, we will understand!

operator

Arithmetic operators:

Basic operator: add (+) subtract (-) multiply (*) divide (/) remainder (%)

Because the rules are relatively simple, we will not repeat too much, but only explain the parts that need attention

  1. Int type / int type result is still int type. If you need to get an accurate value, you need to use double to calculate it
  2. 0 cannot divide (compilation will report an error)
  3. %Represents remainder, which can be used not only for integers, but also for small trees

Incremental assignment operator: (+ =) (- =) (* =) (/ =) (% =)

The rules are as follows

a+=1  Equivalent to  a=a+1;
b-=1   <=>  b=b-1;
c*=2   <=>  c=c*2;
d/=3   <=>  d=d/3;
e%=4   <=>  e=e%4;

Auto increment / Auto decrement operator: (+ +) (–)

int a = 2;
int b = 2;
System.out.println(a++);
System.out.println(++b);
System.out.println(a);
System.out.println(b);

If the return value of the expression is not taken from the increment operation, there is no difference between the pre + + / – and the post + + / – and the variable is made + 1 or - 1. If the return value of the expression is taken, the return value of the pre + + / – is the value after + + / – and the return value of the post + + / – is the value before + + / –,

Relational operator

Relational operators include: equal to * * (= =) * * greater than * * (>) * * greater than or equal to * * (> =) * * less than * * (<) * * less than or equal to * * (< =) * * not equal to * * (! =)**

int a = 2;
int b = 3;
System.out.println(a==b);
System.out.println(a>b);
System.out.println(a>=b);
System.out.println(a<b);
System.out.println(a<=b);
System.out.println(a!=b);

The expression return values of relational operators are of boolean type

Logical operator

There are three main logical operators: and (& &) or (|) not (!)
Note: the operands (operands are often the result of relational operators) and return values of logical operators are boolean

Logical and (& &): both operands are true, and the result is true; otherwise, the result is false

System.out.println(10>20&&10>5);
System.out.println(10>5&&5>3);

Logical or (|): both operands are false, and the result is false, otherwise the result is true

System.out.println(10>20||10>5);
System.out.println(10>20&&5>30);

Logical non (!): the operand is true, the result is false, the operand is false, and the result is true (this is a unary operator with only one operand)

System.out.println(!(5>3));
System.out.println(!(3>7));

Short-circuit evaluation

&&And | observe the rules of short circuit evaluation

System.out.println(1 > 2 && 5 / 0 == 0);
System.out.println(1 < 2 || 1 / 0 == 0);

We know that 0 cannot be a divisor, which will cause the program to throw an exception. However, the above code can compile and run normally, indicating that the operation is not really evaluated. Therefore, for & &, if the value of the expression on the left is false, the overall value of the expression must be false. There is no need to calculate the expression on the right. For |, if the value of the expression on the left is true, Then the overall value of the expression must be true, and there is no need to evaluate the expression on the right

Bitwise Operators

The smallest unit of data operation in Java is not bytes, but binary bits. There are four bit operators: (&) (|) (~) (^)

Bit operation refers to binary bit operation. In computers, binary is used to represent data (sequence composed of 01). Bit operation is based on binary bit
Each bit is calculated in turn

Bitwise AND &: if both binary bits are 1, the result is 1, otherwise the result is 0

int a = 10;               //Binary of a: 0000 1010
int b = 20;				  //Binary of b: 0001 0100
int c = 8;				  //Binary of c: 0000 1000
System.out.println(a&b);      //A & B = 0000 convert 0000 to decimal: 0
System.out.println(a&c);	  //a&c=0000  1000 	 Convert to decimal: 8

Bitwise or |: if both binary bits are 0, the result is 0, otherwise the result is 1

int a = 10;                //Binary of a: 0000 1010
int b = 20;                //Binary of b: 0001 0100
int c = 8;                 //Binary of c: 0000 1000
System.out.println(a|b);        //a|b=0001 1110 converted to decimal: 30
System.out.println(a|c);		//a|c=0000 1010 converted to decimal: 10

  • **When the operands of & and | are integers (int, short, long, byte), they represent bitwise operation; when the operands are boolean, they represent logic
    Operation, but compared with & & and 𞓜, they do not support short-circuit evaluation (this method is not recommended!!!)**
System.out.println(false&true);
System.out.println(false&false);
System.out.println(true&true);
System.out.println(false|true);
System.out.println(true|true);
System.out.println(false|false);

Reverse by bit ~: if this bit is 0, it turns to 1; if this bit is 1, it turns to 0

int a = 7;			   
System.out.println(~a);

The result output here is - 8, which involves some knowledge of the original code, inverse code and complement of the computer during calculation. It is not repeated here. If you are interested, you can understand it by yourself

Bitwise exclusive or ^: if the binary bits of two numbers are the same, the result is 0, and if they are different, the result is 1

int a = 10;                //Binary of a: 0000 1010
int b = 20;                //Binary of b: 0001 0100
int c = 8;                 //Binary of c: 0000 1000
System.out.println(a^b);        //a^b=0001 1110 convert to decimal: 30
System.out.println(a^c);		//a^c=0000 0010 convert to decimal: 2

Displacement operation

There are three shift operators: * * (< (> >) (> >) * * all operate according to binary bits

Move left < <: the leftmost bit is not needed, and the rightmost bit is filled with 0. Move right > >: the rightmost bit is not needed, and the leftmost bit is filled with sign bit (positive number is filled with 0, negative number is filled with 1). Move right without sign > >: the rightmost bit is not needed, and the leftmost bit is filled with 0

int a = 10;                //Binary of a: 0000 1010
System.out.println(a<<1);  //A < < 1 = 0001 0100 converted to decimal: 20
System.out.println(a>>1);  //a> > 1 = 0000 1010 convert to decimal: 5
System.out.println(a>>>1); //a> > > 1 = 0000 1010 convert to decimal: 5

Conditional operator

There is only one conditional operator. The format is: expression 1? Expression 2: expression 3
When the value of expression 1 is true, the value of the whole expression is the value of expression 2. When the value of expression 1 is false, the value of the whole expression is the value of expression 3.

int a =10;
int b =20;
int max = a>b? a : b;
System.out.println(max);

The only ternary operator in Java is the simplified writing of conditional judgment statements

Operator precedence

Operators have priority. We don't have to remember the specific rules, and I won't repeat them here. When writing code, we can add parentheses according to our own operation logic.

The above is the whole content of this article. In view of the author's limited level, the article may make mistakes. I hope you can criticize and correct more!

Topics: Java Windows Back-end IDEA