How to combine two lines in Java?

I am trying to concatenate strings in Java. Why is this not working?

public class StackOverflowTest { public static void main(String args[]) { int theNumber = 42; System.out.println("Your number is " . theNumber . "!"); } } 
+60
java string-concatenation
Sep 20 '10 at 17:29
source share
21 answers

You can concatenate strings using the + operator:

 System.out.println("Your number is " + theNumber + "!"); 

theNumber implicitly converted to String "42" .

+87
Sep 20 '10 at 17:31
source share
β€” -

The concatenation operator in java is + , not .

Read this (including all subsections) before you begin. Try to stop thinking about php path;)

To expand your view of using strings in Java, the + operator for strings is actually converted (by the compiler) to something similar:

 new StringBuilder().append("firstString").append("secondString").toString() 
+45
Sep 20 '10 at 17:31
source share

There are two main answers to this question:

  1. [simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
  2. [less simple]: use StringBuilder (or StringBuffer ).
 StringBuilder value; value.append("your number is"); value.append(theNumber); value.append("!"); value.toString(); 

I recommend not using such operations:

 new StringBuilder().append("I").append("like to write").append("confusing code"); 

Edit: starting with Java 5, the string concatenation operator is translated into a StringBuilder called the compiler. Because of this, both methods above are the same.

Note: a space item is a valuable item, while at the same time it demonstrates

Warning: Example 1 below generates multiple instances of StringBuilder 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; 
+14
Sep 20 '10 at 17:56
source share

Out of the box, you have 3 ways to insert the variable value into a String as you are trying to achieve:

1. The easiest way

You can simply use the + operator between String and any type of object or primitive, it will automatically combine String and

  1. In the case of an object, the value of String.valueOf(obj) corresponding String " null " if obj is null otherwise the value is obj.toString() .
  2. In the case of a primitive type, the equivalent of String.valueOf(<primitive-type>) .

An example with a non- null object:

 Integer theNumber = 42; System.out.println("Your number is " + theNumber + "!"); 

Exit:

 Your number is 42! 

Example with a null object:

 Integer theNumber = null; System.out.println("Your number is " + theNumber + "!"); 

Exit:

 Your number is null! 

Example with a primitive type:

 int theNumber = 42; System.out.println("Your number is " + theNumber + "!"); 

Exit:

 Your number is 42! 

2. Explicit way and potentially the most effective

You can use StringBuilder (or StringBuffer thread-safe legacy 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) 

Exit:

 Your number is 42! 

Behind the scenes, this is actually how recent Java compilers convert all String concatenation done with the + operator, the only difference with the previous method is that you have full control.

Indeed, compilers will use the default constructor , therefore the default capacity is ( 16 ), since they have no idea what the final length of the String will be to build, which means that if the final length is greater than 16 , the capacity will be necessarily extended, which has a price in performance plan.

Therefore, 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 better initial capacity. For example, in our example, we create a String whose length is greater than 16, so for best performance it should be rewritten as follows:

The example is optimized:

 int theNumber = 42; StringBuilder buffer = new StringBuilder(18) .append("Your number is ").append(theNumber).append('!'); System.out.println(buffer) 

Exit:

 Your number is 42! 

3. The most read way

You can use the String.format(locale, format, args) or String.format(format, args) which both use Formatter to create your String . This allows you to specify the format of your final String , using placeholders 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); 

Exit:

 Your number is 42! Your number is still 42 with printf! 

The most interesting aspect of this approach is the fact that we have a clear idea of ​​what will be the last String because it is much easier to read, and it is much easier to maintain.

+7
Oct. 14 '16 at 16:41
source share

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); 
+6
Apr 10 '17 at 7:45
source share

You must be a PHP programmer.

Use the + sign.

 System.out.println("Your number is " + theNumber + "!"); 
+4
Sep 20 '10 at 17:31
source share

"+" instead of "."

+3
Sep 20 '10 at 17:30
source share

Use + to concatenate strings.

 "Your number is " + theNumber + "!" 
+3
Sep 20 '10 at 17:31
source share

