Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is RunThis(char arg[]) expecting a String?  RSS feed

 
Mannie J Chaihan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want my function to accept "this is array of chars".



Of course I can't. compiler is telling me I need to send a String
What am I doing wrong?
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Mannie -

A String is a different thing in Java than it is in C. In C, a null terminated character array is a string; in Java, String is a full-fledged object. So, you can create a char array from the String object that you create when you put text between quotes, or you can change the method parameter to take a String object.

Hope that helps...
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mannie J Chaihan:
I want my function to accept "this is array of chars".



Of course I can't. compiler is telling me I need to send a String
What am I doing wrong?


Actually "this IS a String, NOT an array of chars". As described above, a literal value enclosed in double-quotes behaves VERY differently in Java than it does in C/C++. They are actually String objects, not char arrays.

Layne
 
Mannie J Chaihan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
A java.lang.String != Char[]
Ok, so how do I write my function so that it will accept the call:
 
Mannie J Chaihan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I tried my only option:

And Voila.. It still feels very unnatural.
Thank you for your help!
[JAM Edited for formatting of code....]
[ May 11, 2005: Message edited by: Joel McNary ]
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's correct: Java recognizes the "this is a string" as a literal object. This means that you can do things like:



There's no need for a primitive type, as the object type is much more flexible. Also, Literal strings are treated internally a little bit differently; only 1 copy of a string is created, so:


is true, where

is false.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!