Java language basics (variables, data types)

Table of contents

Java language basics

1. The concept of variables

2. Definition and use of variables

3. Data type

3.1 Overview

3.2 Basic data types

3.3 Reference data types

4. Type conversion

5. Operators

5.1 Arithmetic operators

5.2 Unary operator (unary operator)

5.3 Assignment operator

5.4 Relational operators

5.5 Logical operators

5.6 Ternary operator

6. Expression

7. Result types of multiple types of mixed operations

8. Console input

Java language basics

1. The concept of variables

A variable is a storage space in computer memory and is the basic unit for storing data.

element:

  • Data type is used to define the range of content that can be stored.

  • The variable name is used to locate the content to be operated.

  • value, the final content stored.

  • Hidden elements: address,

2. Definition and use of variables

1. Declare first, then assign value

public class Test1 {
    public static void main(String[] args) {
        // 先声明
        int num; // int类型,整数,num变量名
        // 后赋值,使用=作为赋值符号
        num = 5;
        
        // 打印变量中的值
        System.out.println(num);
    }
}

Note: Java is a strongly typed language, and the type of the variable must be consistent with the assigned value type.

2. Assign value while declaring

public class Test1 {
    public static void main(String[] args) {
        // 声明的同时赋值
        int num1 = 10;
        // 打印变量中的值
        System.out.println(num1);
    }
}

3. Multiple variables of the same type are declared and assigned at the same time (not recommended)

public class Test1 {
    public static void main(String[] args) {
        // 多个变量同时声明并赋值(不推荐使用)
        int n1 = 3, n2 = 5, n3 = 7, n4 = 9;
        System.out.println(n1);
        System.out.println(n3);
    }
}

3. Data type

3.1 Overview

Java is a strongly typed language.

Types are divided into two broad categories:

  • Basic data types

    • integer

    • decimal

    • Boolean

    • character

  • Reference data type

    • string

    • array

    • Custom types and system-defined types

3.2 Basic data types

3.2.1 Integers

byte: byte type, 1 byte, -128 ~ 127, -2^7 ~ 2^7-1

short: short type, 2 bytes, -32768 ~ 32767, -2^15 ~ 2^15-1

int: int type, 4 bytes, -2147483648 ~ 2147483647, -2^31 ~ 2^31-1

long: long type, 8 bytes, -2^63 ~ 2^63-1

// 整数类型
public class Test1 {
    public static void main(String[] args) {
        // byte类型,1字节,-128 ~ 127,-2^7 ~ 2^7-1
        byte num = -128;
        System.out.println(num);
        
        // short类型,2字节,-32768 ~ 32767,-2^15 ~ 2^15-1
        short num2 = 32767;
        System.out.println(num2);
        
        // int类型,4字节,-2147483648 ~ 2147483647,-2^31 ~ 2^31-1
        int num3 = 2147483647;
        System.out.println(num3);
        
        // long类型,8字节,-2^63 ~ 2^63-1
        long num4 = 9223372036854775807L;
        System.out.println(num4);
        
        // 注意:程序中直接使用的整数默认为int类型,
        // 所以当需要写一个长整形时需要在数字的最后加一个字母L(大小写均可)
    }
}

Note: The integers used directly in the program default to int type, so when you need to write a long integer, you need to add a letter L at the end of the number (both upper and lower case)

3.2.2 Decimals (floating point numbers)

float: single-precision floating point number, 4 bytes, negative number range: -3.4E38~-1.4E-45, positive number range: 1.4E-45~3.4E38

double: double-precision floating point number, 8 bytes, negative number range: -1.7E308~-4.9E-324, positive number range: 4.9E-324~1.7E308

// 小数类型
public class Test2 {
    public static void main(String[] args) {
        // float,单精度浮点数,4个字节, 负数的范围:-3.4E38~-1.4E-45,正数范围:1.4E-45~3.4E38
        float f1 = 34795.9375678F;
        System.out.println(f1);
        
        // double,双精度浮点数,8个字节,负数的范围:-1.7E308~-4.9E-324,正数范围:4.9E-324~1.7E308
        double d1 = 3.1415926535897932384626;
        System.out.println(d1);
        
        // 浮点数不精确
        System.out.println(1.0-0.9);
        // 注意:小数默认是double,如果要定义一个float,需要在数字最后加上字母F(大小写均可)
    }
}

