Reputation: 51
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);
}
}
Upvotes: 3
Views: 3774
Reputation: 3687
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 int
s 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 String
s 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.
Upvotes: 5
Reputation: 54168
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
: concatenateNumber + 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]);
Upvotes: 1