How to concatenate int values in java?
Asked Answered
F

22

45

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.

Frizzly answered 20/4, 2010 at 11:42 Comment(3)
Use Horner-Scheme: ((((a * 10 + b) * 10 + c) * 10 + d) * 10 + e. Why do you lose b, when you add them up?Nickolai
More on Horner-Scheme: #1991880Bobstay
I suppose you mean you "lose" a not b, iff a==0.Parch
I
54

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.

Irony answered 20/4, 2010 at 11:46 Comment(8)
Dirty? What? #2506974Bobstay
@polygenelubricants: well, I happen to disagree with the majority opinion on that point.Irony
I'm not a fan of this - I think a + "" + b + "" + c + "" + d + "" + e would be clearer, myself - although more longwinded, of course. It's just too easy to look at "a + b" and think that will be adding the integers together, IMO.Conrad
@polygenelubricants: Thanks for pointing out that question - I hadn't spotted it before...Conrad
I think I would use a StringBuffer with chained appends.Tumer
Isn't direct string concatenation a little inefficient compared to StringBuffer/Builder methods ?Zymo
@Andrei: What is the root of all evil again? Besides, one-line string concatenation will be compiled into a StringBuilder. It's only in more complex scenarios (usually involving loops) where concatenation should be avoided.Irony
What about "" + (a) + (b) + (c) + (d) + (e)? Just as concise, and it draws just enough attention to itself that you go "Ah, I see what's going on here...".Bobstay
N
37

This worked for me.

int i = 14;
int j = 26;
int k = Integer.valueOf(String.valueOf(i) + String.valueOf(j));
System.out.println(k);

It turned out as 1426

Natashianatassia answered 7/11, 2012 at 11:35 Comment(0)
B
36

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();
}
Bobstay answered 20/4, 2010 at 11:47 Comment(4)
Thanks everyone for your answers, I'm always working with 5 digits, but in many cases they start with 0, so Michael's way's the wat way ;-)Frizzly
This also works with 0s. For 5 digits, it always give the same result as Michael's; its only advantage (which you don't need) is that it works with variable number of digits.Bobstay
Varargs + foreach combo is best.Bobstay
this is cleaner and has better performance too... string concatenation is messy and results in a lot of unnecessary string generation. modern VMs may mitigate that... not sure, but i think this is much cleaner nonetheless.Amatruda
H
17

just to not forget the format method

String s = String.format("%s%s%s%s%s", a, b, c, d, e);

(%1.1s%1.1s%1.1s%1.1s%1.1s if you only want the first digit of each number...)

Headmost answered 20/4, 2010 at 14:31 Comment(2)
this is the best solution so farTetragrammaton
Or, if you are printing to the console, System.out.printf("%d%d%d%d%d", a, b, c, d, e);Adeno
S
13

Actually,

int result = a * 10000 + b * 1000 + c * 100 + d * 10 + e;
String s = Integer.toString(result);

will work.

Note: this will only work when a is greater than 0 and all of b, c, d and e are in [0, 9]. For example, if b is 15, Michael's method will get you the result you probably want.

Sisile answered 20/4, 2010 at 11:43 Comment(1)
Consider that considered, added it to the note.Sisile
I
7

How about not using strings at all...

This should work for any number of digits...

int[] nums = {1, 0, 2, 2, 1};

int retval = 0;

for (int digit : nums)
{
    retval *= 10;
    retval += digit;
}

System.out.println("Return value is: " + retval);
Ibex answered 7/6, 2011 at 22:1 Comment(2)
the question was: "How do i concatenate these values so that i end up with a String..."!Headmost
This helped me with a palindrome problem, Thanks!Juta
B
5

If you multiply b by 1000, you will not lose any of the values. See below for the math.

10000
    0
  200
   20
    1
=====
10221
Blastopore answered 20/4, 2010 at 11:44 Comment(2)
what if my first value is equal to 0?Frizzly
It would still work. It will give you the proper value. Do you need it to be exactly 5 chars long?Blastopore
P
5
StringBuffer sb = new StringBuffer();
sb.append(a).append(b).append(c)...

Keeping the values as an int is preferred thou, as the other answers show you.

Padishah answered 20/4, 2010 at 11:44 Comment(2)
StringBuilder in this case is an overkill; plain old + is fine and much more readable.Bobstay
Readable for who? I prefer the StringBuffer/StringBuilder in this case, and agreeing with Jon Skeets comment to Michaels answer.Mailemailed
C
4

Others have pointed out that multiplying b by 1000 shouldn't cause a problem - but if a were zero, you'd end up losing it. (You'd get a 4 digit string instead of 5.)

Here's an alternative (general purpose) approach - which assumes that all the values are in the range 0-9. (You should quite possibly put in some code to throw an exception if that turns out not to be true, but I've left it out here for simplicity.)

public static String concatenateDigits(int... digits)
{
    char[] chars = new char[digits.length];
    for (int i = 0; i < digits.length; i++)
    {
        chars[i] = (char)(digits[i] + '0');
    }
    return new String(chars);
}

In this case you'd call it with:

String result = concatenateDigits(a, b, c, d, e);
Conrad answered 20/4, 2010 at 11:46 Comment(0)
A
4

For fun... how NOT to do it ;-)

String s = Arrays.asList(a,b,c,d,e).toString().replaceAll("[\\[\\], ]", "");

Not that anyone would really think of doing it this way in this case - but this illustrates why it's important to give access to certain object members, otherwise API users end up parsing the string representation of your object, and then you're stuck not being able to modify it, or risk breaking their code if you do.

