Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if i create my own String class in java?

When i create my own String class .If there is another class in same package , main(String[] args) seems to pick my String class instead of the one present in rt.jar. My question is , why String class from rt.jar is not picked by Bootstrap Class loader in this case. My understanding is a class loading request that comes to Application loader will be delegated to bootstrap class loader.

like image 271
user2991413 Avatar asked Dec 15 '22 07:12

user2991413


1 Answers

Because the String in your local package takes precedence; you can explicitly use java.lang.String or name your class String something else1.

public static void main(java.lang.String[] args)

To expand on the above, at compile time the compiler resolves class names to their fully qualified form (at the byte-code level, there aren't any imports). Further, Java includes a String intern pool that is initialized before your class is loaded (in order for that to function, java.lang.String has to be loaded before any user classes).

1Which is really a better idea, shadowing classes from java.lang is asking for a maintenance nightmare.

like image 146
Elliott Frisch Avatar answered Dec 16 '22 21:12

Elliott Frisch