user2991413
user2991413

Reputation: 551

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.

Upvotes: 4

Views: 769

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201517

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.

Upvotes: 8

Stephen C
Stephen C

Reputation: 719436

Why is the String class from rt.jar not picked by the 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.

The name resolution actually happens at compile time. The compiler decides what String means in the context of the source code file that is using it and then uses the full name for the resolved class (e.g. java.lang.String or your.pkg.String) in the class file. At runtime, Java class loaders always load classes using a full class name.

Upvotes: 4

Related Questions