This question already has answers here:
Comparing strings with == which are declared final in Java
(6 answers)
a confusion about java String literal pool and String's concatenation
(4 answers)
Closed 8 years ago.
When I write the following code
int a = "Java";
the java compiler displays the following error :
cannot convert from String to int
So the constant Java is considered as an object derived from
String class.
- Is it true that each list of characters contained between "" is considered as an object derived from String class?
When I try to have concatenation of two strings I used the two
following examples:
String ch1 = "Java " ;
String ch2 = "is cool";
String ch3 = ch1 + ch2;
after I used the command javap -c on my compiled class I found
that the compiler use an instance of StringBuilder to append the
two strings.
but with the other example:
String ch = "Java " + "is cool";
Although the two constants "Java " and "is cool" are both two objects derived from String
class, the compiler doesn't use an instance of StringBuilder to
append the two strings.
- So what's the approach used in the second example?
From here.
'+' creates a new String object every time it concatenates something, except when the concatenation is done at compile time.
While this is not a reputable source, from what I remember from my textbooks this sounds correct. So basically, applying this to your code:
String ch = "Java " + "is cool";
Would be handled at compile time since you've defined two constants and concatenated them together, which implies that the result is also in fact a constant and thus can be treated as such and calculated at compile time. It would be interesting to see if you compiled that code then decompiled to see how that statement would read, I'd imagine it may read:
String ch = "Java is cool";
As for the other statement:
String ch1 = "Java " ;
String ch2 = "is cool";
String ch3 = ch1 + ch2;
Since ch3 is calculated from ch1 and ch2, it is done at runtime since ch1 and ch2 are variables instead of constants.
As for your first question, I can't find any references exactly, but from what I remember yes the "" implies a string, just like '' implies a character. I'm not exactly sure what you're trying to do with that statement, but I would imagine you could convert your string into a char array and then cast it to an int array.
Not sure what your second question is, but for your first question:
"Java" is a string and you're trying to store it as an int type. It is not an integer. The variable a needs to be of type string.
String a = "Java ";
In the first example you have created 2 strings vars, ch1 and ch2 that could be used in other parts of the code so... when you init ch3 a new string in memory is created with the content of both vars (here is where StringBuilder do the work). This is needed because you can change the value of ch2 and ch3 will be not changed.
In the second example both strings are final and never used again further in the code, so Java simply create a unique String "Java is cool".
I don't know if I've explained it well.
When you do the following line
String ch1 = "Java " ;
String ch2 = "is cool";
String ch3 = ch1 + ch2;
Both ch1 and ch2 are literal and the Compiler would create String instance using StringBuilder . In the earlier days ( when compiler is not smart enough to do this) we would be wasting memory for each execution by concat operation
but when you use this
String ch = "Java " + "is cool";
Compiler understood that String Literal "Java " + "is cool" cannot be modified at any time. So the compilers would translate this into
String ch = "Java is cool";
as byte code. and only one String literal would create run time.
Related
set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());
I encountered this code from written by someone. It is java code.
s is a char[].
set is a String set.
So why does he use String and then StringBuffer?
String has a constructor which takes an array of chars, hence why they create a new String first.
Then to reverse the String, they create a StringBuffer to use a built in reverse function in order to not implement their own. StringBuffer's constructor takes a String, hence why a String is made first and then a StringBuffer
Let's split the 3 parts on 3 lines to compare:
set.add(
new String(s)
+ (ch == 0 ? "" : ch)
+ new StringBuffer(new String(s)).reverse()
);
Rewritten
It is equivalent with
String trimZero = ch == 0 ? "" : String.valueOf(ch);
set.add(String.valueOf(s) + trimZero + StringUtils.reverse(s));
Well, using Apache's StringUtils.reverse().
If s is a String it can simply added as is, for example, in an alternative way (to emphasize the different structures):
if (ch == 0) {
set.add(s + StringUtils.reverse(s));
} else {
set.add(s + String.valueOf(ch) + StringUtils.reverse(s));
}
Output wise
For example:
alphabet gets added as alphabet8tebahpla (for coincidence ch is a non-zero integer).
an gets added as anna (given that ch == 0)
Abbreviations and naming-conventions
When guessing the types I would say:
ch probably is a primitive char, array of that, or CharSequece
s most-likely is a String (rather than the rarely used short integer)
Usually abbreviations in symbols/names are ambiguous and can be considered a code-smell.
However there seems to be a historical and accepted convention or habit, especially for temporary / looping variables like:
int i
String s
char ch
The Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori, Chapter 1. Naming Conventions assorted them in a table:
Temporary variable names may be single letters such as i, j, k, m, and n for integers and c, d, and e for characters. Temporary and looping variables may be one-character names as shown in Table 1-1.
Even core Java methods have such (ambiguous) abbreviated parameter-names
if the method-context is obvious enough
that the contents and purpose of the parameter is self-explaining
E.g. String.contains(CharSequence s)
How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output. I want to do System.out.println(char1+char2+char3... and create a String word like this.
I could do
System.out.print(char1);
System.out.print(char2);
System.out.print(char3);
But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.
Thanks
Do you want to make a string out of them?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
Note that
String b = "b";
String s = "a" + b + "c";
Actually compiles to
String s = new StringBuilder("a").append(b).append("c").toString();
Edit: as litb pointed out, you can also do this:
"" + char1 + char2 + char3;
That compiles to the following:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.
I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:
String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";
The first is evaluated at compile-time. The second is evaluated at run-time.
So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.
If the characters are constant, this is fine:
String s = "" + 'a' + 'b' + 'c';
If however they aren't, consider this:
String concat(char... chars) {
if (chars.length == 0) {
return "";
}
StringBuilder s = new StringBuilder(chars.length);
for (char c : chars) {
s.append(c);
}
return s.toString();
}
as an appropriate solution.
However some might be tempted to optimise:
String s = "Name: '" + name + "'"; // String name;
into this:
String s = new StringBuilder().append("Name: ").append(name).append("'").toString();
While this is well-intentioned, the bottom line is DON'T.
Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.
For low-level optimisation the compiler is better at optimising code than you are.
Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?
You can use the String constructor.
System.out.println(new String(new char[]{a,b,c}));
You need to tell the compiler you want to do String concatenation by starting the sequence with a string, even an empty one. Like so:
System.out.println("" + char1 + char2 + char3...);
System.out.println(char1+""+char2+char3)
or
String s = char1+""+char2+char3;
You need a String object of some description to hold your array of concatenated chars, since the char type will hold only a single character. e.g.,
StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);
public class initials {
public static void main (String [] args) {
char initialA = 'M';
char initialB = 'P';
char initialC = 'T';
System.out.println("" + initialA + initialB + initialC );
}
}
I don't really consider myself a Java programmer, but just thought I'd add it here "for completeness"; using the (C-inspired) String.format static method:
String s = String.format("%s%s", 'a', 'b'); // s is "ab"
this is very simple approach to concatenate or append the character
StringBuilder desc = new StringBuilder();
String Description="this is my land";
desc=desc.append(Description.charAt(i));
simple example to selecting character from string and appending to string variable
private static String findaccountnum(String holdername, String mobile) {
char n1=holdername.charAt(0);
char n2=holdername.charAt(1);
char n3=holdername.charAt(2);
char n4=mobile.charAt(0);
char n5=mobile.charAt(1);
char n6=mobile.charAt(2);
String number=new StringBuilder().append(n1).append(n2).append(n3).append(n4).append(n5).append(n6).toString();
return number;
}
System.out.print(a + "" + b + "" + c);
This question already has answers here:
Concatenating null strings in Java [duplicate]
(5 answers)
Closed 7 years ago.
How to add whichever character between every character of a premade String? (JAVA)
For example, I have the String "Hello world" and I have to add '_' between every character of the String.
Any function or useful code I can use to do it?
I have to do an algorithm that make me output "H_e_l_l_o_ _w_o_r_l_d"
This is what I have:
public String example(String s) {
String s2 = null;
for(int i = 0; i < s.length(); i++){
s2 += s.charAt(i) + (((i+1) == 0) ? " " : "-");
}
return s2;
}
My output in the main class is being:
nullH-e-l-l-o- -w-o-r-l-d-
Don't know why
This looks like a homework assignment. So, I won't directly write out all the code.
String = "hello world";
Say, there is a variable len = str.length() - 1. Instead of doing it from index 0, we will start our for loop from len - 1. The character 'd' is at index len, and the '_' will have to be inserted right before that. This can be done by setting the string to str = str.substring(0,i) + "_" + str.substring(i+1);
You will have to use a for loop that starts from len - 1 and goes on till the index reached is 0.
Now, on every single iteration, when you are inserting a character assigning str to str.substring(0,i) + "_" + str.substring(i+1); causes you to make a new string object, which is absolutely horrible style. This can be solved by using a StringBuilder.
Does that make it clear?
In the future, refrain from posting questions without having done any work. This community is there to help you with solving issues that you may have in your solutions, not write your solutions for you.
I am trying to print the letters of the alphabet in caps. So I wrote this in a for loop:
System.out.print(Character.toChars(i));
//where i starts at 65 and ends at 90
This works fine and prints the letters but In my code I wanted to put a space between the letters to make it look nicer. So i did this:
System.out.print(Character.toChars(i) + " ")
Why does it print the memory address of the characters instead of the letter?
The solution I came up with was to explicitly convert the char to a new String object:
String character = new String(Character.toChars(i));
System.out.print (character + " ");
but I'm not quite sure why I can't just write "Character.toChars(i)"
In the first one Does the method(Character.toChars()) point to the address of the character and System.out.print is smart enough to print the value at that address? i.e the corresponding letter?
System.out.print(Character.toChars(i)) calls PrintStream.print(char[]), an overload that handles char[] specially.
Character.toChars(i) + " " is really equivalent to Character.toChars(i).toString() + " "; calling toString() on an array type results in a string representation of its address (this behaviour is directly inherited from Object).
A simpler solution for your particular case may be this:
System.out.println((char)i + " ");
The Character.toChars method returns char[], which will be represented as [C#<hex hashcode> in String form.
You don't need to use the toChars method (or do any casting at all):
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
You use string concatenation, with one side being an array of chars and the other a string and according to the Java language specification, then as the char array is not a primitive type, but a reference value (aka an object), its toString method is called. And as there is no specific method implemented for arrays, they inherit the method implementation from java.lang.Object, which prints the address.
On the other hand, System.out.print(Character.toChars(i)) calls a specific implementation of print for character arrays, see the documentation of PrintStream.
This question already has answers here:
StringBuilder vs String concatenation in toString() in Java
(20 answers)
Closed 6 years ago.
What is the benefit and trade-off of using a string builder over pure string concatenation?
new StringBuilder(32).append(str1)
.append(" test: ")
.append(val)
.append(" is changed")
.toString();
vs say
str1 + " test: " + val + " is changed".
str1 is a random 10 character string.
str2 is a random 8 character string.
In your particular example, none because the compiler internally uses StringBuilders to do String concatenation. If the concatenation occurred in a loop, however, the compiler could create several StringBuilder and String objects. For example:
String s= "" ;
for(int i= 0 ; i < 10 ; i++ )
s+= "a" ;
Each time line 3 above is executed, a new StringBuilder object is created, the contents of s appended, "a" appended, and then the StringBuilder is converted into a String to be assigned back to s. A total of 10 StringBuilders and 10 Strings.
Conversely, in
StringBuilder sb= new StringBuilder() ;
for(int i= 0 ; i < 10 ; i++ )
sb.append( "a" );
String s= sb.toString() ;
Only 1 StringBuilder and 1 String are created.
The main reason for this is that the compiler could not be smart enough to understand that the first loop is equivalent to the second and generate more efficient (byte) code. In more complex cases, it's impossible even for the smartest compiler to know. If you absolutely need this optimization, you have to introduce it manually by using StringBuilders explicitly.
The quick answer is the performance:
when you are using native String classes it operates immutable strings, which means when you are writing
String line = "java";
String sufix = " is awesome";
line = line + sufix;
it will create two strings "java" and " is awesome", than create a new third string "java is awesome" from previous two ("java" and "is awesome") which later are likely to be deleted by a garbage collector (because they are no more used in app). That is a slow solution.
More faster solution is an appliance of StringBuffer class which through the smart algorightms that provide a buffer (that is obvious from its name) for merging strings and as a result would not remove the initial string during the concatenation process.
In case you are writing single thread-application (no concurrancy issues during which multiple threads access same object) it is better to apply StringBuilder which has even faster performance than the initial StringBuffer class.