Notice:

  • The default decimal value is double. If you want to define a float, you need to add the letter F at the end of the number (both uppercase and lowercase)

  • Floating point arithmetic is not precise

  • float has a larger range than long

3.2.3 Boolean

boolean: Boolean type, boolean, two values, true or false, 1 byte

// 布尔类型
public class Test3 {
    public static void main(String[] args) {
        // 布尔类型,boolean,两个值,真true或假false,1个字节
        boolean b = true;
        b = false;
        b = 5 > 3; // 用表达式赋值
        System.out.println(b);
        // 注意:boolean类型不能参与运算,不能转换成其他类型
    }
}

Note: The boolean type cannot participate in operations and cannot be converted to other types.

3.2.4 Characters

Character encoding, character set:

ASCII: American Standard Information Interchange Code, 1 byte, the low bits represent alphanumeric characters, and the high bits represent tab characters.

GB2312: Simplified Chinese, using 2 bytes and using part of the high bits.

GBK: Simplified Chinese, wider than GB2312, using 2 bytes and using most of the high bits.

GB18030, which covers a wider range of Chinese, also includes the scripts of ethnic minorities.

Unicode: Universal code, using 2 bytes to represent characters in Java.

UTF-8: Unified transmission format, using 1 byte to represent English and 3-4 bytes to represent other national characters.

Note: The reason for garbled characters is that the input character encoding is inconsistent with the output encoding.

// 字符类型
public class Test4 {
    public static void main(String[] args) {
        // 字符类型,2个字节,万国码,使用单引号表示,可以作为数字表示,范围为0~65535
        char ch = 'A';
        int n = 'A';
        char ch1 = 65; // 字符A
        System.out.println(ch);
        
        char ch2 = '中';
        // \\u表示万国码
        char ch3 = '\u4f01';
        System.out.println(ch3);
    }
}

Escape characters:

\nnewline

\ta tab character

\\represents a\

\'Represents a single quote

\"Represents double quotes

// 字符类型
public class Test4 {
    public static void main(String[] args) {
        // 转义字符,
        char ch5 = '\n'; // 换行
        System.out.print(ch5);
        char ch4 = '\'';
        System.out.println(ch4);
        char ch6 = '\t';
        char ch7 = 'a';
        System.out.print(ch6);
        System.out.print(ch7);
    }
}

3.3 Reference data types

All non-basic data types are called reference data types. For example: string, array, custom type, etc.

The string type is a type that comes with the system. It can be composed of multiple characters and is quoted using double quotes.

// 字符串类型
public class Test5 {
    public static void main(String[] args) {
        // 字符串,可以由多个字符组成,使用双引号,内容长度可以为0或者多个
        String str = "Hello    world";
        char ch = 'n';
        System.out.println(str);
    }
}

4. Type conversion

1. Automatic type conversion

  • Type compatible

  • The target type range is larger than the source type

2. Forced type conversion

  • Type compatible

  • The target type range is smaller than the source type

// 自动类型转换
public class Test6 {
    public static void main(String[] args) {
        // 整数的类型转换
        
        short sh = 234;
        // 将sh变量中的值赋值给变量n
        int n = sh; // 自动类型转换
        System.out.println(n);
        
        byte b = 120;
        short s1 = b;
        
        long l = n;
        
        char ch = 'B';
        int n1 = ch;        
    }
}
// 强制类型转换
public class Test7 {
    public static void main(String[] args) {
        // 整数的类型转换
        
        int n = -129;
        // 强制类型转换,如果该值能够存入对应的类型,则无损存入,
        // 如果超出范围,则会进入一个环,超出最大值变为最小值,超出最小值变为最大值
        byte b = (byte)n; // 结果为127
        
        System.out.println(b);
    }
}

Convert between integers and decimals:

// 类型转换
public class Test8 {
    public static void main(String[] args) {
        // 整数和小数的转换
        // 将整数放入到小数中,自动类型转换
        long l = 3472393742942342347L;
        float f = l;
        System.out.println(f);
        
        // 将小数放入到整数中,强制类型转换
        double d = 3.54;
        int n = (int) d;
        System.out.println(n);
    }
}

