The third day of Java basic learning (variables, data type conversion, operators)

1. Variables

1. Definition: A variable is a quantity whose value can change during the operation of the program

2. Format of declaring (defining) a variable:
Method 1: Data type variable name
Method 2: Data type variable name 1, variable 2….[declare multiple variables of the same type at one time]
Note: variables must be declared first With, a variable with the same name cannot be declared in a scope.

3. The naming convention of variable names: the first word is lowercase, the first letter of other words is uppercase, and the other words are lowercase.

4. Two data types
① Basic data type (8)
◆ Integer data type:
byte (byte): 8 bits (bit) 2^8 = 256 -128~127
short (short integer): 16bit
int( Integer): 32bit
long (long integer): 64bit
Note: If an integer is not added with any mark, then the default is int type data. If you need to represent the data as a long type of data, you need to add L after the data to indicate that L is not case-sensitive, but it is recommended to use uppercase.
◆ Decimal data type:
float (single-precision floating-point type): 32bit (reserving 7 decimal places)
double (double-precision floating-point type): 64bit (reserving 15 decimal places)
Note: If a decimal is not added with any sign , then the decimal is the data of double type by default. If it needs to be represented as float type, then you need to add f after the decimal to indicate that f is not case-sensitive.
◆ Boolean type: only true or false two values
​​boolean: 1 byte or 4 bytes
Note : If you use boolean to declare a variable of a basic type, then the variable occupies 4 bytes; if you use boolean to declare an array type , then each element of the array occupies 1 byte.
◆ Character type:
char: 2 bytes (16bit)
② Reference data type The data type of
character string is: String

class Demo3.1{
    public static void main(String[] args){     
        byte age = 120; //定义了一个byte类型的变量,变量名叫age,把120存储到了age变量中 
        age = 121;//改变变量的值      
        short money = 128;//定义了一个short类型的变量 
        int bossMoney = 1000000000;//定义了一个int类型的变量          
        long  allMoney = 10000000000000000L;//定义了一个long类型的变量    

        //存储小数
        float f = 3.14f;
        double d = 3.1415926537;
        boolean b = false;          
        char c = 'a';
        String str = "Hello World";
        System.out.println(str); //需要获取一个变量存储的数据,只需要使用变量名即可
    }
}

5. Escape characters
Special characters use "\" to convert them into their own output, then the characters using "\" are called transfer characters.

escape character explain
\r Equivalent to pressing Enter, move the cursor to the first position of a line
\n means newline
\t The tab character is equivalent to the Table key. In order to align a column, a tab is generally equal to 4 spaces
\b Backspace key, equivalent to BackSpace
\’ apostrophe
\’’ Double quotes
\ represents an oblique span
\t The tab character is equivalent to the Table key. In order to align a column, a tab is generally equal to 4 spaces
\b Backspace key, equivalent to BackSpace

Note: If you need a newline when operating files on the Windows system, you need \r\nto use it together; if you need a newline on other operating systems, you only need it \n.

