wood burning stoves*
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
Author

Awkward query on String

shwetank singh
Greenhorn

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";
..is 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..

thanks!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38497
    
  23
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 - http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html


OCPJP 6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38497
    
  23
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.
 
 
subject: Awkward query on String