identifiers, keywords, data types

2.2 Identifiers, keywords

2.2.1 Keywords

1Classificationkeywordsmeaning
2basic typebooleanboolean
3bytebyte type
4intInteger
5shortshort integer
6longlong integer
7charcharacter
8floatfloating point
9doubledouble precision
10nullnull
11truereal
12falseFake
13
14Access controlprivateprivate
15publicpublic
16protectedunder protection
17
18Program controlbreakdirectly terminate the loop
19continueJump out of the current loop and enter the next loop
20returnreturn
21doRun, the loop body is executed at least once.
22whilewhile loop
23ifif
24elseotherwise
25forfor loop
26instanceofDetermines the class to which the object belongs.
27switchswitch statement
28casemark each branch in a switch statement
29defaultUsed to mark the default branch in a switch statement
30
31Class, method, and variable modifiersabstractdeclarative abstraction
32classdeclarative class
33extendsinherit
34finalfinal, immutable
35implementsaccomplish
36interfacedeclare interface
37nativelocal
38newcreate
39staticstatic
40strictfpstrict, precise
41synchronizedthread, synchronization
42transientshort
43volatileMember variables that can be modified asynchronously by multiple threads
44
45error handlingtrycatch exception
46catchHandling exceptions
47throwthrows an exception object
48throwsdeclares that an exception may be thrown
49
50package relatedimportimport
51packageBag
52
53variable referencesupersuperclass
54thisreference the current instance
55voidno return value
56
57reserved wordgotoJump If you don't use it, it will cause confusion in the program structure.
58conststatic
59nativelocal
60

2.2.2 Identifiers

Identifiers are used to name variables, classes, methods, and packages.

​ Identifiers usually contain: letters (az, AZ), numbers, dollar signs ($), underscores (_)

*** Naming conventions: *** Usually camel case is used. Capitalize the first letter of each word

1,Class names: usually nouns, capitalized, followed by camel case
2,Method name: usually use the verb, the first letter is lowercase, and the subsequent use of camel case
3,Variable name: the first letter is lowercase, followed by camel case
4,Constant name: all uppercase letters

Identifier Notes:

1,Identifiers must start with letters ( a~z,A~Z),dollar sign ( $),underscore (_)beginning
2,Subsequent letters can be letters ( a~z,A~Z),dollar sign ( $),underscore (_),any combination of numbers
3,Cannot use keywords as identifiers
4,Strictly case sensitive
5,no space bar
6,It is not recommended to use Chinese as an identifier

2.3 Data Types

​ Java is a strongly typed language, and the use of variables is required to strictly follow the regulations, and must be defined before use

Classification of data types:

1,Basic data categories: divided into 4 categories and 8 types
	Integer: byte,int,short,long
	Float: float,double
	Character type: char
	Boolean: boolean
2,reference data type
	string String,Arrays, classes, interfaces, Lambda