5. Operators

5.1 Arithmetic operators

Addition, subtraction, multiplication, division, remainder

Note: The result of dividing an integer by an integer is still an integer. The remainder can be calculated using decimals, negative numbers, etc.

// 算术运算符
public class Test9 {
    public static void main(String[] args) {
        // +
        int n = 5 + 3 + 2; // 将5+3的结果赋值到n中
        System.out.println(n);
        // 注意:+还可以用来做字符串拼接
        String str = "hello";
        String str1 = "world";
        String str2 = str + str1;
        System.out.println(str2);
        System.out.println("hello, " + "world" + "!!!");
        System.out.println(str + ",tom");
        System.out.println(str + n); // 所有的类型与字符串相加,都是拼接
        
        // -
        int n1 = 10 - 4;
        System.out.println(n1);
        
        // *
        int n2 = 6 * 6 * 6;
        System.out.println(n2);
        
        // /
        // 注意:在Java中整数除以整数,结果仍是整数
        int n3 = 5 / 2; // 除
        System.out.println(n3); // 结果为2
        
        // 求余  %,优先级与乘除一样
        int n4 = 10 % 3;
        System.out.println(n4);
        double d1 = 4.8 % 2.2;
        System.out.println(d1);
        int n5 = -10 % 3;
        System.out.println(n5);
        int n6 = 10 % -3;
        System.out.println(n6);
        int n7 = -10 % -3;
        System.out.println(n7);
    }
}

5.2 Unary operator (unary operator)

It means that only one variable can be used.

++:increment by 1

--: Decrease by 1

// 单目运算符
public class Test10 {
    public static void main(String[] args) {
        // ++,自增1
        int n1 = 5;
        n1++;
        System.out.println(n1);
        
        int n2 = 5;
        ++n2;
        System.out.println(n2);
        
        // --,自减1
        int n3 = 5;
        n3--;
        System.out.println(n3);
        
        int n4 = 5;
        --n4;
        System.out.println(n4);
        
        int m1 = 5;
        // ++ 如果在后面,先将值拿出用来参与运算,后自增1
        int m2 = m1++ + 5;
        // ++ 如果在前面,先自增1,后将结果拿出用来参与运算
//      int m2 = ++m1 + 5;
        System.out.println(m2);
        System.out.println(m1);
        
        int m3 = 5;
        // m4 = 5 + 6 + 7;
//      int m4 = m3++ + m3++ + m3++;
        // m4 = 5 + 6 + 5 + 6 + 5;
//      int m4 = m3++ + m3-- + m3++ + m3-- + m3++;
        // m4 = 5 + 6 + 6 + 6 + 5;
        int m4 = m3++ + m3-- + (++m3 + m3--) + m3++;
        System.out.println(m4);
        System.out.println(m3);
    }
}

5.3 Assignment operator

Calculate first, assign later

// 赋值运算符
public class Test11 {
    public static void main(String[] args) {
        // =
        int n = 5;
        n += 6; // 等同于n = n + 6;
        System.out.println(n);
        int m = 6;
        m++; // 自增1,相当于m = m + 1;
        m+=2; // 自增2
        
        int m1 = 4;
        m1 -= 5; // 自减5,相当于m1 = m1 - 5;
        
        int m2 = 6;
        m2 *= 3; // 相当于m2 = m2 * 3;
        
        int m3 = 3;
        m3 /= 2; // 相当于m3 = m3 / 3;
        System.out.println(m3);
        
        int m4 = 6;
        m4 %= 4; // 相当于m4 = m4 % 4;
        System.out.println(m4);
        
        // b++和b+=1会隐式类型转换,而b=b+1需要强制类型转换
        byte b = 127;
        // b++; 与 b += 1; b = b + 1;
        b++;
        System.out.println(b);
    }
}

Classic interview questions:

byte b = 1;

What is the difference between b++; and b = b + 1;?

Answer: b++ and b+=1 will perform implicit type conversion, while b=b+1 requires forced type conversion, otherwise an error will be reported.

5.4 Relational operators

