adding chars

M

Millian Brave

Check out String.valueOf(char) method
To produce a String you could also do like this:

char ch1 = 'a';
char ch2 = 'b';

String str = ch1 + ch2 + "";
 
M

Michael Borgwardt

Millian said:
Check out String.valueOf(char) method
To produce a String you could also do like this:

char ch1 = 'a';
char ch2 = 'b';

String str = ch1 + ch2 + "";

That's exactly how you DON'T do it, because it will add the chars' numeric values
and then display that as a String, i.e. it will prodcute "195".
 
V

VisionSet

Rookie said:
How can I add two char to make a string?

either:

new String( new char[] {'h', 'e', 'l', 'l', 'o'} );

or

StringBuffer buffer = new StringBuffer();

buffer.append('a');
buffer.append('b');

System.out.println(buffer.toString());
 
M

Millian Brave

Sorry, I switched the order of the "". If you do a:

String str = "" + ch1 + ch2... you'll get the result you wanted, "ab" that
is. But I of course agree, this is a dirty way of doing it (implicit cast).
 
J

Joona I Palaste

Millian Brave said:
Sorry, I switched the order of the "". If you do a:
String str = "" + ch1 + ch2... you'll get the result you wanted, "ab" that
is. But I of course agree, this is a dirty way of doing it (implicit cast).

Typically, the proper way of making a char into a String would be the
String.valueOf() method instead of "" + char, but I don't see how it
could be used to make *two* chars into *one* String.
 
M

Millian Brave

Yep, that's what I said (String.valueOf()). About the ""+ch1+ch2.. try it
out yourself.
 
M

Michael Borgwardt

Joona said:
Typically, the proper way of making a char into a String would be the
String.valueOf() method instead of "" + char, but I don't see how it
could be used to make *two* chars into *one* String.

Well, obviously you'd have to invoke it for each char separately and concatente
the resulting Strings. But then, using a StringBuffer directly would be faster
and cleaner, since I believe that's what the "+"-concatenation is translated to.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top