This should work

 public class StackOverflowTest { public static void main(String args[]) { int theNumber = 42; System.out.println("Your number is " + theNumber + "!"); } } 
+3
Sep 20 '10 at 17:32
source share

For the exact operation of concatenating two strings, use:

 file_names = file_names.concat(file_names1); 

In your case, use + instead .

+3
Mar 28 '13 at 13:24
source share

For best performance, use str1.concat(str2) , where str1 and str2 are string variables.

+3
Mar 07 '14 at 18:34
source share

There is a " + " in the java concatenate symbol. If you are trying to concatenate two or three lines when using jdbc, 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 only for spaces.

+2
Jul 19 '14 at 11:14
source share

In Java, the concatenation character is "+", not ".".

+1
Sep 20 '10 at 17:32
source share

"+" not "."

But be careful with string concatenation. Here is a link representing some of the thoughts from IBM DeveloperWorks .

+1
Sep 20 '10 at 17:33
source share

First method: you can use the β€œ+” sign to concatenate strings, but this always happens in print. Another way: the String class includes a method for combining two strings: string1.concat (string2);

0
Oct 22 '13 at 18:44
source share
 import com.google.common.base.Joiner; String delimiter = ""; Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!")); 

This may be an overkill answer to the op question, but it's good to know about more complex join actions. This question in stackoverflow praises the overall Google search queries in this area, so it's good to know.

0
Jun 20 '16 at 8:15
source share

you can use stringbuffer, stringbuilder and, like everything that was mentioned before me, "+". I'm not sure how fast the β€œ+” (I think it is the fastest for shorter lines), but the longer I think the builder and buffer are approximately equal (the builder is a little faster because it is not synchronized).

0
Jul 18 '16 at 14:52
source share

You can concatenate strings using the + operator:

 String a="hello "; String b="world."; System.out.println(a+b); 

Output:

hello world.

What he

0
Aug 02 '16 at 11:11
source share

here is an example for reading and concatenating 2 lines without using a third 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); } } 
0
Oct 06 '16 at 15:16
source share

There are several ways to do this, but Oracle and IBM say using + is bad practice because, in essence, every time you concatenate String, you end up creating additional objects in memory. It will use extra space in the JVM, and your program may run out of space or it may run slower.

Using StringBuilder or StringBuffer is the best way to do this. Please look at the comment by Nicholas Phillato above, for example, related to StringBuffer .

 String first = "I eat"; String second = "all the rats."; System.out.println(first+second); 
0
Feb 11 '19 at 7:40
source share

Thus, from a skillful answer, you could get an answer why your fragment is not working. Now I will add my suggestions on how to do this effectively. This article is a good place where the author talks about different ways of combining strings, as well as the results of comparing time between different results.

Different ways to concatenate strings in Java

  1. Using the + operator (20 + "")
  2. Using the concat in the String Class
  3. Using StringBuffer
  4. Using StringBuilder

Method 1:

This is not a recommended method. What for? When you use it with integers and characters, you should clearly remember about converting the integer to toString() before adding a string, otherwise this will lead to the processing of characters in an ASCI int and doing the addition on top.

 String temp = "" + 200 + 'B'; //This is translated internally into, new StringBuilder().append( "" ).append( 200 ).append('B').toString(); 

Method 2:

This is an internal implementation of the concat method concat

 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 contents to the newly allocated buffer. This way it will be too slow if you do it on more lines.

Method 3:

It is thread safe and relatively fast compared to (1) and (2). It uses a StringBuilder internal use, and when it allocates new memory for the buffer (say its current size is 10), it increases it by 2 * size + 2 (which is 22). Therefore, when the array becomes larger and larger, it will actually work better, since it does not need to allocate a buffer size for each append call each time.

  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 will be the fastest for String concatenation, since it is not Thread Safe . If you are not sure that your class using this is one ton, I highly recommend not using this one.

In short, use a StringBuffer until you are sure that your code can be used by multiple threads. If you're damn sure your class is singleton, then use StringBuilder to concatenate.

0
Jul 14 '19 at 11:55
source share



All Articles