how to add 2 numbers in java

how to add 2 numbers in java

To add two numbers in Java, you can use the + operator.

Here's an example of how you could add two int variables:

int a = 2;
int b = 3;
int c = a + b; // c is now 5
S‮cruo‬e:www.lautturi.com

The + operator can also be used with other numeric data types, such as float, double, and long. For example:

float d = 2.5f;
float e = 3.0f;
float f = d + e; // f is now 5.5

double g = 2.5;
double h = 3.0;
double i = g + h; // i is also 5.5

In these examples, the + operator adds the operands and returns the result as the same data type as the operands.

Keep in mind that the + operator has a higher precedence than most other arithmetic operators in Java, which means that it will be evaluated before other operators in an expression. For example:

int j = 2 + 3 * 4; // j is 14
int k = (2 + 3) * 4; // k is 20

In the first example, the * operator has a higher precedence than the + operator, so the multiplication is performed first, and the result is added to 2. In the second example, the parentheses override the operator precedence, so the addition is performed first, and the result is multiplied by 4.

You can use parentheses to control the order of evaluation in an expression and to specify which operations should be performed first.

Created Time:2017-11-01 12:05:09  Author:lautturi