Java is a strongly typed language

What is a strongly typed language? A variable can only correspond to one type. Instead of an ambiguous type symbol. Let me illustrate this phenomenon with an example.

  • You can use var to represent many data types in javascript
// A is number
var a = 1;
// a is a string of '1'.
var a = '1';
Copy the code

As you can see, in javascript, you can use var to hold various data types, but in Java, you have to declare specific data types for variables (Var was also opened in Java10, and the current version is Java8).

8 Big data type

Basic types of Storage required size Value range
int 4 bytes – 2147483648 ~ 2147483647
short 2 – – 32768 ~ 32767
long 8 bytes – 9223372036854775808 ~ 9223372036854775807
byte 1 byte – 128 ~ 127
float 4 bytes 1.4 e-45 f ~ 3.4028235 e + f
double 8 bytes E+308 e-324 4.9 ~ 1.7976931348623157
char 2 – \u0000~\uFFFF
boolean Different results depending on JVM compile behavior (1/4) The size of a Boolean type is undefined. It is usually defined as taking a literal value of “true” or “false”

NaN and infinity

  • NaN

In floating-point numerical calculations, there is a NaN to indicate that the value is not a number

/ * * *@authorJaymin <br> * How to express a value that is not a number * 2021/3/21 14:54 */
public class NaNDemo {
    public static void main(String[] args) {
        Double doubleNaN = new Double(0.0/0.0);
        // A constant whose value is a non-numeric (NaN) value of type doubleDouble nan = Double.NaN; System.out.println(doubleNaN.isNaN()); System.out.println(nan.isNaN()); }}Copy the code
  • Plus and minus infinity
    private static void isPositiveInfinityAndNegativeInfinity(a){
        double positiveInfinity = Double.POSITIVE_INFINITY;
        double negativeInfinity = Double.NEGATIVE_INFINITY;
        System.out.println(positiveInfinity);
        System.out.println(negativeInfinity);
    }
Copy the code

Result:

Infinity
-Infinity
Copy the code

Floating-point numbers have accuracy problems

Floating point values cannot be used to represent fractions in Java because they are ultimately represented in the binary system.

/ * * *@authorJaymin <br> * Floating point numbers cannot represent fractions *@since2021/3/21 15:07 * /
public class PrecisionDemo {
    public static void main(String[] args) {
        System.out.println(2.0 - 1.1);
        // How to solve it? Use BigDecimal
        BigDecimal a = BigDecimal.valueOf(2.0);
        BigDecimal b = BigDecimal.valueOf(1.1); System.out.println(a.subtract(b)); }}Copy the code

Upward transformation and downward strong transformation

  • upcasting
/ * * * * *@author jaymin
 * @since2021/3/21 double-break * /
public class ForcedTransfer {

    public static void main(String[] args) {
        int n = 123456789;
        // Integer upconversion lost precision
        float f = n;
        System.out.println(f);
        int n1 = 1;
        float f1 = 2.2 f;
        // Different types of values will be converted upwardSystem.out.println(n1 + f1); }}Copy the code

Here we see two phenomena:

  1. Integers can be assigned to floating-point types, but accuracy may be lost.
  2. An integer is added to a floating-point number, first converting an integer up to float, then performing float operations.

Hierarchy :double>float>long>int

  • One detail that interviewers often ask for

Can I compile here?

short s1= 1;
s1 = s1 + 1;
Copy the code

The answer is no. If we perform any arithmetic or bitwise operations on basic data types less than int (that is, char, byte, or short), these values will be promoted to int before the operation is performed, and the resulting value will be of type int. If you want to reuse a smaller type, you must use a cast (the result may lose precision due to reassignment back to a smaller type). Anything less than an int will eventually be promoted to an int. Using final can help you solve this problem.

  • The correct sample
short s1= 1;
// 1
s1 = (short) (s1 + 1);
// 2. Second solution
s1+=1;
Copy the code
        final short a1 = 1;
        final short a2 = 2;
        short result = a1 + a2;
Copy the code
  • Downcast (cast)

Scenario: You get a floating point number in your program, turn it into an integer, and you can use strong turns.

/** * strong conversion between values **@author jaymin
 * @since2021/3/21 double-break * /
public class ForcedTransfer {

    public static void main(String[] args) {
        double x = 2021.0321;
        // Strong integer
        int integerX = (int) x;
        System.out.println(integerX);
        x = 2021.8888;
        // Round off
        int round = (int) Math.round(x); System.out.println(round); }}Copy the code

Result:

2021, 2022,Copy the code

If the range of the upper data type exceeds the range of the lower data type during strong casting, truncation is performed. The following procedure can be performed to verify the problem.

        long l = Long.MAX_VALUE;
        int l1 = (int) l;
        System.out.println(l1);
        int i = 300;
        byte b = (byte) i;
        / / 128 * 2 = 256300-256 = 44
    System.out.println(b);
Copy the code

Reuslt:

1 44Copy the code

The initial value

Basic data types have default initial values.

Basic types of The initial value
boolean false
char \u0000 (null)
byte (byte) 0
short (short) 0
int 0
long 0L
float 0.0 f
double 0.0 d
When you define an object, if you use a primitive type, the class will default if you don’t explicitly assign it after initialization. This is not true in some cases (e.g., if you need to transmit an ID through HTTP, you should report an error when the id is not transmitted, but because of the basic data type, the id has a default value of 0, and then the application will fail).

To define the members of an object, it is best to use wrapper types rather than base types.

Integer Specifies the cache area of the object

There are some values that you need to use frequently in your program, such as 1, 2, and 3, which are often used as mapping values when defining enumerations. The Java language specification JLS requires that values from -128 to 127 be cached. (The size of the cache can be controlled by the -xx: AutoBoxCacheMax = option. In the VM during initialization, can be in the sun. The misc. VM class in the system of private property Settings and save the Java. Lang. Integer. IntegerCache. High attribute.)

  • Using == to compare integers can produce unexpected results
    public static void main(String[] args) {
        Integer a1 = Integer.valueOf(127);
        Integer a2 = Integer.valueOf(127);
        System.out.println(a1==a2);
        Integer a3 = Integer.valueOf(128);
        Integer a4 = Integer.valueOf(128);
        System.out.println(a3==a4);
    }
Copy the code

Result:

true
false
Copy the code

The solution is simple: use equals to compare,Integer internally overrides equals and Hashcode.

Some commonly used escape characters

In strings, if you want to wrap the output string, you need to use escape characters

Escape character Unicode meaning
\b \u0008 backspace
\t \u0009 TAB
\n \u000a A newline
\r \u000d enter
\" \u0022 Double quotation marks
\ ' \u0027 Single quotes
\ \ \u005c The backslash
\ \. .
  • Newline output string
    System.out.println("I'm about to change lines \n I'm next line");
Copy the code