import java.io.*;
class Demo3.2{
    public static void main(String[] args) throws Exception{
        File file = new File("F:\\Demo4.2.txt");
        FileWriter out = new FileWriter(file);
        out.write("大家好\r\n");
        out.write("你们辛苦了~");
        out.close();
    }

2. Data type conversion

1. Data type conversion:
small data type > big data type [automatic type conversion]
big data type > small data type [forced type conversion]
Format of forced type conversion: small data type variable name = (small data type) big data type

2. Details to pay attention to
① All data of byte, short and char data types will be automatically converted into data of int type before operation.
② When data of two different data types are operated, the result depends on the larger data type.

3. The storage principle of negative numbers
In the computer, if the highest bit of a binary is 1, then the number must be a negative number; if the highest bit of a binary is 0, then the data must be a positive number.
However, negative numbers are stored in the computer's complement.
For example: -7 > 11111001
① First take the absolute value of the negative number, and find the binary code of the absolute value (original code)
② Invert the original code
to get the complement ③ Invert the code +1 to get the complement

class Demo3.3{
    public static void main(String[] args) {
        int i1 = 128;  //4个字节
        byte b =(byte) i1;  // 1个字节
        System.out.println(b);  // -128     
        //如果是负数,那么最高位肯定是1,正数的二进制位的最高位是0
        //sun给我们提供一个功能 Integer.tobinaryString()查看一个数据的二进制数据形式的
        System.out.println(Integer.toBinaryString(-7)); //11111001(补码)  

        //凡是byte、short 、 char数据类型数据在运算的时候都会自动转换成int类型的数据再运算             
        byte b1 = 1;
        byte b2 = 2;
        byte b3 = (byte)(b1+b2);
        System.out.println(b3); //3         
        System.out.println('a'+1); //98 

        //两个不同数据类型的数据在运算的时候,结果取决于大的数据类型
        int i2 = 10;
        long l = 20;
        i2 = (int)(i2+l); 
        System.out.println(i2);

        byte b = 10;  
        //10 是一个常量,编译器在编译的时候就能够确认常量的值了,byte b = 10,在编译到的时候,java编译器就会检查到10并没有超出byte的表示范围,所以允许赋值。
        int i3 = 10; 
        byte b = (byte)i3;  
        //java编译器在编译的时候并不能确认变量所存储的值,变量存储的值是在运行的时候才在内存中分配空间的
        System.out.println(b);
    }
}

3. Operators

1. Arithmetic operators
+, -, *, /(division), %(modulo, remainder), ++(self-increment), --(self-decrease)
connectors: Let any data be spliced ​​with strings
Among them , if the + sign When used for strings, the + sign is a connector, not an addition function.
Note : Any type of data is connected to a string using a connector, and the result is a string type of data.

class Demo3.4 {
    public static void main(String[] args){ 
        //计算机每次运算的时候只能取两个数据运算
        Syste.out.println(1+2+3 +" world"+1+2+3); // 6world123  
        //过程:3+3 +" world"+1+2+3 > 6+" world"+1+2+3 > "6world"+1+2+3

        int a1 = 10;
        int b1 = 3;
        System.out.println(a1/b1); //3  
        double a2 = 12.0;
        int b2 = 3;
        System.out.println(a2/b2); //4.0

        //在java中做取模运算的时,结果的正负号是取决于被除数。
        System.out.println("结果:"+(10%3));  // 1
        System.out.println("结果:"+(10%-3)); // 1
        System.out.println("结果:"+(-10%3)); // -1
        System.out.println("结果:"+(-10%-3)); //-1

        //后自增在jvm的运行原理:因为后自增要使用到没有+1之前的值,那么jvm会先声明一个变量用于保存没有+1之前的值。
        //原理:
        //1. int temp = i; // 声明了一个临时变量用于记录了i没有加1之前的值
        //2. 自增 i = i + 1; 此时i=1
        //3. 返回temp,用作了表达式的结果
        //i的值发生了几次变化:i = 0 > 1 > 0
        int i = 0;
        i = i++; //后自增要使用到没有+1之前的值
        System.out.println("i= "+i);//i=0
    }
}

2. Assignment operator
Assignment operator: =, +=, -=, *=, /=,%=

class Demo3.5 {
    public static void main(String[] args){ 
        int i = 10; // 把10赋予给i变量。
        i+=2;  // i = i+2; 
        System.out.println("i = "+i);//12

        byte b1 = 1;
        byte b2 = 2;
        //b2 = b2+b1; //报错。需要强制类型转换
        b2+=b1;  //b2=b2+b1;b2+=b1在编译的时候,java编译器会进行强制类型转换,不需要我们手动转换
        System.out.println("b2 : "+ b2);
    }
}

3. Comparison operators Comparison
operators all return a Boolean value
==(judging whether it is equal), !=(not equal), >(greater than), <(less than), >=(greater than or equal), <=(less than or equal to)
among them , == When comparing two basic data type data (reference type variables), the comparison is whether the values ​​stored in the two variables (the memory addresses recorded by the reference type variables) are consistent

class Demo3.6 {
    public static void main(String[] args){     
        byte b = 10;
        long l = 30;
        System.out.println(l>b); //true
        //两个不同类型的数据是否可以比较呢?可以的,但是两个不同类型的数据必须是兼用的数据
        //这个比较的过程会先把b转换了long类型的数据,然后再进行比较
        System.out.println('a'>50);//true
    }
}

4. Logical operators
Logical operators: The role of logical operators is to connect
&(and), |(or), ^(exclusive or), (not), &&(short-circuit and, double and), ||(short-circuit or , double or)
① The same and different points of short-circuit and and single-and symbols:
Same point: The result of short-circuit and operation is the same.
Difference : When using short-circuit and, if the Boolean expression on the left is false, then The Boolean expression on the right-hand side is not evaluated, which improves efficiency. When using single AND, even if the boolean expression on the left is found to be false, the Boolean expression on the right will still be evaluated.
◆ Only when the boolean expression on the left is false, the efficiency of double AND is higher than that of single AND.
② Similarities and differences between short-circuit or and single-or: the
same point: the result of the operation is the same
Difference : when using short-circuit or, when the Boolean expression on the left is found to be true, the Boolean expression on the right will not be calculated Mode. When using single or, if the left boolean expression is found to be true, the right boolean expression will still be calculated

5. Bit operators
Bit operators: bit operators directly operate on binary bits (1 is regarded as true, 0 is regarded as false)
&(and), |(or), ^(exclusive or), ~(reverse)

class Demo3.7{
    public static void main(String[] args){
        System.out.println(6&3); // 2 
        System.out.println(6|3); // 7
        System.out.println(6^3); // 5
        System.out.println(~7);  // -8
    }
}

① Rule: If operand A is XORed with the same operand twice in a row, then the result is still operand A
② Application: Encrypt data encryption (XOR) using XOR to encrypt image data

import java.io.*;
class Demo3.8{
    public static void main(String[] args) throws Exception{
        //找到图片文件
        File inFile = new File("f:\\待加密的图片.jpg");
        File outFile = new File("d:\\加密的图片.jpg");
        //建立数据通道,让图片的二进制数据流入
        FileInputStream input = new FileInputStream(inFile);
        FileOutputStream output = new FileOutputStream(outFile);
        //边读,把读到的数据异或一个数据并写出
        int content = 0;//该变量用于存储读取到的数据
        while((content = input.read())!=-1){
             //如果没有到文件的末尾,那么继续读取数据
             output.write(content^12);
        }
        //关闭资源
        output.close();
        input.close();
    }
}

③ Possible written test questions for bitwise operators:
◆ Exchange the values ​​of two variables, and no third-party variables are allowed.

class Demo3.9{
    public static void main(String[] args){
        int a = 3;
        int b = 5;      
        /*
        方式1: 定义第三方变量
        int temp = a;  //3 
        a = b; //a = 5 
        b = temp;   
        */
        /*  
        方式2:相加法, 缺点: 两个int类型的数据相加,有可能会出现超出int的表示范围      
        a = a+b;  // a =8
        b = a-b; //b = 8 - 5 = 3
        a = a-b; // a = 8 - 3 = 5
        */
        /*      
        方式3: 可以使用异或。 缺点:逻辑不清晰       
        a = a^b;  // a = 3^5
        b = a^b;  // b = (3^5)^5 = 3
        a = a^b; //  a = (5^3)^3 = 5 
        */
        System.out.println("a = "+ a+" b= "+b);
    }
}

◆ Take out a specified number of bits of binary data. It is required to read the lower 4 bits of the binary data
AND operation

6. Shift operator
<<(left shift)
rule: When an operand performs a left shift operation, the result is equal to the nth power of the operand multiplied by 2, and n is the number of bits left shifted
3<<1 = 3 * 2(1) = 6
3<<2 = 3*2(2) = 12
3<<3 = 3*2(3) = 24
>>(Right shift)
rule: When an operand performs a right shift operation, In fact, it is equal to the nth power of the operand divided by 2, n is the number of bits shifted to the right
3>>1 = 3 / 2(1) = 1
3>>2 = 3 / 2(2) = 0
>>>( Unsigned right shift)
The difference between unsigned right shift and right shift:
When performing a right shift operation, if the operand is a positive number, then the left vacancy is complemented by 0; if the operand is a negative number, then the left vacancy Bits use 1's complement.
When using unsigned right shift, both positive and negative numbers are uniformly complemented by 0.
④ Written test questions: Use the highest efficiency to calculate the result of 2 times 8. 2<<3 = 2*2(3) = 16

class Demo3.10{
    public static void main(String[] args){
        //左移
        System.out.println(3<<1); // 6 
        System.out.println(3<<2); // 12
        System.out.println(3<<3); // 24         
        //右移
        System.out.println(3>>>1); // 1 
        System.out.println(3>>>2);  //0         
    }
}

7. Ternary operator (ternary operator)
format: Boolean expression? Value 1: Value 2
Note: When using the ternary operator, be sure to use the result returned by the expression, or define a variable to receive the result returned by the expression.

class Demo3.11{
    public static void main(String[] args){
        int age = 26;
        String result = age>=18?"成年人":"未成年人";
        System.out.println(result);//成年人
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325999299&siteId=291194637