Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2008

Tip: Looking for answers? Try searching our database.

Create String from char - so difficult??

Thread view: 
column.column@gmail.com - 22 Mar 2008 11:57 GMT
Hello,

How to create new String having one char. Is it really only way to
create new char array that has length one and using it create string?

     char a = 'a';
     String ss = new String ( new char[] {a});

By the way, in first line  characters '' represents only char or it
might be something else? As i understood "" always represents String.

Thank You
RedGrittyBrick - 22 Mar 2008 12:36 GMT
> Hello,
>
[quoted text clipped - 6 lines]
> By the way, in first line  characters '' represents only char or it
> might be something else? As i understood "" always represents String.

Any of the following will work.

  String s = "a";

  String s = "" + 'a';

  char c = 'a';
  String s = "" + c;
Arne Vajhøj - 22 Mar 2008 14:37 GMT
>   String s = "" + 'a';
>
>   char c = 'a';
>   String s = "" + c;

"" +

i not good code style.

Arne
RedGrittyBrick - 22 Mar 2008 21:04 GMT
>>   String s = "" + 'a';
>>
[quoted text clipped - 4 lines]
>
> i[s] not good code style.

True. Lothar explained why and suggested
    char c = 'a';
    ...
    s = Character.toString(c);

Perhaps
    Character c = 'a';
    ...
    String s = c.toString();
would often be marginally preferable?
Owen Jacobson - 24 Mar 2008 07:13 GMT
On Mar 22, 4:04 pm, RedGrittyBrick <RedGrittyBr...@SpamWeary.foo>
wrote:
> >>   String s = "" + 'a';
>
[quoted text clipped - 15 lines]
>      String s = c.toString();
> would often be marginally preferable?

For almost entirely superstitious reasons I would prefer the former
over the latter, even though the latter is more uniform with respect
to other, non-primitive types.  I dislike intentionally obscuring the
line between primitives and non-primitives in Java almost as much as I
dislike the existence of primitive, non-reference types in Java in the
first place.
Lothar Kimmeringer - 22 Mar 2008 12:55 GMT
> How to create new String having one char. Is it really only way to
> create new char array that has length one and using it create string?
>
>       char a = 'a';
>       String ss = new String ( new char[] {a});

String ss = Character.toString('a');
alternatively
String ss = String.valueOf('a');
This way is to be preferred over the usual answer
String ss = "" + 'a';
Reason for this is the way Strings are working in Java and what
the Java-compiler creates out of that line:
String ss = new StringBuffer().append("").append(String.valueOf('a')).toString();

Regards, Lothar
Signature

Lothar Kimmeringer                E-Mail: spamfang@kimmeringer.de
              PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
                questions!

Roedy Green - 22 Mar 2008 15:50 GMT
>      char a = 'a';
>      String ss = new String ( new char[] {a});

see http://mindprod.com/applet/converter.html
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 24 Mar 2008 13:13 GMT
>How to create new String having one char. Is it really only way to
>create new char array that has length one and using it create string?

Surely somebody has had it up to here with the irregularity of Java
conversion functions and written a wrapper class to convert any
primitive to any other (plus strings).

like this

double Cvt.todouble( String s );
float  Cvt.tofloat ( int i );
Float Cvt.toFloat ( long l );

....

See http://mindprod.com/applet/converter.html
for the code to implement each function.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Lew - 24 Mar 2008 13:46 GMT
>> How to create new String having one char. Is it really only way to
>> create new char array that has length one and using it create string?
[quoted text clipped - 8 lines]
> float  Cvt.tofloat ( int i );
> Float Cvt.toFloat ( long l );

I understand why you did it, but the lack of camel case is jarring (no pun
intended).  Besides, with autoboxing you don't need two versions:

  float f = Cvt.toFloat( int i );
  Float fc = Cvt.toFloat( int i );

Then again,

  float f = i;

works just fine.

As for String conversions, I don't understand what you mean by the
"irregularity" at all.  The String class has valueOf() overloads for all the
primitive types.  The primitive type wrapper classes except Character have
valueOf( String ) overloads.  It's hard to be more regular than that, unless
you insist on "remedying" the sole exception of Character, and I suspect that
one is due to the special relationship between Strings and chars and the
existence of String.charAt().

It's not worth running around Jericho's barn to wind up where I'm already
standing.

Signature

Lew

Mark Space - 24 Mar 2008 17:09 GMT
>> double Cvt.todouble( String s );
>> float  Cvt.tofloat ( int i );
>> Float Cvt.toFloat ( long l );

>   float f = Cvt.toFloat( int i );
>   Float fc = Cvt.toFloat( int i );

