Fundamentals of Java syntax

Posted by PHPAnx on Sat, 01 Jan 2022 02:13:30 +0100

notes

In the Java language, there are three ways to annotate:

  1. Single line comment: / / comment content
  2. Multiline comment: / * comment content*/
  3. Document comments: / * * comment content*/

Example:

/**
 * (Document comments)
 * @Description HelloWorld
 * @Author Vivid sky
 */
public class HelloWorld {
    public static void main(String[] args) {
        //(single line comment) the function of this program is to output Hello, world!
        System.out.println("Hello, world!");
        /*
        (Multiline comment)
        The function of this program is to output Hello, world!
        */
    }
}

identifier

Definition: all components of Java need names. Class names, variable names, and method names are all called identifiers.

be careful:

  • All identifiers should start with letters (a-z or a-z), dollar sign ($), or underscore ()
  • The first character can be followed by any combination of letters (a-z or a-z), dollar sign ($), underscore () or numbers
  • Keywords cannot be used as identifiers
  • Identifiers are case sensitive
  • It can be named in Chinese, but it is highly recommended
  • Examples of legal identifiers: age, $salary_ value,__ 1_value
  • Examples of illegal identifiers: 123abc, - salary

Example:

public class Demo01 {
    public static void main(String[] args) {
        String hello = "Hello, world!";     //Start with a lowercase letter, correct
        String Hello = "Hello, world!";     //Start with a capital letter, correct
        String $Hello = "Hello, world!";    //Start with dollar sign, correct
        String _Hello = "Hello, world!";    //Begin with an underscore, correct
        String Hello123 = "Hello, world!";  //Use numbers in non beginning positions, correct

        //String 123Hello = "Hello, world!";    // Error starting with number
        //String #Hello = "Hello, world!";      // Start with pound sign, error
        //String *Hello = "Hello, world!";      // Error starting with asterisk

        String The Scripture of Ethics = "Dao Kedao, extraordinary Dao.";      //In Chinese, it can be passed, but it is highly recommended
    }
}

data type

Java is a strongly typed language. There are two types of data in Java:

  1. Basic type
  2. reference type

There are four basic data types:

  1. Integer type: byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes)
  2. Floating point type: float (4 bytes), double (8 bytes)
  3. Character type: char (2 bytes)
  4. boolean: boolean (1 bit)

There are three types of reference data:

  1. class
  2. Interface
  3. array

Example:

public class Demo02 {
    public static void main(String[] args) {
        //Eight basic data types
        //integer
        int num1 = 10;      //Most commonly used
        byte num2 = 20;
        short num3 = 30;
        long num4 = 30L;    //The long type adds the capital letter L at the end of the number
        //Floating point number
        float num5 = 3.14159F;      //For float type, add F at the end of the number
        double num6 = 3.14159;
        //character
        char a = 'A';
        //Boolean value
        boolean flag1 = true;
        boolean flag2 = false;
    }
}

Among them, integers can also be expressed in different hexadecimals:

  • Binary: beginning with 0b
  • Octal: beginning with 0
  • decimal system
  • Hex: beginning with 0x

Example:

public class Demo03 {
    public static void main(String[] args) {
        int num1 = 10;      //decimal system
        int num2 = 0b10;    //Binary starts with 0b
        int num3 = 010;     //Octal starts with 0
        int num4 = 0x10;    //Hex starts with 0x
        System.out.println(num1);   //Output 10
        System.out.println(num2);   //Output 2
        System.out.println(num3);   //Output 8
        System.out.println(num4);   //Output 16
    }
}

In addition, floating-point types should not be used as comparison objects because of precision and overflow problems.

Example:

public class Demo03 {
    public static void main(String[] args) {
        float f1 = 2313467468515648F;
        float f2 = f1 + 1;
        System.out.println(f1==f2);     //Clearly f2=f1+1, but still output true, that is, f1 is equal to f2
    }
}

The character type is still an integer in nature.

Example:

public class Demo03 {
    public static void main(String[] args) {
        char c1 = 'a';                  //Assigned as a
        System.out.println(c1);         //Output a
        System.out.println((int)c1);    //Output 97
        char c2 = 'in';                 //Assigned as medium
        System.out.println(c2);         //In output
        System.out.println((int)c2);    //Output 20013
        char c3 = 97;                   //Direct integer assignment
        System.out.println(c3);         //Output a
        char c4 = '\u0061';             //Escape to unicode encoding
        System.out.println(c4);         //Output a
    }
}

