By stevie lol


2019-07-10 19:51:37 8 Comments

So this is the task: Given a string, return a string where for every char in the original, there are two chars.

And I don't understand why its output are numbers instead of letters, I tried doesn't work?

public String doubleChar(String str) {
  String s = "";
  for(int i=0; i<str.length(); i++){
  s +=  str.charAt(i) + str.charAt(i);

  }
    return s;
}

Expected :

doubleChar("The") → "TThhee"

doubleChar("AAbb") → "AAAAbbbb"

Output:

doubleChar("The") → "168208202"

doubleChar("AAbb") → "130130196196"

5 comments

@Edward 2019-07-10 20:07:06

Why does it output integers?

The + operator is overloaded in Java to perform String concatenation only for Strings, not chars.

From the Java Spec:

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

In your case, char is converted to its primitive value (int), then added.

Instead, use StringBuilder.append(char) to concatenate them into a String.

If performance is not a concern, you could even do:

char c = 'A';
String s = "" + c + c;

and s += "" + c + c;

That will force the + String concatenation operator because it starts with a String (""). The Java Spec above explains with examples:

The + operator is syntactically left-associative, no matter whether it is determined by type analysis to represent string concatenation or numeric addition. In some cases care is required to get the desired result. For example [...]

1 + 2 + " fiddlers" is "3 fiddlers"

but the result of:

"fiddlers " + 1 + 2 is "fiddlers 12"

@kaan 2019-07-10 20:06:49

String.charAt() returns a char (https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)) so you're dealing with a single character. With onechar, you can perform operations on it like this (which will print "65" which is ASCII value for the 'A' character):

System.out.println('A' + 0);

you can print the ASCII value for the next character ("B") by adding 1 to 'A', like this:

System.out.println('A' + 1);

To make your code work – so that it doubles each character – there are number of options. You could append each character one at a time:

s += str.charAt(i);
s += str.charAt(i);

or various ways of casting the operation to a string:

s += "" + str.charAt(i) + str.charAt(i);

@Neil 2019-07-11 08:57:32

s = s + str.charAt(i) + str.charAt(i); probably also works, I guess?

@Nexevis 2019-07-10 19:55:45

You are adding the value of two characters together. Change the String concatenation from:

s +=  str.charAt(i) + str.charAt(i);

To:

s +=  str.charAt(i) + "" + str.charAt(i);

Which will ensure the characters convert to a String.

Note: This is a quick fix, and you should use StringBuilder when String concatenating inside of a loop. See the other answers for how this is done.

@Bobulous 2019-07-10 20:04:07

In Java the char primitive type is basically just a numeric value that maps to a character, so if you add two char values together they produce a number and not another char (and not a String) so you end up with an int as you're seeing.

To fix this you can use the Character.toString(char) method like this:

s += Character.toString(str.charAt(i)) + Character.toString(str.charAt(i))

But this is all fairly inefficient because you're doing this in a loop and so string concatenation is producing a lot of String objects needlessly. More efficient is to use a StringBuilder and its append(char) method like this:

StringBuilder sb = new StringBuilder(str.length() * 2);
for (int i = 0; i < str.length(); ++i) {
    char c = str.charAt(i);
    sb.append(c).append(c);
}
return sb.toString();

@Hayes Roach 2019-07-10 20:12:39

This should be correct answer. Creating new String objects each loop iteration is not good practice. Using a StringBuilder is more efficient. Look here for exaplanation stackoverflow.com/a/18453485/8685250

@marstato 2019-07-11 07:03:08

At least since Java 8 the compiler is converting regular string concats to stringbuilder constructs where it helps. There is no need to make your code less clear or more complicated of the compiler can optimize better, anyways

@LordOfThePigs 2019-07-11 12:37:58

@marstato that is true, but it doesn't apply in this case. The Java compiler will indeed convert sequences of string concatenations to sequences of StringBuilder.append. That will cover the s += s1 + s2 statement inside the for block, but it will be compiled such that each execution of this statement creates its own StringBuilder. Manually creaing it outside of the loop won't have this issue.

@Bobulous 2019-07-11 19:37:41

@marstato LordOfThePigs is right: the problem with string concatenation within a loop is that it forces the creation of a new StringBuilder object for every iteration. Also, the default capacity of a StringBuilder is only 16 characters, so a lot of appending will force numerous resizes, thus creating more objects. I have created a JMH benchmark to test this and found that in a loop of 1000 iterations, String concatenation generates 11MiB of garbage, and runs at 876 ops/sec, while a StringBuilder with optimum capacity generates only 29KiB of garbage and runs at 39,734 ops/sec.

@Joshua Blevins 2019-07-16 13:42:38

@Edward they are just passing down useful information. You have to remember how much "magic" happens behind the scenes in Java. It isn't like other languages, where the most efficient way is the most obvious way.

@LeffeBrune 2019-07-10 20:01:27

You are adding numeric values of chars first before concatenating the result (now integer) to the string. Try debugging with print statements:

public static String doubleChar(String str) {
  String s = "";
  for (int i = 0; i < str.length(); i++) {
    System.out.println(str.charAt(i));
    System.out.println(str.charAt(i) + str.charAt(i));
    s += str.charAt(i) + str.charAt(i);
  }
  return s;
}

The more efficient way of doing what you want is:

public static String doubleChar(String str) {
  StringBuilder sb = new StringBuilder(str.length() * 2);
  for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    sb.append(c).append(c);
  }
  return sb.toString();
}

@Nexevis 2019-07-10 20:04:43

I agree he should be using StringBuilder since he is concatenating a String inside of a loop, but it may be helpful to explain briefly why it is better.

@marstato 2019-07-11 07:03:43

At least since Java 8 the compiler is converting regular string concats to stringbuilder constructs where it helps. There is no need to make your code less clear or more complicated of the compiler can optimize better, anyways

@Martin Bonner supports Monica 2019-07-11 09:48:19

@marstato Using the stringbuilder is at least as clear as any solution not using the string builder. It also offers the opportunity to initialize the string builder to the right size (and I doubt the compiler reliably does that).

@LeffeBrune 2019-07-11 14:13:26

@marstato compiler would only convert concatenation of strings into a string builder inside of the loop. A new string and string builder would be created on every iteration AFAIK.

@Stop Harming Monica 2019-07-11 14:19:33

A better suggestion is to try debugging with a debugger.

Related Questions

Sponsored Content

6 Answered Questions

14 Answered Questions

10 Answered Questions

[SOLVED] Why is it string.join(list) instead of list.join(string)?

  • 2009-01-29 22:45:13
  • Evan Fosmark
  • 1242592 View
  • 1672 Score
  • 10 Answer
  • Tags:   python string list

8 Answered Questions

[SOLVED] What does the 'b' character do in front of a string literal?

12 Answered Questions

[SOLVED] Why does Java's hashCode() in String use 31 as a multiplier?

15 Answered Questions

[SOLVED] Why does this code using random strings print "hello world"?

  • 2013-03-03 04:38:06
  • 0x56794E
  • 194643 View
  • 1734 Score
  • 15 Answer
  • Tags:   java string random

6 Answered Questions

[SOLVED] What is the difference between encode/decode?

5 Answered Questions

[SOLVED] How does the concatenation of a String with characters work in Java?

  • 2014-01-05 20:26:32
  • kusur
  • 1572 View
  • 1 Score
  • 5 Answer
  • Tags:   java string

3 Answered Questions

1 Answered Questions

[SOLVED] Why int for integer yet not str for string

  • 2015-12-26 21:40:47
  • Hyden
  • 52 View
  • 1 Score
  • 1 Answer
  • Tags:   string integer

Sponsored Content