Java basic programming architecture

The data type

  • In Java, the range of integers is independent of the machine on which the Java code is running, which ensures Portability.
  • Long integer values have a suffix L or L (such as 40000000L). Hexadecimal values have a prefix of 0x or 0x (such as 0xCAFE). Octal has a prefix of 0, for example 010 corresponds to an 8 in octal.
  • Starting with Java7, you can write binary numbers with the prefix 0b or 0b. For example, 0b1001 is 9. Also, starting with Java7, you can underline numeric literals, such as 1_000_000(or 0B1111_0100_0010_0100_0000) for a million. The underlining is just to make it easier to read. The Java compiler removes these underscores.
int c = 0b1001; int c1 = 3_1; System.out.println(c); // 9 system.out.println (c1);     / / output 31Copy the code
  • The vast majority of applications use double, with only a few cases where float is appropriate. Values of type float have a suffix F or F (for example, 3.14f). Floating-point values without suffixes (such as 3.14) are double by default.
  • Three special floating-point values for floating-point overflow and error cases: positive infinity, negative infinity, NaN(not a number). For example, a positive integer divided by 0 results in positive infinity. Compute the square root of 0/0 or a negative number and the result is NaN. Note: Constants double. POSITIVE_INFINITY, double. NEGATIVE_INFINITY, and double.nan.
if(Double.isNaN(x))          //check whether x is "not a number"
Copy the code
  • The char type was originally used to represent a single character. But things have changed. Today, some Unicode characters can be described by a single CHAR value, while others require two char values.
  • Bitwise operators: When working with integer types, you can operate directly on the bits that make up the value of an integer. This means that you can use the mask technique to get the bits in the integer. Bitwise operators include:
& ("and") | ("or") ^ ("xor") ~ ("not")
Copy the code
  • Enumeration types:
enum Size{SMALL, MEDIUM, LARGE};
Size s = Size.MEDIUM;
Copy the code

string

substring

Substring: The substring method of the String class extracts a substring from a larger String.

String greeting = "Hello"; String s = greeting.substring(0, 3); / / to get"Hel"
Copy the code

Joining together

The Java language, like most languages, allows the + sign to concatenate two strings. If you want to group multiple strings together, separated by a delimiter, you can use the static join method

Immutable string

The String class does not provide methods to modify strings. If you want to modify, extract the desired character first, and then concatenate the substituted string.

The greeting = the greeting. The substring (0, 3) +"p!";
Copy the code

Checks whether strings are equal

You can use the equals method to check whether two strings are equal.

s.equals(t)
s.equalsIgnoreCase("hello") // Ignore case comparisonsCopy the code

Never use the == operator to check if two strings are equal! This operator can only determine if two strings are placed in the same place.

Empty and Null strings

The empty string “” is a string of length 0. You can call the following code to check if a string is empty:

if(STR. Length () = = 0) orif(str.equals(""))
Copy the code

An empty string is a Java object with its own string length (0) and content (empty). However, the String variable can also hold a special value, NULL. Indicates that no object is currently associated with this variable. Check if a string is null:

if(str == null)
Copy the code

Sometimes you check that a string is neither empty nor null

if(str ! = null && str.length() ! = 0) // First check not null. If a method is called on a null value, an error occurs.Copy the code

Build string

Sometimes you need to build strings from shorter strings. It is inefficient to use string concatenation to achieve this purpose. Each time a String is concatenated, a new String is built, which is time-consuming and wastes space. Using the StringBuilder class avoids this problem.

Note: the StringBuilder class was introduced in JDK5.0. The predecessor of this class, StringBuffer, is less efficient, but allows you to add or remove characters in a multithreaded manner. If all strings are edited in a single thread (most of the time), StringBuilder should be used instead. The API for both classes is the same

Large numerical

If basic integer and floating-point precision is not enough, you can use two useful classes in the java.Math package: BigInteger and BigDecimal. These two classes can contain numeric values for any length sequence of numbers. The BigInteger class implements integer arithmetic with arbitrary precision, and BigDecimal implements floating point arithmetic with arbitrary precision.

The static valueOf method can be used to convert an ordinary value to a large value:

BigInteger a = BigInteger.valueOf(100);
Copy the code

Unfortunately, you can’t use familiar arithmetic operators such as + and * to handle large values. Instead, use the Add and multiply methods in large values. (decrease: subtract; In addition: divide)

BigInteger c = a.add(b);          //  c = a + b
BigInteger d = c.multiply(b.add(BigInteger.valueOf(2)));      // d = c * (b + 2)
Copy the code

An array of

When declaring an array variable, you need to specify the array type (the data element type follows []) and the name of the array variable. We declare the array a as an integer:

int[] a;
Copy the code

However, this statement only declares the variable a, and does not initialize it as a true array. You should use the new operator to create an array.

int[] a = new int[100];
Copy the code

Array initialization and anonymous arrays

In Java, a simplified form of writing is provided to create array objects and assign initial values. Here’s an example:

Int [] smallPrimes =,3,5,7,11,13 {2};       // When using this statement, there is no need to call new.Copy the code

You can even initialize an anonymous array:

17,19,23,29,31,37 new int [] {};Copy the code

This notation creates a new array and initializes it with the values provided in parentheses. The size of the array is the number of initial values. This syntax allows you to reinitialize an array without creating a new variable. Such as:

17,19,23,29,31,37 smallPrimes = new int [] {};Copy the code

This is a short form of the following statement:

17,19,23,29,31,37 int [] annoymous = {}; smallPrimes = annoymous;Copy the code

Copy an array

In Java, it is possible to copy an array variable to another array variable. In this case, both variables will reference the same array:

int[] luckyNumbers = smallPrimes;
luckyNumbers[5] = 12;    // now smallPrimes[5] is also 12
Copy the code

If you want to copy all the values of an array into a new array, you use the copyOf method of the Arrays class:

int[] copiedLuckyNumbers = Arrays.copyOf(luckyNubers, luckyNumbers.length);
Copy the code

The second argument is the length of the new array. This method is usually used to increase the size of an array:

luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);
Copy the code

If the array elements are numeric, the extra elements are assigned a value of 0; If the array element is Boolean, the value is assigned to false. Conversely, if the length is less than the length of the original array, only the uppermost array element is copied.

Multidimensional array

In Java, declaring a two-dimensional array is fairly simple. Such as:

double[][] balances;
Copy the code

As with one-dimensional arrays, a multidimensional array cannot be used until it is initialized with a call to new. Here we can initialize it like this:

balances = new double[NYEARS][NRATES];
Copy the code

Irregular array

Java doesn’t actually have multidimensional arrays, only one-dimensional arrays. Multidimensional arrays are interpreted as “arrays of arrays”. Construct an array of triangular irregular matrices:

int[][] odds = new int[NMAX+1][];
for(int n = 0; n <= NMAX; n++){
    odds[n] = new int[n + 1];
}
Copy the code