Notice:

  • ==Equal, not equal to!=

  • boolean b3 = 10 > n2 > 5; // Code error, continuous comparison cannot be performed

// 关系运算符
public class Test12 {
    public static void main(String[] args) {
        // >、<、>=、<=与数学中一样
        boolean b = 5 >= 3;
        System.out.println(b);
        
        int n = 5;
        boolean b1 = n == 5; // 等于
        System.out.println(b1);
        boolean b2 = n != 5; // 不等于
        System.out.println(b2);
        
        int n2 = 7;
        
    
        // 注意:==等于,不等于是!=,
        //      boolean b3 = 10 > n2 > 5; // 不能连续比较
    }
}

5.5 Logical operators

// 逻辑运算符
public class Test13 {
    public static void main(String[] args) {
        // and
        int n = 7;
        boolean b = n > 5 && n < 10; // 并且,两个条件同时成立
        System.out.println(b);
        
//      boolean b1 = n > 5;
//      boolean b2 = n < 10;
//      boolean b3 = b1 && b2;
        
        boolean b1 = n > 5 || n < 7; // 或者,两个条件有一个成立即可
        
        // 注意:&& 和 || 有短路的特征。
        // 如果前面一个表达式能表示整个结果,那么后面的表达式不会执行判断
        // & 和 | 计算结果与&&和||相同,但是无论如何都会计算两边的表达式的结果
        
        int n1 = 5;
        boolean b2 = n1 > 3 || n1 / 0 == 3; // 只用|,会计算两边,代码会报错,使用||,代码不会报错,后面的不会计算
        System.out.println(b2);
        
        boolean b3 = !(n1 > 3);
        System.out.println(b3);
        
        // 用来进行算术运算
        int n2 = 5 & 3;
        System.out.println(n2);
    }
}

Classic interview questions:

What is the difference between && and & (|| and |)?

answer:

&& and || have short circuit characteristics. If the previous expression can express the entire result, then the subsequent expression will not perform judgments & and |. The calculation results are the same as && and ||, but the results of the expressions on both sides will be calculated anyway.

&& and || can only be used as logical operations, while & and | can also be used as arithmetic operations.

5.6 Ternary operator

Syntax: Boolean expression? Result 1: Result 2

When the Boolean expression is true, return result 1, otherwise return result 2

// 三目(三元)运算符
public class Test14 {
    public static void main(String[] args) {
        // ? : 
        // 布尔表达式?结果1:结果2
        // 当布尔表达式为true时,返回结果1,否则返回结果2
        int hp = 250;
        String str = hp > 200 ? "撤退" : "越塔强杀"; 
        System.out.println(str);
        
        int n = hp < 100 ? 3 : 2;
        System.out.println(n);
    }
}

6. Expression

Expression: A variable or literal value connected by an operation that can calculate a result, but is not an independent line of code.

For example: n > 5, a + b

7. Result types of multiple types of mixed operations

  • When basic data participates in the operation, the result is the variable type with the largest range,

  • If multiple operands are of type byte or short, the result is int.

Note: The order of the four mixed operations will also be followed. Finding remainder precedence is equivalent to multiplication and division.

If a string is used with +, the result is a string.

// 混合运算
public class Test15 {
    public static void main(String[] args) {
        double d = 5 / 2; // 2.0
        System.out.println(d);
        
        System.out.println("结果为:" + 5 + 2); // 结果为:52
        
        System.out.println("hello, " + 'A' + 1); // hello, A1
    }
}

8. Console input

Receive console input:

import java.util.Scanner;
// 控制台输入
public class Test16 {
    public static void main(String[] args) {
        // 创建一个控制台扫描对象,用来接收控制台的输入
        Scanner input = new Scanner(System.in);
        
        System.out.println("请输入一个字符串:");
        // nextLine()上面不能有接收整数
        // next()不识别空格
        String str = input.nextLine(); 
        System.out.println(str);
        
        System.out.println("请输入第一个整数:");
        // 接收输入的整数
        int n1 = input.nextInt();
        System.out.println("请输入第二个整数:");
        int n2 = input.nextInt();
        System.out.println("结果为:" + (n1 + n2));
    }
}

Guess you like

Origin blog.csdn.net/asdf12388999/article/details/127117244