Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Awkward query on String  RSS feed

 
shwetank singh
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 54881
155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You appear to have posted in the wrong place; I shall move you to somewhere more appropriate.
 
Vinoth Kumar Kannan
Ranch Hand
Posts: 276
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Marshal
Posts: 54881
155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Too many men are afraid of being fools - Henry Ford. Foolish tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!