Why are total_amount
and tax_amount
concatenated together as strings instead of added together as numbers in the below println
statement?
public class Test{
int total_amount,tax_amount;
public void cal(int total_amount,int tax_amount)
{
System.out.println("Total amount : "+total_amount+tax_amount);
}
public static void main(String[] args) {
new Test().cal(100, 20);
}
}
Output Total amount : 10020
Expected Total amount : 120
That's because of operator precedence. Basically, your code is doing the equivalent of:
System.out.println(("Total amount : " + total_amount) + tax_amount);
So when total_amount
is 100, and tax_amount
is 20, that ends up being:
System.out.println(("Total amount : " + 100) + 20);
which is evaluated as:
System.out.println("Total amount : 100" + 20);
which is evaluated as:
System.out.println("Total amount : 10020");
Options:
Use parentheses to show how you want the operations to be grouped:
System.out.println("Total amount : " + (total_amount + tax_amount));
Perform the summation first, and store it in a new variable:
int totalIncludingTax = total_amount + tax_amount;
System.out.println("Total amount : " + totalIncludingTax);
As a side note, I'd recommend:
underscores_separating_words
, e.g. taxAmount
instead of tax_amount
total_amount
but then print something different with a label of Total amount
With code formatting as well, you'd end up with:
public class Test {
public static void main(String[] args) {
calculateTotal(100, 20);
}
private static void calculateTotal(int preTaxTotal, int tax) {
int totalIncludingTax = preTaxTotal + tax;
System.out.println("Total amount: " + totalIncludingTax);
}
}
(You should also consider what you're going to do for non-integer prices... I'd recommend either using integers, but make that the number of cents/pennies/whatever, or using BigDeciml
to represent prices.)
See more on this question at Stackoverflow