String n = new String( char + int) adds but should concatenate - java

I have the following code for a class:
public class sqrt
{
public sqrt()
{
char start = 'H';
int second = 3110;
char third = 'w';
byte fourth = 0;
char fifth = 'r';
int sixth = 1;
char seventh = 'd';
float eighth = 2.0f;
boolean ninth = true;
String output = new String(start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);
System.out.println(output);
}
}
The required output is:
H3110 w0r1d 2.0 true
However, this outputs the following:
3182 w0r1d 2.0 true
I can only assume this is because it sees the numerical (ASCII) value of char 'H' and adding it to int 3110.
My question is:
Shouldn't new String() convert each item within to a string and concatenate them?
If I change the output to:
String output = start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth +
" " + ninth;
It does the same thing, and adds the value of char and int together before concatenating the rest.
I know I can overcome this by adding a "" + before start, and I suppose that explains why it is seeing the ASCII value of char 'H' (because it looks at the next value, sees it's an int, and goes from there?), but I'm confused as to why the new String() isn't working as intended.
PS, I want to write better questions, and I know I am still a bit of a beginner here, so any advice in that regard would be appreciated as well. PMs are more than welcome, if anyone is willing to take the time to help.
PPS, If I figure out why this is, I will post the answer myself, but I am really trying to learn this, and I'm just very confused.

I can only assume this is because it sees the numerical (ASCII) value of char 'H' and adding it to int 3110.
That's perfectly correct.
Shouldn't new String() convert each item within to a string and concatenate them?
The String constructor has no control over this, because the expression start + second + " " + ... is evaluated before.
The concise approach here is to use a StringBuilder. It has methods to accept all primitive types and arbitrary objects.
String output = new StringBuilder().append(start).append(second).append(' ')
.append(third).append(fourth).append(fifth).append(sixth).appends(seventh)
.append(' ').append(eighth).append(' ').append(ninth).toString();
or
StringBuilder builder = new StringBuilder();
builder.append(first);
builder.append(second);
builder.append(' ');
builder.append(third);
builder.append(fourth);
builder.append(firth);
builder.append(sixth);
builder.append(seventh);
builder.append(' ');
builder.append(eighth);
builder.append(ninth);
String output = builder.toString();

Shouldn't new String() convert each item within to a string and concatenate them?
new String() has nothing to do with it. First we evaluate the expression. Then we pass the value of the expression to the String constructor.
So first of all we're adding a char to an int; this is integer addition. Then the result of that (3112) is converted to string so it can be concatenated to the string " ". Thereafter at least one operand is a String therefore concatenation applies.

I'm confused as to why the new String() isn't working as intended.
It's working as intended, which is to initialize a new String object representing the data passed to it.
Shouldn't new String() convert each item within to a string and
concatenate them?
Currently, you're using this overload of the String constructor which states:
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; in other words, the newly
created string is a copy of the argument string.
Essentially, as the string you passed to the String constructor is 3182 w0r1d 2.0 true the new string object is a copy of that. Nothing else is performed.

you can use the code below since characters cannot be changed to string inherently
so:
String output = new String(String.valueOf(start) + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);

Related

splitting string by spaces and new lines

I'm trying to split a string into an array. This should be fine as str.split(" ") should work fine, however the string is actually in the form of "xyz 100b\nabc 200b\ndef 400b". I'm wondering what the best way to handle this is. I also need to return 4 strings in the format they gave. Below is how I'm trying it now, but it's not splitting the array up correctly. My goal is to get the array split to ["xyz", "100b", "abc", "200b", "def", "400b"]
public static String solution(String words){
String array[] = words.split(" ");
/*
There's a lot of other code manipulating the array to get 4 figures in the
end. This doesn't matter, it's just splitting the array and the return that
is my issue
In the end I will have 4 integers that I want to return in a similar way
that they gave them to me.
*/
return "answer 1" + String.valueOf(num1) + "b\n" +
"answer2 " + String.valueOf(num2) + "b\n" +
"answer 3" + String.valueOf(num3) + "b\n" +
"answer4 " + String.valueOf(num4) + "b\n";
}
EDIT:
String array [] = str.split("\n| ") will split the array as I needed, thank you A.Oubidar
I hope i understood your question right but if you're looking to extract the number and return them in the specific format you could go like this :
// Assuming the String would be like a repetition of [word][space][number][b][\n]
String testString = "xyz 100b\nabc 200b\ndef 400b";
// Split by both endOfLine and space
String[] pieces = testString.split("\n| ");
String answer = "";
// pair index should contain the word, impair is the integer and 'b' letter
for (int i = 0; i < pieces.length; i++) {
if(i % 2 != 0 ) {
answer = answer + "answer " + ((i/2)+1) + ": " + pieces[i] + "\n";
}
}
System.out.println(answer);
This is the value of answer after execution :
answer 1: 100b
answer 2: 200b
answer 3: 400b
You should put this code in the "return" instead of the one you already have:
return "answer 1" + array[0] + "b\n" +
"answer 2 " + array[1] + "b\n" +
"answer 3" + array[2] + "b\n" +
"answer 4 " + array[3] + "b\n";
The split() method takes one regular expression as argument. This: input.split("\\s+") will split on whitespace (\s = space, + = 1 or more).
Your question is unclear, but if you're supposed to extract the '100', '200', etc, regular expressions are also pretty good at that. You can throw each line through a regular expression to extract the value. There are many tutorials (just google for 'java regexp example').

Why do we print variable values like this?

I want to know why we concatenate a dummy string with a variable while printing its value.
Eg.
system.out.print(var + " ");
Concatenation with an empty string is a technique some developers use to convert any value to a string. It's unnecessary with System.out.print as that accepts any value anyway. I prefer using String.valueOf anyway:
String text = String.valueOf(variable);
This is clearer in terms of the purpose being converting a value to a string, rather than concatenation.
However, in the case you've given, it's possible that the developer wasn't just using concatenation for that purpose - but actually to get the extra space. For example:
int var1 = 1, var2 = 2, var3 = 3;
System.out.print(var1 + " ");
System.out.print(var2 + " ");
System.out.print(var3 + " ");
Those will all print on the same line:
1 2 3
Other options include:
Using a StringBuilder to build up the string before printing it
Putting it all into a single System.out.print call: System.out.print(var1 + " " + var2 + " " + var3);
Using printf instead: System.out.printf("%d %d %d", var1, var2, var3);
Extremely sorry. The question was l1.setText(var+" "); and it is done because a text field cannot take an integer value, so we concatenate a dummy string at the end of it, so the integer value in var can be printed.
Thank you all for helping me out!

Recursion- reversing String

I believe that I have a decent understanding of recursion (factorial etc), however in the following example in reversing a string I do not understand the line. Can someone please explain what it does?
return reverseString(str.substring(1)) + str.charAt(0);
Full Code from method:
public static String reverseString(String str){
if(str.length()<2){
System.out.println("reached Base case");
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
The call substring(1) takes the first character off of the string. That is fed into the recursive call, which reverse all but the last character. Then, the first character is appended, completing the reversal.
Example:
reverseString("abc") =>
reverseString("bc") + 'a' =>
(reverseString("c") + 'b') + 'a' =>
("c" + 'b') + 'a' =>
"cb" + 'a' =>
"cba"
It takes everything after the first character and calls the recursive function. The first character is put at the end of the string. This results in a reversal.
return reverse(Everything after the first) + the first
return reverseString(str.substring(1)) + str.charAt(0);
For example, the String is HelloWorld
Then "HelloWorld".substring(1) returns "elloWorld"
and "HelloWorld".charAt(0) returns "H"
You take the first letter and add it to the end od the string. But before, you do it again with the first part. In the end, this algorithm reverses the string.
Let's take this string:
str = "Reverse";
The value of str.substring(1) is "everse".
The value of str.charAt(0) is "R".
I think you can take it from there if you understand recursion.
It inefficiently reverses the string by placing each successive sub-string on the stack until it reaches a length less then 2; it then reverses the characters by popping those results off the stack and appending the first character to the sub-string. It is inefficient because Java includes the StringBuilder class and that has a reverse method.
Try to think of reversing a string in this manner:
//reverse of a string can be expressed as the last character
//plus the reverse of everything remaining. For example, if we had
//"food", you would have "d" + reverse("foo"), which is "d" + "oof"
//which gives you "doof". So:
reverse(str) = str[str.length - 1] + reverse(str[0:str.length - 2]);
reverse(str[0]) = str[0] //reverse of a 1 character string is the character itself
So apply this to the string abcd:
You have:
reverse("abcd") = "d" + reverse("abc")
reverse("abc") = "c" + reverse("ab")
reverse("ab") = "b" + reverse("a")
reverse("a") = "a";
Now when you substitute you have:
reverse("ab") = "b" + "a" = "ba"
reverse("abc") = "c" + "ba" = "cba"
reverse("abcd") = "d" + "cba" = "dcba"
Think about how you can write code that mimics this behavior.

why does java starts treating everything as a String once it has encountered a string in System out statement?

i am learning java and practicing it daily,i wrote the following code and wondered about the output
class test
{
public static void main(String args[])
{
System.out.println(1+2+ " = " +10+2);
}
}
here the output was 3=102,and wondered about the following "Java starts treating everything as a String once it has encountered a string in System out statement"
can anyone explain this ?i m confused why does it accept it as string?
Java parses program text without regard to the types of expression. As motivation, consider if they were fields written after the method in the class. So, as string concatenation and addition share the same operator, we have
1+2+ " = " +10+2
is equivalent to
((((1+2)+ " = ") +10)+2)
Folding constants, we have
(((3+ " = ") +10)+2)
(("3 = " +10)+2)
("3 = 10"+2)
"3 = 102"
"Java starts treating everything as a String once it has encountered a
string in System.out statement"
It's completely wrong. System.out is a static instance of the class PrintStream.
PrintStream has many overloaded versions of the println() method and the one in your example accepts String as parameter. You are using + operator and it's for concatenation of Strings unless the operands are both numbers.
System.out.println(3+5+"."); // println(String) is invoked.
System.out.println(3+5); // println(int) is invoked.
+ with String becomes String concatenation operator and not a addition operator.
1 + 2 + 10 + 2 will be equal to 15 as a simple addition
while
1 + 2 + "+" + 10 + 2 will be treated as
1. 1 + 2 output will be 3 as it is a simple addition
2. 3 + = (String) output will be 3= because it is String concatenation
3. 3= (String) + 10 + 2 will be String concatenation and not a simple addition so output will be 3=102
(1+2) -- two integres additoin will result int 3
(3 + " = ") -- this will result int + String = String (concatination)
("3=") -- String + any thing (data type) will result String

How do I concatenate two strings in Java?

I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

Categories

Resources