Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing multiple array elements concatenated in Java

The code below returns a strange result. The problem is somehow in Line 46. Adding a String as argument to println solves the issue

System.out.println("result" + arr[i] + arr[j]+ arr[k]);
System.out.print("\n" + arr[i] + arr[j]+ arr[k]);

I don't understand why println wouldn't work. Is it not possible to concatenate arrays elements without inserting a string in java?

import java.util.Scanner;
public class Main 
{
    public static void main(String Args[])
    {
        System.out.print("How many digits: ");
        Scanner obj = new Scanner(System.in);
        int n = obj.nextInt();
        int[] arr = new int[n];
        for(int i=0; i<n; i++)
        {
            System.out.print("Enter number "+ (i+1) +": ");
            arr[i]=obj.nextInt();
        }
        combinations(arr);
    }

    public static void combinations(int[] arr) {
        int count=0;
        for(int i=0; i<arr.length; i++) {
            for(int j=0; j<arr.length; j++) {
                for(int k=0; k<arr.length; k++) {
                    System.out.println(arr[i] + arr[j]+ arr[k]);//Line 46 
                    count++;
                }
            }
        }
        System.out.print("\n" + "Total combinations: "+ count);
    }
}
like image 965
Asim Maqsood Avatar asked Apr 17 '26 04:04

Asim Maqsood


2 Answers

This is because the + operator has different behaviours depending on its operands: either it adds numbers or it concatenates strings.

You have declared your array as [int]. This means that when you do:

arr[i] + arr[j]+ arr[k];

you are calculating the sum of three ints which returns an int. This is defined in the Java specification as:

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.

However, when you write:

"result" + arr[i] + arr[j]+ arr[k];

because the first element is a String, Java will convert all the other elements into Strings and concatenate them all together.

This is described in the Java specification as:

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time.

Finally, when you call System.out.println it will evaluate the expression given as parameter first, then check if its type is String and call toString on it if it is not.

like image 188
Rodrigue Avatar answered Apr 19 '26 18:04

Rodrigue


System.out.println(arr[i] + arr[j]+ arr[k]);

When it runs, it finds ints next to each other so it sums them

So the rule is easy :

  • String + anythingElse : concatenate
  • Number + Number : sum (int, double, float, ...)

To avoid that you're mandatory to add empty String between or a separator :

System.out.println(arr[i] + ""+ arr[j] +""+ arr[k]);
System.out.println(arr[i] + "-"+ arr[j] +"-"+ arr[k]);
like image 24
azro Avatar answered Apr 19 '26 16:04

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!