I don't find either of these to be all that readable.  In Roedy's
example, just the change in case is easy for my old eyes to miss. In
your case, overloading functions always runs the risk of calling the
wrong function on accident. (Say if the compiler is the one choosing
which function to call, how certain are you it calls the one you thought
it would?)

I think I'd make the function name more explicit, and skip the overloading.

float f = Cvt.toPrimitiveFloat( int i );
Float f2 = Cvt.toFloat( int i );

Or something like that.  The idea of readability is key here.
Owen Jacobson - 24 Mar 2008 17:42 GMT
> >> double Cvt.todouble( String s );
> >> float  Cvt.tofloat ( int i );
[quoted text clipped - 9 lines]
> which function to call, how certain are you it calls the one you thought
> it would?)

The whole point of Lew's post is that there is no overloading, as the
language already provides a feature that obviates the need for it.  In
this case, there is a single method

 public static float toFloat (int i)

In the second case, the returned float is being automatically boxed to
a Float by the compiler, freeing the programmer from having to write a
second method.

(Futhermore, Java forbids programmers from overloading by return type
only...)

-o
Mark Space - 24 Mar 2008 19:49 GMT
> (Futhermore, Java forbids programmers from overloading by return type
> only...)

Oh, good point.  I didn't realize that.
Roedy Green - 24 Mar 2008 18:39 GMT
>Then again,
>
>   float f = i;
>
>works just fine.

that's the problem.  the lack of predictability and regularity.  You
need something  a newbie can use mindlessly.  A decent optimiser
should inline them all so the final code would be just that.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Eric Sosman - 24 Mar 2008 19:16 GMT
>> Then again,
>>
[quoted text clipped - 5 lines]
> need something  a newbie can use mindlessly.  A decent optimiser
> should inline them all so the final code would be just that.

    Neither newbies nor roedies[*] should be encouraged
to write code mindlessly.

    [*] Needed a word connoting uncommon breadth and depth
of experience, the opposite of "newbie."  For the sake of
sentence punch, wanted a two-syllable word ending in "-ies"
to highlight the contrast; this was the best I could find.

Signature

Eric.Sosman@sun.com

John W. Kennedy - 24 Mar 2008 22:56 GMT
>> Then again,
>>
[quoted text clipped - 5 lines]
> need something  a newbie can use mindlessly.  A decent optimiser
> should inline them all so the final code would be just that.

You're on the road to reinventing PL/I.

Signature

John W. Kennedy
"Only an idiot fights a war on two fronts.  Only the heir to the throne
of the kingdom of idiots would fight a war on twelve fronts"
 -- J. Michael Straczynski.  "Babylon 5", "Ceremonies of Light and Dark"

Roedy Green - 24 Mar 2008 18:40 GMT
>As for String conversions, I don't understand what you mean by the
>"irregularity" at all.  The String class has valueOf() overloads for all the
[quoted text clipped - 3 lines]
>one is due to the special relationship between Strings and chars and the
>existence of String.charAt().

have a look at all the various conversions at
http://mindprod.com/applet/converter.html

There are pockets of regularity, but overall it drives newbies to
distraction.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 24 Mar 2008 19:28 GMT
>I understand why you did it, but the lack of camel case is jarring (no pun
>intended).  Besides, with autoboxing you don't need two versions:
>
>   float f = Cvt.toFloat( int i );
>   Float fc = Cvt.toFloat( int i );

you can't quite to do that e.g.

boolean isBig =   ctv.toFloat( i ).isInfinite();

I don't think autoboxing would be smart enough to handle that.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Lew - 25 Mar 2008 04:11 GMT
> Float Cvt.toFloat ( long l );

Lew wrote,
>> Besides, with autoboxing you don't need two versions:
>>
>>   float f = Cvt.toFloat( i );
>>   Float fc = Cvt.toFloat( i );

> you can't quite to do that e.g.
>
> boolean isBig =   ctv.toFloat( i ).isInfinite();
>
> I don't think autoboxing would be smart enough to handle that.

Works fine here:

package testit;
public class Boxer
{
  public static Float toFloat( int in )
  {
    return (float) in;
  }

  public static Float toFloat( long in )
  {
    return (float) in;
  }

  public static void main(String[] args)
  {
    int in = 17;
    boolean isBig = toFloat( in ).isInfinite();
    System.out.println( "Is "+ in +" big? "+ isBig );

    long ln = 4000000000L;
    isBig = toFloat( ln ).isInfinite();
    System.out.println( "Is "+ ln +" big? "+ isBig );

  }
}

Signature

Lew

Roedy Green - 25 Mar 2008 05:08 GMT
>     isBig = toFloat( ln ).isInfinite();

Good. that gets rid of the need to distinguish between toFloat and
tofloat.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.