Concatenate chars to form String in java
Use StringBuilder
:
String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
sb.append(c);
str = sb.toString();
One-liner:
new StringBuilder().append(a).append(b).append(c).toString();
Doing ""+a+b+c
gives:
new StringBuilder().append("").append(a).append(b).append(c).toString();
I asked some time ago related question.
Why is possible to concatenate Char and String in Java?
Java's '+' operator also serves as a concatenation operator. It can concatenate primitives and objects and would return you a string which is its result.
The following explanation assumes that you are familiar with Java's wrapper classes. In case you are not familiar with them, please give it a read.
Java's '+' operator converts all the primitive data types used in the statement to their equivalent Wrapper classes and invokes toString() method on those instances and uses that result, which is a string in the expression.
Ex: In Java, a statement like System.out.println( 3 + " Four " + 'C' );
ends up creating a String with the content "3 Four C"
.
In the above statement, 3 is a primitive int variable. " Four " is a String object and 'C' is a primitive char variable.
During '+' concat operation,
3 gets converted to its corresponding Wrapper class -> Integer. And then toString() method is called on it. Output is String 3 i.e., "3"
" Four " is already a String and needs no further processing.
'C' gets converted to Character wrapper class and toString() method results in returning the String "C".
So finally, these three are added so that you get "3 Four C".
To Sum up:
- If a primitive is used in '+' operator, it would be converted to its Wrapper class and then toString() method is called on it and the result would be used for appending.
- If an object other than String is used, its toString() method would be called and its result would be used for appending.
- If a String is called, well, there is not much to do and the string itself gets used for appending.
Concatenate characters to a string - java
String result = "";
for (int i = 0; i < encrypt.length(); i++) {
char c = encrypt.charAt(i);
if (Character.isLetter(c)) {
c -= shift;
if(c < 'A'){
c = (char) (((int) c + (int) ('A')) % 26 + (int) ('A'));
}else{
c = (char) (((int) c - (int) ('A')) % 26 + (int) ('A'));
}
}
result += String.valueOf(c);
}
JOptionPane.showMessageDialog(null, result);
Concatenation of Strings and characters
You see this behavior as a result of the combination of operator precedence and string conversion.
JLS 15.18.1 states:
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
Therefore the right hand operands in your first expression are implicitly converted to string: string = string + ((char)65) + 5;
For the second expression however string += ((char)65) + 5;
the +=
compound assignment operator has to be considered along with +
. Since +=
is weaker than +
, the +
operator is evaluated first. There we have a char
and an int which results in a binary numeric promotion to int
. Only then +=
is evaluated, but at this time the result of the expression involving the +
operator has already been evaluated.
How does the concatenation of a String with characters work in Java?
str.charAt(i)
returns a char
, adding two char
s results in a char
with a codepoint equal to the sum of the input codepoints. When you start with str +
, the first concatenation is between a String
and a char
, which results in a String
, followed by the second concatenation, also between a String
and a char
.
You can fix this a few ways, such as:
str1 += String.valueOf(str.charAt(i)) + str.charAt(i);
or
str1 += "" + str.charAt(i) + str.charAt(i);
or, as you've already discovered, and likely the most readable:
str1 = str1 + str.charAt(i) + str.charAt(i);
Java Concatenating two Strings with only charAt
You are performing assignment, not concatenation, and you can't assign a char
to a String
variable anyway.
In order to concatenate the characters, you can use the +
operator (or +=
):
String concatenated = "";
for (int i = 0; i < firstString.length(); i++){
concatenated += firstString.charAt(i);
}
Or you can use a StringBuilder
object and append the characters to it:
StringBuilder concatenated = new StringBuilder(firstString.length()+secondString.length());
for (int i = 0; i < firstString.length(); i++){
concatenated.append(firstString.charAt(i));
}
for (int i = 0; i < secondString.length(); i++){
concatenated.append(secondString.charAt(i));
}
System.out.println(concatenated.toString());
This is more efficient than the +
operator, since it only generates one StringBuilder
object, while the +
operator generates a new String
object each time you use it.
Best way to concatenate Strings in java(Time efficiency)
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder
instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Related Topics
Bouncy Castle:Pemreader => Pemparser
How to Check a Timeperiod Is Overlapping Another Time Period in Java
Jaxb Mapping Cyclic References to Xml
Production Settings File for Log4J
Gwt: Timer and Scheduler Classes
Why Does String.Replace Not Work
Why Is Super Class Constructor Always Called
How to Specify the Default Jvm Arguments for Programs I Run from Eclipse
Postgresql Uuid Supported by Hibernate
Include External Jar When Running Java -Jar
What Is the Purpose of Mavens Dependency Declarations Classifier Property
How to Convert Words to a Number
How to Provide Pagination Support to a Jtable in Swing
Create Simple Pojo Classes (Bytecode) at Runtime (Dynamically)
How to Check the Type of a Value from a JSONobject
Why Do Java If Statement Fail When It Ends in Semicolon