Group friends in the wechat group discussion of a topic, a little interesting, especially out to share.

First look at the following procedure, and group friends share roughly the same.

public static void main(String[] args) {
    String hw = "hello world";

    String hello = "hello";
    final String finalWorld2 = "hello";
    final String finalWorld3 = hello;
    final String finalWorld4 = "he" + "llo";

    String hw1 = hello + " world";
    String hw2 = finalWorld2 + " world";
    String hw3 = finalWorld3 + " world";
    String hw4 = finalWorld4 + " world";

    System.out.println(hw == hw1);
    System.out.println(hw == hw2);
    System.out.println(hw == hw3);
    System.out.println(hw == hw4);
}
Copy the code

Program output:

false
true
false
true
Copy the code

Why is the string “hello” defined with final true and false when both == operations are performed, and false when no final is used?

First, let’s understand macro variables:

In Java, a variable defined with final, regardless of type, is a macro variable if final is defined and an initial value is specified, and the initial value is determined at compile time. The compiler replaces any use of the variable directly with the value of the variable, which means that the compiler can perform macro substitution on a macro variable.

Such as:

final String a = "hello";
final String b = a;
final String c = getHello();
Copy the code

A is determined at compile time, but b and C are not, so a is a macro variable and b and C are not.

So, going back to the program above, finalWorld2 and finalWorld4 are final and can be determined at compile time, so they can be replaced by macros, The compiler makes finalWorld2 and finalWorld4 point to the string “Hello World” cached in the string pool, so they are the same object.

Recommended reading

Dry goods: Free 2TB architect four-stage video tutorial

Interview: the most complete Java multithreaded interview questions and answers

Tools: Recommended an online creation flow chart, mind mapping software

Share Java dry goods, high concurrency programming, hot technology tutorials, microservices and distributed technology, architecture design, blockchain technology, artificial intelligence, big data, Java interview questions, and cutting-edge hot news.