![]() |
VOOZH | about |
In Java, adding numbers is a basic operation that can be performed in multiple ways depending on the use case, such as direct arithmetic, bit manipulation, loops, command-line arguments, or handling very large numbers.
Example:
Sum = 15
Explanation: here we are adding two integers using '+' operator;
Below are some of the approaches to perform addition.
The most straightforward way to add two numbers in Java is by using the + operator.
Sum = 30
Explanation: The + operator performs arithmetic addition of the two integer values.
Addition can also be done without using the + operator by applying bitwise operations.
Sum = 40
Explanation: XOR calculates the sum bits, AND with left shift calculates carry bits, and the loop continues until no carry remains.
Java allows passing input values at runtime using command-line arguments.
👁 Adding_Two_Numbers_Using_Command_Line
Explanation: The arguments are converted from String to int using Integer.parseInt() and then added.
When numbers exceed the range of int or long, Java provides the BigInteger class.
Sum of Two BigIntegers: 15966888634697288357207200089
Explanation: String values are converted into BigInteger objects and added using the add() method to avoid overflow.