How to Add Two Numbers in Java - Step by Step Examples
How to Add Two Numbers in Java ?
Answer
To add two numbers in Java, you can use the '+' operator.
✐ Examples
1 Adding Two Numbers
In this example,
- We declare two variables
num1
andnum2
and initialize them with the numbers to be added. - We add these two numbers using the
+
operator and store the result in a variablesum
. - Finally, we print the value of
sum
to the console usingSystem.out.println()
.
Java Program
// Adding Two Numbers
public class Main {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
}
}
Output
Sum of 10 and 20 is: 30
Summary
In this tutorial, we learned How to Add Two Numbers in Java language with well detailed examples.