2.3.1 Basic data types

  • Integer

    • byte byte

      1,byte The data type is a 1-byte 8-bit, signed, integer represented in two's complement;
      2,The minimum value is -128(-2^7),The maximum value is 127 (2^7-1)
      3,Default value is 0
      4,byte Types are used to save space in large arrays, mainly in place of integers, byte The space occupied by the variable is only int type of quarter
      

      ​ Definition: byte b = 10;

    • short short integer

      1. short The data type is a 2-byte 16-bit, signed two's complement integer
      2. The minimum value is -32768(-2^15), The maximum value is **32767(2^15 - 1
      3. Default value is 0
      

      ​ Definition: short s = 10;

    • int integer

      1. int The data type is a 4-byte 32-bit, signed two's complement integer
      2. The minimum value is -2,147,483,648(-2^31,The maximum value is 2,147,483,647(2^31 - 1)
      2. Generally, integer variables default to int type;
      3. Default value is 0 
      

      ​ Definition: int i = 10;

    • long long integer

      1,long The data type is an 8-byte 64-bit, signed two's complement integer;
      2,The minimum value is -9,223,372,036,854,775,808(-2^63),The maximum value is 9,223,372,036,854,775,807(2^63 -1);
      3,This type is mainly used on systems that require relatively large integers;
      4,Default value is 0 L
      5,"L"In theory, case insensitive, but if written as"l"easy with numbers"1"Confusion, not easy to distinguish. So better capitalize.
      

      ​ Definition: long l = 10L;

  • Floating-point type: It is finite and discrete, with rounding errors. The result is approximately equal. The use of floating-point numbers should be avoided for comparison. For banking business, the BigDecimal tool class can be used.

    • float single precision decimal

      1,float The data type is single precision, 4 bytes 32 bits, conforming to IEEE 754 standard floating point numbers;
      2,float Save memory space when storing large floating point arrays;
      3,Default value is 0.0f;
      4,Floating-point numbers cannot be used to represent exact values, such as currency; banking can use BigDecimal Tools
      

      ​ Definition: float f = 10.0f

    • double double precision decimal

      1,double The data type is double precision, 8 bytes 64 bits, conforming to IEEE 754 standard floating point numbers;
      2,The default type for floating point numbers is double type;
      3,double Types also cannot represent exact values, such as currency;
      4,Default value is 0.0d;
      

      ​ Definition: double d = 10.0d

  • char character

    1,char Type is a single 2 bytes 16 bits Unicode character;
    2,The minimum value is \u0000(is 0), the maximum value is \uffff(i.e. 65, 535);
    3,char The data type can store any character;
    4,can be calculated, in essence Unicode Computation between codes.
    

    ​ Definition: char c1 = ‘a’ char c2 = ‘medium’

  • boolean boolean

    1,boolean The data type represents one bit of information;
    2,There are only two values: true (1)and false(0);
    3,This type is only recorded as a flag true/false Happening;
    4,The default value is false;
    5,Boolean is used for logical operations, conditional control statements, loop statements, etc.
    

2.3.2 Basic type conversion

​java is a strongly typed language. Data types with a small range of numbers can be automatically converted to data types with a large range. However, conversion of large-scale data into small-range data requires forced type conversion, and large values ​​are automatically represented to the range during calculation. data type promotion.

Notice:

1,Boolean values ​​do not participate in type conversions
2,Cannot convert object type to unrelated type
3,Converting large-scale data into small-scale data requires`coercion`   (type)value
4,There is a memory overflow problem in the forced conversion, which is easy to affect the precision
5,Float-to-integer conversions are obtained by discarding decimals, not rounding

2.3.3 Reference data types

String

Strings are objects in Java, and Java provides the String class to create and manipulate strings.

Creation of the string:

1,String str1 = "name";    //Creates a string and the compiler automatically creates a String object with the value
2,String str2 = new String("name");		//Create a String object with new
//new will create a new object each time, and if the string created by String has the same value, it will point to the same object each time
//The String class is immutable, so once you create a String object, its value cannot be changed,
//Reassignment just changes the stored data address

Interview questions:

Is String the most basic actual type?
​ **Answer: **No, the basic data types are: byte, short, int, long, float, double, Boolean, char8
The Java.lang.String class is final, so String cannot be inherited and modified. So in order to improve efficiency and save space, use the StringBuffer class

Interview questions:

​ The difference between String, StringBuffer, and StringBuilder
​ **Answer:** These three classes are used to manipulate strings, but the String class is a final type and the content cannot be changed. The StringBuffer and StringBuilder classes can be modified.
​ StringBuilder is efficient, but thread-insecure. If a string variable is defined in a method, it can only be used by one thread
​ StringBuffer is thread-safe. If member variables are defined in the class, and the instance object is used in a multi-threaded environment, this class is used.

Action string:

1,Concatenation of strings:
    use directly'+'to concatenate strings
    
2,Get string length:
    str.length();

3,Get characters in a string:
    str.charAt(i);		//i is the index position of each character within the string starting at 0 and ending at length-1

4,compare strings
    Do not ignore letter case: str1.equals(str2);
	Ignore letter case: str.equalsIgnoreCase(str2);

5,Get the position of a character:
    Find the first occurrence of a specified character: str.indexOf("specified character")
	from the specified location(int)Start looking for the first occurrence of the specified character: str.indexOf("specified character",int)
    Find the last occurrence of a specified character: str.lastIndexOf("specified character")
    from the specified location(int)Start looking forward to the first occurrence of the specified character: str.lastIndexOf("specified character",int);

6,String interception:
    Cut from the specified position to the end: str.subString(int)
    Cut from the specified position to the specified position: str.subString(int1,int2);

7,Remove spaces:
    Remove leading spaces: str.trim()
    Remove all spaces: str.replaceAll("//s","");

8,Modify the specified character in a string
    Replace all matching strings with a new string: str.replaceAll("raw string","new string")
    Convert specified characters to other characters: str.replace('original character','new character')
    Replace the first string that matches the specified string with a new string, and the subsequent ones remain unchanged: str.replaceFirst("raw string","new string");

9,Determine the beginning and end of a string (returns a boolean value):
    Determine if a string starts with**beginning: str.startsWith("**")
    Determine if the string starts at the specified position with**beginning: str.startsWith("**",int)
    Determine if a string starts with**end: str.endsWith("**");

10,Case conversion in strings:
    Uppercase to lowercase: str.toLowerCase()
    Lowercase to uppercase: str.toUpperCase();

11,Split the string:
    Split by specified characters: str.split('delimiter')
    Split the specified number of times with the specified character: str.split('delimiter',int);

12,Check if it is an empty string:
    str.isEmpty();

13,Formatting of strings:
    String str = String.formart("",);	//Similar to formatted printing
array

​ Data is an ordered combination of data of the same type.

Basic Features:

1,The length of the array cannot be changed after it is defined, the array is bounded[0,length-1],So in the process of use, you often encounter the exception that the array subscript is out of bounds
2,The type of an array cannot be changed after it is defined, and the elements stored inside must be the same
3,Arrays can be defined as any data type
4,The array is a reference type, the object is stored in the heap, the data is stored in the stack, and the stored data is the address

Arrays class:

​ Located in the java.util package, it mainly contains various methods for manipulating arrays

​ Commonly used functions:

1,print array elements   toString
    Arrays.toString(array name);			//one-dimensional array
	Arrays.deepToString(array name);		//Multidimensional Arrays
2,Array elements are sorted in ascending order: sort
    Arrays.sort(array name);	
3,Fill value: fill
    Arrays.fill(array name,value);		//Fills all elements of an array with the specified value
	Arrays.fill(array name,start,end,value);	//The elements with the subscript [start,end] of the array are all filled with the specified value
4,Compare arrays: equals 
    Arrays.equals(array 1, array 2);
	

Bubble Sort:

public class BubbleSort {
    public static void main(String[] args) {
        int arr[] = {26,15,29,66,99,88,36,77,111,1,6,8,8};
        for(int i=0;i < arr.length-1;i++) {//The outer loop controls the number of sorting passes
            boolean flag = false;	//Judging by Boolean value can reduce a certain number of cycles
            for(int j=0; j< arr.length-i-1;j++) {//The inner loop controls how many times to sort each pass
                // Swap small values ​​to the front
                if (arr[j]>arr[j+1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    flag = true;	//If judged, flag is true
                }
            }
            if(!flag){
                break;
            }
        }
        System.out.println("Final sorting result:");
        for(int a = 0; a < arr.length;a++) {
            System.out.println(arr[a] + "\t");
        }
    }
}

2.3.4 Enumeration

​ Enumeration type is part of the new features in Java 5. It is a special data type. It is both a class type and has more special constraints than class types, but the existence of these constraints also creates The simplicity, safety, and convenience of enumeration types.

​ The keyword we use when defining enumeration types is enum

//Enumeration type, use the keyword enum to define constants from Monday to Sunday
enum Day {
    MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
//direct quote
Day day =Day.MONDAY;

Tags: Java

Posted by mistercash60000 on Fri, 03 Jun 2022 06:14:32 +0530