【JavaSE】Data types and variables

Table of contents

1. Literal constants

2. Data type 

3. Variables 

3.1 Variable concept

3.2 Grammar format 

3.3 Integer variables 

3.3.1 Integer variables

3.3.2 Long integer variable 

 3.3.3 Short integer variable

 3.3.4 Byte variables

3.4 Floating point variables 

 3.4.1 Double precision floating point type

 3.4.2 Single-precision floating point type Edit 

3.5 Character variables

3.6 Boolean variables

4. Type conversion

 4.1 Automatic type conversion (implicit) 

4.2 Forced type conversion (explicit)  

5. Type promotion

 6. String type


 From now on, we will gradually update Java knowledge


1. Literal constants

 For example:  System.Out.println("Hello World"); statement, no matter when the program is run, the output is Hello
World, in fact, "Hello World" is a literal constant.

 Constants are fixed quantities that do not change during the running of the program:

public class Test {
    public static void main(String[] args) {
        System.out.println("hello world!");
        System.out.println(100);
        System.out.println(3.14);
        System.out.println('A');
        System.out.println(true);
        System.out.println(false);
    }
}

 

Among them: 100, 3.14, ‘A’, true/false are all constants, which are called literal constants 

Classification of literal constants:
1. String constants: enclosed by "", such as "12345", "hello", "hello".
2. Integer constants: numbers written directly in the program (note that there is no decimal point), such as: 100, 1000
3. Floating point constants: numbers written directly in the program decimal, such as: 3.14, 0.49
4. Character constant: a character enclosed in single quotes, such as: 'A', '1'
5. Boolean constants: there are only two kinds: true and false
6. Empty constant: null (more on this later)
Note: string, integer, floating point type , character type and Boolean type are called data types in Java.


2. Data type 

Data types in Java are mainly divided into two categories: basic data types and reference data types (will be discussed later)

There are four and eight basic data types:
1. Four categories: Integer type, < /span> 2. Eight types:Boolean type and Character, Floating point

Note:
1. Whether in a 16-bit system or a 32-bit system, int occupies 4 bytes and long occupies 8 bytes
2. Both integer and floating-point types are signed
3. The default integer type is int and the default floating-point type is double
4 .Strings are reference types, and the types will be introduced later 

What is a byte?
A byte is the basic unit of space in a computer.
Computers use binary to represent data. We think of 8 A binary bit (bit) is a byte.
Our usual computer has 8GB of memory, which means 8G bytes.
Among them, 1KB = 1024 Byte, 1MB = 1024 KB, 1GB = 1024 MB. 1B=8 bit
So ​​8GB is equivalent to more than 8 billion bytes 

Note:10.24 is also our programmers’ holiday 1024 


3. Variables 

3.1 Variable concept

In a program, in addition to constants that remain unchanged, some contents may change frequently, such as a person's age, height, score, calculation results of mathematical functions, etc. For these frequently changing contents, in a Java program, called variables. Data types are used to define different types of variables.

To put it simply: A quantity that can be modified is called a variable.

3.2 Grammar format 

The syntax format for defining variables is: 

Data type variable name = initial value; 

 For example :

public class Test {
    public static void main(String[] args) {
        int a = 10; // 定义整形变量a,a是变量名也称为标识符,该变量中放置的值为10
        double d = 3.14;
        char c = 'A';
        boolean b = true;
        System.out.println(a);
        System.out.println(d);
        System.out.println(c);
        System.out.println(b);
        a = 100; // a是变量,a中的值是可以修改的,注意:= 在java中表示赋值,即将100交给a,a中保存的值就是100
        System.out.println(a);
// 注意:在一行可以定义多个相同类型的变量
        int a1 = 10, a2 = 20, a3 = 30;
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);
    }
}

Relatively simple, roughly familiar with C language 

        int a;
        System.out.println(a);

Uninitialized values ​​are not allowed in Java. This way of writing is wrong. 

3.3 Integer variables 

3.3.1 Integer variables

// 方式一:在定义时给出初始值
int a = 10;
System.Out.println(a);
// 方式二:在定义时没有给初始值,但使用前必须设置初值
int b;
b = 10;
System.Out.println(b);
// 使用方式二定义后,在使用前如果没有赋值,则编译期间会报错
int c;
System.Out.println(c);
c = 100;
//也会报错

 Generally familiar with C language, passed it directly

Key points: 