Asparagus answered 20/4, 2010 at 13:6 Comment(0)
S
3

Using Java 8 and higher, you can use the StringJoiner, a very clean and more flexible way (especially if you have a list as input instead of known set of variables a-e):

int a = 1;
int b = 0;
int c = 2;
int d = 2;
int e = 1;
List<Integer> values = Arrays.asList(a, b, c, d, e);
String result = values.stream().map(i -> i.toString()).collect(Collectors.joining());
System.out.println(result);

If you need a separator use:

String result = values.stream().map(i -> i.toString()).collect(Collectors.joining(","));

To get the following result:

1,0,2,2,1

Edit: as LuCio commented, the following code is shorter:

Stream.of(a, b, c, d, e).map(Object::toString).collect(Collectors.joining());
Sapowith answered 26/3, 2017 at 10:17 Comment(1)
Or : Stream.of(a, b, c, d, e).map(Object::toString).collect(Collectors.joining()); Or: IntStream.of(a, b, c, d, e).mapToObj(Integer::toString).collect(Collectors.joining());Perspicacity
S
2
int number =0;
int[] tab = {your numbers}.

for(int i=0; i<tab.length; i++){
    number*=10;
    number+=tab[i];
}

And you have your concatenated number.

Showoff answered 3/12, 2019 at 11:18 Comment(0)
S
1

I would suggest converting them to Strings.

StringBuilder concatenated = new StringBuilder();
concatenated.append(a);
concatenated.append(b);
/// etc...
concatenated.append(e);

Then converting back to an Integer:

Integer.valueOf(concatenated.toString());
Sparklesparkler answered 20/4, 2010 at 11:45 Comment(4)
He seems to want a String as the end result, so the parsing is unnecessary (and if that were actually wanted, the correct solution would be to just add up the numbers without any String tomfoolery)Irony
Good point on him wanting a String, but if the numbers were just added, the result would be 6, not 10221...Sparklesparkler
@polygenelubricants: Totally agree with you - forget this answer, Michael or Jon's answer are the best solutions going on the information given :)Sparklesparkler
@polygenelubricants: ... or yours ;-)Sparklesparkler
S
1

Use StringBuilder

StringBuilder sb = new StringBuilder(String.valueOf(a));
sb.append(String.valueOf(b));
sb.append(String.valueOf(c));
sb.append(String.valueOf(d));
sb.append(String.valueOf(e));
System.out.print(sb.toString());
Shiner answered 20/4, 2010 at 11:46 Comment(0)
M
1

People were fretting over what happens when a == 0. Easy fix for that...have a digit before it. :)

int sum = 100000 + a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.valueOf(sum).substring(1));

Biggest drawback: it creates two strings. If that's a big deal, String.format could help.

int sum = a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.format("%05d", sum));
Mousey answered 20/4, 2010 at 12:10 Comment(0)
A
1

You can Use

String x = a+"" +b +""+ c+""+d+""+ e;
int result = Integer.parseInt(x);
Abeyance answered 20/4, 2010 at 12:19 Comment(1)
You can just "" + a + b + cLashay
I
1

Assuming you start with variables:

int i=12;
int j=12;

This will give output 1212:

System.out.print(i+""+j); 

And this will give output 24:

System.out.print(i+j);
Isosceles answered 10/4, 2013 at 15:59 Comment(0)
G
0

Best solutions are already discussed. For the heck of it, you could do this as well: Given that you are always dealing with 5 digits,

(new java.util.Formatter().format("%d%d%d%d%d", a,b,c,d,e)).toString()

I am not claiming this is the best way; just adding an alternate way to look at similar situations. :)

Gilges answered 20/4, 2010 at 15:18 Comment(0)
D
0

NOTE: when you try to use + operator on (string + int) it converts int into strings and concatnates them ! so you need to convert only one int to string

public class scratch {

public static void main(String[] args){

    int a=1;
    int b=0;
    int c=2;
    int d=2;
    int e=1;
    System.out.println( String.valueOf(a)+b+c+d+e) ;
}
Dewberry answered 21/12, 2020 at 6:55 Comment(0)
M
0
//Here is the simplest way 
public class ConcatInteger{
    public static void main(String[] args) {
      
      int [] list1={1,2,3};
      int [] list2={1,9,6};
      
      String stNum1="";
      String stNum2="";
   
      for(int i=0 ; i<3 ;i++){
        stNum1=stNum1+Integer.toString(list2[i]);   //Concat done with string  
      }
      
      for(int i=0 ; i<3 ;i++){
        stNum2=stNum2+Integer.toString(list1[i]);
      }
      
      int sum= Integer.parseInt(stNum1)+Integer.parseInt(stNum2); // Converting string to int
      
         System.out.println(sum);  
    } 
}
Morsel answered 6/8, 2021 at 19:23 Comment(0)
A
-1

Couldn't you just make the numbers strings, concatenate them, and convert the strings to an integer value?

Autocephalous answered 26/12, 2015 at 15:3 Comment(0)
I
-4
public class joining {

    public static void main(String[] args) {
        int a=1; 
        int b=0;
        int c=2;
        int d=2;
        int e=1;

        String j = Long.toString(a);
        String k = Long.toString(b);
        String l = Long.toString(c);
        String m = Long.toString(d);
        String n = Long.toString(e);

       /* String s1=Long.toString(a);    // converting long to String
        String s2=Long.toString(b);
        String s3=s2+s1;
        long c=Long.valueOf(s3).longValue();    // converting String to long
        */

        System.out.println(j+k+l+m+n);  
    }
}
Incoherent answered 2/10, 2015 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.