public static String obify(String v) {
//String v = "AEIOU";
String result = "";
for(int i=0; i<v.length();i++) {
String x = String.valueOf(v.charAt(i));
//if a character in the string is an age,i,o,u, or y,
// then we insert a "OB" infront of the character.
// So if your string was ajp, then the output should
// be obajb. My question is why is the valueof method
// here important, are there any other alternatives?
if(x.equals("A")|| x.equals("E")|| x.equals("I")|| x.equals("O")|| x.equals("U")|| x.equals("Y")) {
result = result + "OB" + x;
}
else {
result +=x;
}
}
return result;
}

- 55,782
- 14
- 81
- 108
-
1You could also do v.substring(i, i + 1) – user Jul 11 '20 at 22:41
3 Answers
valueOf
is converting your char to a string. You don't need to do that. You can keep it as a char, and compare the char to other chars instead of to strings. Chars are single-quoted instead of double-quoted.
public static String obify(String v) {
String result = "";
for (int i=0; i<v.length(); i++) {
char ch = v.charAt(i);
if (ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U' || ch=='Y') {
result += "OB" + ch;
} else {
result += ch;
}
}
return result;
}
You can make that more concise by instead of checking if your character is equal to one of those letters using ||
, you can check if it is present in a string.
...
if ("AEIOUY".indexOf(ch) >= 0) {
result += "OB" + ch;
}
...

- 55,782
- 14
- 81
- 108
You can also do this much more concisely with regex:
return v.replaceAll("[AEIOUY]", "OB$0");

- 137,514
- 11
- 162
- 243
The v.charAt() methods a 'char' value and you are using the String.valueOf method to convert a 'char' value into a 'string'. Please refer to the java doc. I think this would answer your question.
As for alternatives, there are so many, but for your scenario, using a valueOf is perfectly okay, but actually the valueOf method is not required if you refactor it as follows;
public static String obify(String v) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < v.length(); i++) {
char charValue = v.charAt(i);
switch (charValue) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
result.append("OB").append(charValue);
break;
default:
result.append(charValue);
}
}
return result.toString();
}
Note that concatenation of string is also not recommended, instead in the code snippet above a "StringBuilder" is used. Also, the if statement has been replaced by a switch.
Good luck!

- 450
- 4
- 11
-
Thank that makes sense, since the for loop is going though a char each iteration, we want to convert it to a string. Makes sense. Thank you – Jul 11 '20 at 23:14