public class Test {
    public static void main(String[] args) {
        // int型变量所能表示的范围:
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);
    }
}

This is the maximum value of int and the minimum value Print 

The packaging type of int is Integer

int type range -2147483648--2147483647

Maximum: Integer.MIN_VALUE

Minimum value: Integer.MAX_VALUE

 

In Java, once the scope of the type is exceeded, an error will be reported immediately. 

Notes:
1. Int is 4 bytes no matter what system it is in.
2. It is recommended to use the first definition, if If there is no suitable initial value, it can be set to 0
3. When setting the initial value for a variable, the value cannot exceed the representation range of int, otherwise it will cause overflow
4. Variables must be assigned an initial value before use, otherwise a compilation error will be reported
5. The packaging type of int is Integer 


 3.3.2 Long integer variable 

public class Test {
    public static void main(String[] args) {
        int a = 10;
        long b = 10; // long定义的长整型变量
        long c = 10L; // 为了区分int和long类型,一般建议:long类型变量的初始值之后加L或者l
        long d = 10l; // 一般更加以加大写L,因为小写l与1不好区分
    }
}
  // long型变量所能表示的范围:这个数据范围远超过 int 的表示范围. 足够绝大部分的工程场景使用.
        System.out.println(Long.MIN_VALUE);
        System.out.println(Long.MAX_VALUE);

 This i value is already very large, and long is not used in most scenarios.

Notes:
1. Add L or l after the initial value of a long integer variable. It is recommended to add L
2. Regardless of the long integer type Under that system, they all occupy 8 bytes
3. The representation range of long integer is: -2^63--2^63-1
4 The packaging type of .long is Long 


3.3.3 Short integer variable

public class Test {
    public static void main(String[] args) {
        short a = 10;
        System.out.println(a);
// short型变量所能表示的范围:
        System.out.println(Short.MIN_VALUE);
        System.out.println(Short.MAX_VALUE);
    }
}

Notes:
1. Short occupies 2 bytes in any system
2. The representation range of short is: -32768 ~ 32767
3. Be careful not to exceed the range when using it (generally used less)
4. The packaging type of short is Short  


 3.3.4 Byte variables

 byte is a Java-specific type. It occupies one byte -128--127

public class Test {
    public static void main(String[] args) {
        byte b = 10;
        System.out.println(b);
// byte型变量所能表示的范围:
        System.out.println(Byte.MIN_VALUE);
        System.out.println(Byte.MAX_VALUE);
    }
}

Notes:
1. byte occupies 1 byte in any system
2. The range of byte is: -128 ~ 127
3. The packaging type of bytes is Byte 

Once it exceeds the scope of this type, it will report an error directly, which is also different from C language; 


3.4 Floating point variables 

 3.4.1 Double precision floating point type

double d = 3.14;

System.out.println(d);

The default type of floating point in Java isdouble Occupies8 bytes

Magic code one: 

        int a = 1;
        int b = 2;
        System.out.println(a / b); // 输出 0.5 吗?

The answer is 0 because they are all plastic, just like C language

To become 0.5 

Correct way to write:

System.out.println(a*1.0 / b);

Magic code two:  

double num = 1.1;
System.out.println(num * num);  // 输出1.21吗?

// As a result
1.2100000000000002 

Notes:
1. Double occupies 8 bytes in any system
2. Storage of floating point numbers and integers in memory The methods are different and cannot be calculated simply using the form
3. The packaging type of double is Double 

4. The memory layout of the double type complies with the IEEE 754 standard (the same as the C language). If you try to use limited memory space to represent potentially infinite decimals, there will inevitably be a certain precision error. Therefore, the floating point number is an approximation, not an exact value.


 3.4.2 Single precision floating point type  

An error is reported, because the default floating point type in Java is double. This will report an error.

Correct writing: 

float num = 1.0f;   // 写作 1.0F 也可以
System.out.println(num);

Note: The float type occupies four bytes in Java and also complies with the IEEE 754 standard. Due to the small precision range of the data represented, floating point numbers are generally given priority when using them in engineering double, it is not recommended to use float. The packaging type of float is Float. float occupies 4 bytes


3.5 Character variables

public class Test {
    public static void main(String[] args) {
        char c1 = 'A'; // 大写字母
        char c2 = '1'; // 数字字符
        System.out.println(c1);
        System.out.println(c2);
// 注意:java中的字符可以存放整形
        char c3 = '帅';
        System.out.println(c3);
    }
}

