Constant Pool question in Java

Asked 2 years ago, Updated 2 years ago, 23 views

While studying Java, I learned that it was Constant Pool. I thought that using Constant Pool and hashcode() I could find out the address of the String variable declared private, so I organized the code and turned it around, but I keep getting an explicit start of expression.

package project;

public class Main{
    public static void main(String[] args){//main method
  private String name=new String("Caleb");//created with private start of expression
        System.out.println ("First Reference="+name.hashcode());//1Output
Main operator=new Main();
        operator.runMethod0();
    }
}

public class AnotherClass{ 
    public void runMethod0(){
          Public Stringirm="Caleb";//Canstant pool induced ilegal start of expression
        System.out.println ("Second Reference="+irm.hashcode());//2Output
    }
    }

I want to know why the ilgal start of expression occurs

java

2022-09-22 19:57

1 Answers

The code you suggested earlier is not grammatical.

By default, access restrictors are not available within methods (such as private).

Second, the hashcode method returns int. It's also a compilation error because I added it to the string.

Third, there is also no runMethod0 method in the Main class.

And if you do the new String, it is not registered in the constant pool, but in the heap.

The important fact is that hashcode is not like a memory address. The hashcode is not related to whether it is the same as the value of the constant pool.

Note - This is the hashCode implemented in jdk 1.8.

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

The important fact is that if you create a literal string (in the form String a = "), it is registered in the constant pool, and if you create a String object using the new operator, it is stored in heap.

After creating a String object using the new operator, the internal method allows you to explicitly register with the constant pool.

Constants pool does not have the same string.

This means that only one "abcd" is registered in the constant pool.

String a = "abcd";
String b = "abcd";


2022-09-22 19:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.