int variables being concatenated instead of added inside System.out.println()

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
Jon Skeet
people
quotationmark

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:

  • Following Java naming conventions, using camelCase instead of underscores_separating_words, e.g. taxAmount instead of tax_amount
  • Naming variables more carefully - it's odd to have a variable called total_amount but then print something different with a label of Total amount
  • Using a static method here, as you're not actually using the fields in your object. (Those fields are confusing, as you're not using them.)

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.)

people

See more on this question at Stackoverflow