Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate int values in java?

I have the following values:

int a=1;  int b=0; int c=2; int d=2; int e=1; 

How do i concatenate these values so that i end up with a String that is 10221; please note that multiplying a by 10000, b by 1000.....and e by 1 will not working since b=0 and therefore i will lose it when i add the values up.

like image 503
Shamli Avatar asked Apr 20 '10 11:04

Shamli


People also ask

Can you concatenate an integer?

You can use the String concatenation operator + to concatenate integers to a string in a clear and concise manner. Note that the compiler implicitly constructs an intermediate StringBuilder object, append the integers, and then call the toString() method.

How do I concatenate an integer to a string?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.

How do you concatenate variables in Java?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.

How do you concatenate numbers?

This means that you can no longer perform any math operations on them. To combine numbers, use the CONCATENATE or CONCAT, TEXT or TEXTJOIN functions, and the ampersand (&) operator. Notes: In Excel 2016, Excel Mobile, and Excel for the web, CONCATENATE has been replaced with the CONCAT function.


2 Answers

The easiest (but somewhat dirty) way:

String result = "" + a + b + c + d + e 

Edit: I don't recommend this and agree with Jon's comment. Adding those extra empty strings is probably the best compromise between shortness and clarity.

like image 127
Michael Borgwardt Avatar answered Oct 09 '22 12:10

Michael Borgwardt


Michael Borgwardt's solution is the best for 5 digits, but if you have variable number of digits, you can use something like this:

public static String concatenateDigits(int... digits) {    StringBuilder sb = new StringBuilder(digits.length);    for (int digit : digits) {      sb.append(digit);    }    return sb.toString(); } 
like image 41
polygenelubricants Avatar answered Oct 09 '22 11:10

polygenelubricants