Type conversion

Because Java is a strongly typed language, type conversion is required in the mixed operation of some integer, floating point and character data. Different types of data are first converted to the same type, and then calculated.

low  --------------------------------------->  high
byte/short/char —> int —> long—> float —> double

The following points should be paid attention to when converting data types:

  • Boolean cannot be type converted.
  • Object types cannot be converted to unrelated types.
  • Automatic type conversion occurs when a type with small capacity is converted to a type with large capacity.
  • Cast must be used when converting a high-capacity type to a low-capacity type.
  • Overflow or loss of accuracy may occur during conversion.

Example:

public class Demo04 {
    public static void main(String[] args) {
        //High - > low cast (type) variable name
        int num1 = 128;
        byte num2 = (byte)num1;
        System.out.println(num2);   //Memory overflow, output - 128

        //Low - > high automatic type conversion
        double num3 = num1;
        System.out.println(num3);   //Output 128.0

        //Precision loss
        float f = 3.5F;
        double d = 3.5;
        System.out.println((int)f);      //Output 3
        System.out.println((int)d);      //Output 3

        //For the type transformation in calculation, it should be transformed first and then calculated
        int money = 10_0000_0000;       //You can use underline division arbitrarily in integers
        int years = 20;
        int total1 = money*years;
        System.out.println(total1);     //Output - 1474836480, i.e. result overflow
        long total2 = money*years;
        System.out.println(total2);     //Output - 1474836480, i.e. result overflow
        long total3 = money*((long)years);
        System.out.println(total3);     //Output 2000000000, i.e. the result is correct
    }
}

variable

In the Java language, all variables must be declared before use. The basic format of declaring variables is as follows:

type varname [ = value] [, varname[= value] ...];
//Type variable name = value; You can declare multiple variables of the same type at the same time separated by commas, but this is not recommended

matters needing attention:

  • Each variable has a type, which can be a basic type or a reference type.
  • Variable name must be a legal identifier.
  • Variable declaration is a complete statement, so each declaration must end with a semicolon.
  • Try to follow the hump principle of lowercase initial letters for variable names, such as num, lastName, redApple and studentsNameList.

Example:

public class Demo05 {
    public static void main(String[] args) {
        int num = 123;
        String name = "Vivid sky";
        char x = 'X';
        double pi = 3.14159;
    }
}

The variable types supported by the Java language are:

  • Class variable: a variable independent of the method and decorated with static.
  • Instance variable: a variable independent of the method without static modification.
  • Local variable: a variable located in a method.

Example:

public class Demo06 {
    //Instance variable: subordinate to object. No initialization is required and default values will be assigned.
    int a;          //The default value for integer types is 0
    boolean b;      //The default value for Booleans is false
    String c;       //The default value of the reference type is null

    //Class variable: subordinate to class. Use static modifier. No initialization is required and default values will be assigned.
    static int d;

    //main method 
    public static void main(String[] args) {
        //Local variable: must be declared and initialized
        int i = 10;
        System.out.println(i);

        //Instance variable
        Demo06 demo06 = new Demo06();   //You need to create an instance
        System.out.println(demo06.a);   //Output 0
        System.out.println(demo06.b);   //Output false
        System.out.println(demo06.c);   //Output null
        demo06.a = 10;
        System.out.println(demo06.a);   //Output 10
        demo06.b = true;
        System.out.println(demo06.c);   //Output true
        demo06.c = "Vivid sky";
        System.out.println(demo06.c);   //Output vivid

        //Class variable
        System.out.println(d);          //Output 0
        d = 12;
        System.out.println(d);          //Output 12
    }
}

constant

Definition: a constant is a value that cannot be changed again after initialization. Constant names generally use uppercase characters and underscores. The basic declaration format is as follows:

final Type constant name = value;
//For example: final double PI = 3.14;

Example:

public class Demo07 {

    //static and final are modifiers, and there is no order
    static final double PI = 3.14;

    public static void main(String[] args) {
        System.out.println(PI);     //Output 3.14
    }
}

operator

