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 . "!"); } }
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. Of 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()
You must be a PHP programmer.
Use a + sign.
"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 + "!");
}
}
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
There are two basic answers to this question: 1. [simple and inefficient] Use the + operator (string concatination).
"your number is" + theNumber + "!" (as noted elsewhere) 2. [less simple and less inefficient]: 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");
Spaceisavaluablecommodity,asthissentancedemonstrates.