0 foreword

In the next two months, we will review the core technology of Java. Although we have studied the general things, it is also good to have a thorough review and deepen the impression. We refer to the book “Java Core Volume”.

A simple Java application

public class hello { public static void main(String[] args) { System.out.println("hello lei"); }}Copy the code

This procedure is the first line of code to start Java knocking.

Includes the modifier public, the type class, and the class name Hello.

Standard class names: nouns that begin with a capital letter and have a hump.

Why a String array? String is universal as the most versatile wrapper class in Java. Everything in the universe can be interpreted as String, and String can be interpreted as everything in the universe, so using String to store parameters is naturally the best choice.

Second, the annotation

Comment information, which is eliminated during compilation, is not interpreted by the JVM

Classification:

  • Single-line comments: // Comments the text
  • Multi-line comments: /* Comments text */
  • /** Comment text */

Data types

Java is a strongly typed language that defines specific data types for each type of data and allocates different sizes of memory space in memory. There are eight basic types, including four integers, two floating-point types, one char, and one Boolean.

3.1 the integer

Integers are used to represent values that have no fractional part and are allowed to be negative.

type Storage requirements Value range
byte 1 byte – 128 ~ 127
short 2 – 15 ~ 2-2 ^ ^ 15-1
int 4 bytes – 2 ^ 31 ~ 2 ^ 31-1
Long 8 bytes – 2 ^ 63 ~ 2 ^ 63-1

Conclusion:

  1. The range of integers is independent of running Java code. This solves the problem of software portability.
  2. Integer types can be represented in binary, octal, decimal, and hexadecimal.

3.2 Floating point Type

Floating point types are used to represent values that have a fractional part. There are two floating point types in Java.

type Storage requirements Value range
float 4 bytes 3.403 e38 ~ 3.403 e38
double 8 bytes 1.798 e308 ~ 1.798 e308

Conclusion:

  1. Double is twice as accurate as float, and most applications use double.
  2. Floating point values are not suitable for financial calculations that do not accept rounding errors, so the BigDeciaml class should be used when financial indicates that no rounding errors are allowed.

3.3 the type char

The char type was originally used to represent a single character, but unicode characters can now be described by a char value. We strongly recommend against using the char type in programs.

3.4 a Boolean type

Boolean types have two values, false and true, to determine logical conditions.

Four, variables,

Each variable has a type that precedes its name when it is declared.

4.1 Variable Initialization

Once a variable has been declared, it must be explicitly initialized with an assignment statement. Never use an uninitialized variable.

Specification: It is good writing to declare variables as close as possible to where they are first used.

4.2 constant

  • Java uses the keyword final to indicate a constant; the reserved word const is not used.
  • The final keyword means that the variable can only be assigned once and cannot be changed once it has been assigned.
  • By convention, constant names are all uppercase.

5. Operators

Arithmetic operator + – * % /

Note: Dividing an integer by 0 produces an exception, whereas dividing a floating-point number by 0 produces infinity

5.1 Mathematical functions and constants

Math methods, using the Math class. For example, math. PI and math. sin

5.2 Conversion between numeric types

When a binary operation is performed on two values, the operands are first converted to the same type and then evaluated.

  • If one of the operands is of type double, the other operand is converted to type double.
  • If one of the operands is of type float, the other will be converted to float
  • If one of the operands is of type long, the other operand is converted to long
  • Otherwise, both operands are cast to int

Interview questions:

    byte b1 =3, b2=4, b;
  1.  b= b1+ b2 ;
  2.  b = 3+4;
Copy the code

In the last interview question, which one compiled wrong?

B =b+1; b=b+1; b=b+1; b=b+1; B = 3 + 4; 3 is a constant int, but Java has a constant type optimization mechanism can be directly recognized as byte; When two constants are added, the compiler evaluates the value of the constant, determines whether the type range is satisfied, and assigns the value.

5.3 Cast Type

Java runs numeric types for casts, such as:

Double x = 9.9; int nx=(int)x ;Copy the code

Thus, the value of the variable nx is 9, resulting in information loss!!

How it works: A cast converts a floating point value to an integer by truncating the fractional part.

If you want to round a floating point number to get the closest certificate, you can do this:

Double x = 9.9; int nx=(int)Math.round(x);Copy the code

Note: If you try to cast a value from one type to another outside the representation of the target type, the result will be a completely different value, such as (byte) 300, which actually has a value of 44

Byte by = 300 Decimal The binary value of 300 is 1 0010 1100 300 The value of byte is exceeded. Byte A byte containing eight bits. Take the last eight bits 0010 1100 0010 1100 sign bit as 0 and a positive number. The source and complement of a positive number are itself. So for 00101100 = 32 + 8 + 4 = 44Copy the code

5.4 Assignment and operators

Such as:

x+=4;
x*=2;
Copy the code

If the type is different from that of the operand on the left, a cast occurs.

Int x = 3; X + 3.5; ==== will set x to (int)(x+3.5)Copy the code

5.5 Increment and decrement operators

++, — are numeric variable operations, constants do not work.

5.6 Relational and Boolean operators

Java contains rich relational operators. To test for equality, use two equal signs == or! =

5.7 bit operator

1. And the operator.

