How to Concatenate Int Values in Java

How so I concatenate int values without adding them? (Java)

Use a stringbuilder

StringBuilder sb = new StringBuilder();

sb.append(num1);
sb.append(num2);
sb.append(num3);
sb.append("-");
sb.append(num4);
sb.append("-");
sb.append(num5);

System.out.println("Your phone number is: " + sb.toString());

Is it possible to add integer values while concatenating Strings?

Yes.

System.out.println(str + (c + k)); 

You can change order of execution by adding parentheses (same way as in math).

concatenating two int in java

Anything in java.lang.* should be fair game...

int a = Integer.parseInt(Integer.toString(9) + Integer.toString(10));

Addendum:

I do not like the following the syntax because the operator overloading doesn't declare intent as clearly as the above. Mainly because if the empty string is mistakenly taken out, the result is different.

int a = Integer.parseInt(9 + "" + 10);

Concatenate list of ints in java 8

If you wanna do it using reduce convert Integers into Strings and then use Accumulator function

Optional<String> result = numbers.stream().map(i->i.toString()).reduce((i,j)->i+", "+j);

Or you can simply use Collectors.joining

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

Concatenate two integer to get a float in Java

Try Float.parseFloat(), like this:

float fb2 = Float.parseFloat(fb + "." + fb1);

You could also use Float.valueOf() combined with String.valueOf(), like this:

float fb2 = java.lang.Float.valueOf(String.valueOf(fb) +"."+ 
String.valueOf(fb1));

Concatenating two int[]

You can use IntStream.concat in concert with Arrays.stream to get this thing done without any auto-boxing or unboxing. Here's how it looks.

int[] result = IntStream.concat(Arrays.stream(c), Arrays.stream(d)).toArray();

Note that Arrays.stream(c) returns an IntStream, which is then concatenated with the other IntStream before collected into an array.

Here's the output.

[1, 34, 3, 1, 5]



Related Topics



Leave a reply



Submit