File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Awkward query on String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Awkward query on String" Watch "Awkward query on String" New topic

Awkward query on String

shwetank singh

Joined: Apr 02, 2007
Posts: 26
Hello Ranchers!

i understand it's incorrect, how it happens is what i wish to understand.
experts..please explain how is this handled in java
String b ="a"
creates reference b to string a. how is "a" allocated and assigned to String (a class?)

MyOwnClass c = "a"; truly incorrect (or could this be done?), i understand "a" is string and hence couldn't be allocated to MyOwnClass reference type..but how is this decided by compiler?..where could i get compiler directives of java?

this obviously results from my own brains, i am just curious, even when wrong
please guide..

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
You appear to have posted in the wrong place; I shall move you to somewhere more appropriate.
Vinoth Kumar Kannan
Ranch Hand

Joined: Aug 19, 2009
Posts: 276

MyOwnClass c = "a";
wont work. "a" is a String literal - Anything within a double quotes is a String literal. A String literal can be assigned only to references of the String class, or else the compiler would throw an error.

A google on 'String literal pool' or 'String constant pool' might help you in understanding String memory allocations.
JavaRanch itself has an excellent article regarding this -

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Every reference variable has a Class<T> object associated with it. The compiler can verify that all your reference variables are the correct type by querying the details in the classes; those allow it to check the inheritance of your objects and whether it matches the inheritance of the type of variable you are using.
I agree. Here's the link:
subject: Awkward query on String
It's not a secret anymore!