The Java language supports the following operators:

  • Arithmetic operators: +, -, *, /,%, + +--
  • Relational operators: >, <, > =, < =, = =,! = instanceof
  • Bitwise operators: &, |, ^, ~, > >, <, > > >
  • Logical operators: & &, |!
  • Assignment operators: =, + =, - =, * =/=
  • Conditional operator:?:
  • Other Operators

Arithmetic operator

Example:

package operator;

public class Demo01 {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 30;
        int d = 40;

        //Binary operator
        System.out.println(a+b);            //Addition operation, output 30
        System.out.println(b-c);            //Subtraction, output - 10
        System.out.println(c*d);            //Multiplication, output 1200
        System.out.println(a/(double)d);    //Division operation, output 0.25
        System.out.println(d%c);            //Remainder operation, output 10

        //Unary operator
        System.out.println(a);      //Output 10
        System.out.println(a++);    //Output 10. When + + is later, it is calculated first and then increased automatically.
        System.out.println(a);      //Output 11
        System.out.println(++a);    //Output 12. When + + comes first, it increases first and then operates.

        //Operation using Math class
        double e = Math.pow(2, 3);
        System.out.println(e);      //Output 8, that is, the third power of 2
        int f = Math.abs(-5);
        System.out.println(f);      //Output 5, i.e. the absolute value of - 5
    }
}

Relational operator

Example:

package operator;

public class Demo02 {
    public static void main(String[] args) {
        //The return result of relational operation is Boolean, that is, the result is only true or false
        int a = 10;
        int b = 20;
        System.out.println(a>b);    //Output false
        System.out.println(a<b);    //Output true
        System.out.println(a==b);   //Output false
        System.out.println(a!=b);   //Output true
    }
}

Logical operator

Example:

package operator;

public class Demo03 {
    public static void main(String[] args) {
        //Logical operator
        //And (and) or (or) not (not)
        boolean a = false;
        boolean b = true;
        System.out.println(a&&b);   //Output false. Logic and operation: if both are true, the result is true.
        System.out.println(a||b);   //Output true. Logical or operation: if one of the two is true, the result is true.
        System.out.println(!a);     //Output true. Logical non operation: true becomes false, and false becomes true.

        //Short circuit operation
        int c = 5;
        boolean d = (c<4)&&(c++<4);
        System.out.println(d);      //Output false
        System.out.println(c);      //Output 5 indicates that C + + < 4 has not been executed, and the statement is "short circuited"
    }
}

Bitwise Operators

Example:

package operator;

public class Demo04 {
    public static void main(String[] args) {
        //Bit operation
        /*
         * set up
         * A = 1101 0001
         * B = 0110 1000
         * be
         * A&B = 0100 0000   Bitwise sum operation
         * A|B = 1111 1001   Bitwise OR operation
         * A^B = 1011 1001   Bitwise exclusive or operation, that is, inequality is 1 and equality is 0
         * ~B = 1001 0111    Bitwise inversion
         * */

        /*
        Title: how to calculate 2 * 8 fastest?
        Idea: 2 * 8 = 2 * 2 * 2 * 2
        0000 0000       0
        0000 0001       1
        0000 0010       2
        0000 0011       3
        0000 0100       4
        0000 1000       8
        0001 0000       16
        <<It is a left shift, and each left shift is equivalent to the value * 2, but the efficiency is very high
        >>It is a right shift. Each right shift is equivalent to the value / 2, but it is very efficient
         */
        System.out.println(2<<3);       //Output 16
    }
}

Assignment Operators

Example:

package operator;

public class Demo05 {
    public static void main(String[] args) {
        int a = 10;
        int b = 10;
        a += b;                     //Equivalent to a = a + b;
        System.out.println(a);      //Output 20
        a -= b;                     //Equivalent to a = a - b;
        System.out.println(a);      //Output 10
        a *= b;                     //Equivalent to a = a * b;
        System.out.println(a);      //Output 100
        a /= b;                     //Equivalent to a = a / b;
        System.out.println(a);      //Output 10
    }
}

Conditional operator

Example:

package operator;

public class Demo06 {
    public static void main(String[] args) {
        //Conditional operator a? b : c
        //If a is true, execute b; otherwise, execute c
        int score = 50;
        String mark = score>=60 ? "pass" : "fail,";
        System.out.println(mark);       //Output "fail"
    }
}

Topics: Java