1

i have a task to repeat characters multiplying it for example the user should write the letter and number of repeat input 3 R output

RRR

input 6 O output

OOOOOO

and it should be one letter only i have used strings but can i use char ? and how can i do it ? why when when multiplying chars the result is number ? for example char*3 the result is 246

i am new to java

1 Answers1

3

A char is represented by a UTF-16 value (an unsigned short). When you use char in arithmetic, its UTF-16 value is used.

If you want to repeat a char, you can use something like this:

String.join("", Collections.nCopies(6, 'O'));

>> "OOOOOO"

A con of using this method with a char is that each primitive is boxed into the Character wrapper class, so you might be better of using a String instead to produce the same result.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • That would be true if `char` had anything to do with ASCII. It doesn't. Java's text datatypes use the UTF-16 encoding of the Unicode character set. – Tom Blodget Apr 12 '17 at 20:20