The and operator is represented by the symbol “&”, which is used as follows:

The result is 1 only if the bit in both operands is 1, otherwise the result is 0, as in the following program segment.

public class data13 { public static void main(String[] args) { int a=129; int b=128; Println ("a and b and the result is: "+(a&b)); }}Copy the code

Run results a and b and the result is: 128

Here’s an analysis of the program:

The value of “A” is 129 and translated into binary is 10000001, while the value of “B” is 128 and translated into binary is 10000000. According to the operation rule of the and operator, only two bits are 1, the result is 1, and it can be known that the result is 10000000, namely 128.

2. Or operator.

Or the operator with the symbol “|”, said its operation law is as follows:

If one of the two bits is 1, the result is 1, otherwise it’s 0. Let’s look at a simple example.

public class data14 { public static void main(String[] args) { int a=129; int b=128; System. The out. Println (" or the result of a and b is: "+ (a | b)); }}Copy the code

The result of running a and B or is: 129

Analyze the program segment below:

The value of A is 129, which is 10000001 when translated into binary, while the value of B is 128, which is 10000000 when translated into binary. According to the operation rule of the or operator, only one of the two bits is 1, the result is 1, which can be known as 10000001, namely 129.

3. The operator

Non-operators are represented by the symbol “~”, and their operation rules are as follows:

If the bit is 0, the result is 1, if the bit is 1, the result is 0, so let’s do a simple example.

public class data15 { public static void main(String[] args) { int a=2; System.out.println("a is not the result: "+(~a)); }}Copy the code

4. Xor operator

The xOR operator is represented by the symbol “^” and operates as follows:

In the bits of two operands, the result is 0 if they are the same, and 1 if they are different. Let’s look at a simple example.

public class data16 { public static void main(String[] args) { int a=15; int b=2; Println ("a ^b +(a^b) +(a^b)); }}Copy the code

The xOR result of a and B is: 13

The value of a is 15, converted into binary 1111, and the value of B is 2, converted into binary 0010. According to the operation law of xOR, it can be concluded that the result is 1101, namely 13.

Vi. String

A Java string is a sequence of Unicode characters

6.1 substring

The substring method of the String class extracts a substring from one and larger strings.

String the greeting = "hello"; String s = the greeting. The substring (0, 3);Copy the code

6.2 joining together

Concatenation can be hidden by a + sign. For multiple strings, use delimiters:

String all = String.join("/","s","M","L");
all is "s/m/l"
Copy the code

6.3 Immutable Strings

The String class does not provide methods for modifying strings.

6.4 Checking Whether Strings are Equal

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

Never use the == operator to check whether two strings are equal. This string can only determine if two strings are placed in the same place. Of course, if strings are not placed in the same place, they must be equal, but it is entirely possible to copy multiple strings with the same content to different places.

6.5 Empty and NUll Strings

An 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) or the if (STR) equals (" "))Copy the code

An empty string is a Java object with its own string length and content.

To check whether a string is null

if(str==null)
Copy the code

To check that a string is neither null nor empty

if(str! =null && str.length()! = 0)Copy the code

6.6 Constructing a String

Sometimes, strings need to be constructed from shorter strings, and string concatenation is inefficient. Will build a String, which is time-consuming and time consuming. Using StringBuilder can avoid this problem. StringBuilder is thread-safe and inefficient; Stringbuffers are thread-unsafe and highly efficient.

7. Input and output

7.1 Reading Input

For input from the console, first create a Scanner object and associate it with “biaoZHUn”

Scanner in = new Scanner (system.in); String name = in.nextLine();Copy the code

7.2 Formatting Output

As with C, there is a dedicated formatted output.

7.3 File Input and Output

Scanner in = new Scanner(Paths.get("myfile.txt"),"utf-8");
Copy the code

8. Control process

Control statements, common conditional, loop, multiple choice switch and interrupt.

The switch statement executes from the case tag matching the option value until a break statement is encountered, or the end of the switch statement is executed. If there is no matching case tag and there is a default clause, this clause is executed.

Case constant expressions, enumerated variables, and string constants labeled char, byte, short, or int.

9. Large numbers

Two useful classes in the java.math package are BigInteger and BigDecimal. These two classes can handle values containing sequences of numbers of arbitrary length, with the BigInteger class implementing integer operations with arbitrary precision and the BigDecimal class implementing floating point operations with arbitrary precision.

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

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

Ten, arrays,

An array is a data structure used to store a collection of values of the same type. Declare array format:

int [] a;
Copy the code

Once declared, it needs to be initialized before it can be used.

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

10.1 the forEach loop

That is, the enhanced for loop can iterate through each element of the array without requiring subscripts

for(int element:a){
 
}
Copy the code

10.2 Array initialization and anonymous Arrays

In Java, a simplified form of writing is provided to create array objects and assign initial values

Int [] a={1,2,3,4,5,6} new int[] {1,2,3,4}Copy the code

10.3 Array Copy

Java allows you to copy an array variable to another array variable. So two variables will reference the same array:

int [] a=b;
Copy the code

If you want all the values to be copied into a new array, use the copyOf method of the Arrays class

int copya =Arrays.copyOf(a,a.length)
Copy the code