Notes:
1. In Java, single quotes + single letters are used to represent character literals.
2. The nature of characters in computers is an integer. In C language, ASCII is used to represent characters, while in Java, Unicode is used represents characters. Therefore, one character occupies two bytes and represents more types of characters, including Chinese. 

3. The char type occupies 2 bytes in Java, so it can represent more types

4.charpackaging typeCharacter


3.6 Boolean variables

The Boolean type is often used to represent true and false, and it often appears in real life. For example: I heard that classmate xxx won 100 million when he bought lottery tickets... After hearing this, I estimate that most people's first reaction is: I x, really Fake?

This is also a type only found in Java

public class Test {
    public static void main(String[] args) {
        boolean b = true;
        System.out.println(b);
        b = false;
        System.out.println(b);
    }
}

Notes:
1. There are only two values ​​for boolean type variables, true means true , false means false.
2. Java's boolean type and int cannot be converted to each other, there is no 1, which means true, 0 represents false usage.

3. The Java virtual machine specification does not clearly stipulate how many bytes boolean occupies, and there are no bytecode instructions specifically used to process boolean. In Oracle's virtual machine implementation, boolean occupies 1 byte.
4. The packaging type of boolean is Boolean


4. Type conversion

 Java, as a strongly typed programming language, will implement strict verification when variables of different types are assigned to each other.

 

long is the high byte, occupies 8 bytes, int occupies 4 bytes

The low byte can be stored in the high byte type

Vice versa; 

 In Java, when the data types involved in the operation are inconsistent, type conversion will be performed. Type conversion in Java is mainly divided into two categories: automatic type conversion (implicit) and forced type conversion (explicit).

4.1 Automatic type conversion (implicit) 

Automatic type conversion means that the code does not need to undergo any processing. The compiler will automatically process it when the code is compiled. Features: The conversion from a small data range to a large data range will be done automatically.

Error example:


4.2 Forced type conversion (explicit)  

Forced type conversion: When operating, the code needs to go through a certain format and cannot be completed automatically. Features: Large data range to small data range.

 Notes:
1. Assignment between variables of different numeric types means that types with a smaller range can be implicitly converted to types with a larger range
2. If you need to assign a type with a large range to a type with a small range, you need to force type conversion, but the precision may be lost
3. When assigning a literal constant, Java will Automatically check the numeric range
4. Forced type conversion may not be successful, and irrelevant types cannot be converted to each other


5. Type promotion

When different types of data operate on each other, the smaller data type will be promoted to the larger data type.

1. Between int and long: int will be promoted to long

      int a = 10;
      long b = 20;
      int c = a + b; // 编译出错: a + b==》int + long--> long + long 赋值给int时会丢失数据
      long d = a + b; // 编译成功:a + b==>int + long--->long + long 赋值给long

Analysis: int is 4 bytes and long is 8 bytes. When the two are added, int will be promoted to long type.

So the c that receives it must also be of type long

 2. Operation of byte and byte

 

Conclusion: byte and byte are the same type, but a compilation error occurs. The reason is that although a and b are both bytes, calculating a + b will first promote a and b to int, and then perform the calculation, and the result obtained is also int, if this is assigned to c, the above error will occur.

Since the computer's CPU 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.

[Type promotion summary:]
1. Different types of data mixing operations, small ranges will be promoted to large ranges.
2. For types such as short and byte, which are smaller than 4 bytes, they will first be promoted to 4-byte int and then operated. 


6. String type

 Use the String class to define string types in Java, such as:

 

 Note: The ‘+’ sign here is particularly magical.

The '+' sign in Java can directly concatenate two strings.

Equivalent to strcat in C language

Therefore, the efficiency of Java development will be higher


In some cases, it is necessary to convert between strings and integer numbers:
1. Convert String to int

public class Test {
    public static void main(String[] args) {
        String a="123";
        int ret=Integer.parseInt(a);
        System.out.println(ret+1);
    }
}

Analysis: Java provides many efficient functions

 Integer.parseInt() This function can directly convert strings into numbers

2.Convert int to String

Analysis: Both methods are available

1. Use the '+' symbol after the number to turn it into a string

2. Directly use the String.valueOf() function to receive

This section only provides a brief introduction to strings. You can use them normally. I will introduce them in detail later.

Guess you like

Origin blog.csdn.net/chaodddddd/article/details/134043760