โ Java: How to Add Two Numbers (With and Without User Input)
๐งฒ Introduction โ Why Learn This?
Adding two numbers is one of the most foundational tasks in Java programming. Whether youโre building a calculator app, handling user form submissions, or performing arithmetic in backend logic โ understanding how to add numbers is an essential first step.
โ In this guide, you’ll learn how to:
- Add two numbers using hardcoded values
- Add two numbers using user input
- Handle both integers and floating-point numbers
- Understand basic Java syntax and arithmetic
๐งฎ Method 1: Add Two Numbers Using Hardcoded Values
public class AddNumbers {
public static void main(String[] args) {
int a = 15;
int b = 25;
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
โ Explanation:
int a = 15;
andint b = 25;
: Declare two integers.int sum = a + b;
: Add the values.System.out.println(...)
: Print the result.
๐ This is great for testing logic or basic understanding.
๐งพ Method 2: Add Two Numbers Using User Input
โ
With Scanner
(for Integers)
import java.util.Scanner;
public class AddUserInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
โ Explanation:
Scanner
is used to take user input from the console.nextInt()
reads integers.- Values are stored, added, and printed.
โ
With Scanner
(for Decimal Numbers)
import java.util.Scanner;
public class AddDoubles {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first decimal: ");
double a = sc.nextDouble();
System.out.print("Enter second decimal: ");
double b = sc.nextDouble();
double sum = a + b;
System.out.println("Sum: " + sum);
}
}
โ Explanation:
- Use
double
instead ofint
for floating-point input. nextDouble()
reads decimals from the user.
๐ก Tips
- โ
Use
int
when working with whole numbers. - โ
Use
double
for precise arithmetic (e.g., prices, weights). - ๐ Always validate user input in production apps.
๐ Summary
Adding numbers in Java is simple, yet foundational. Whether you’re taking hardcoded values or reading input from users, this operation sets the stage for more advanced mathematical operations and applications.
๐งพ Key Takeaways:
- Use
+
operator to add numbers - Use
Scanner
for user input - Use
int
for whole numbers anddouble
for decimals - Validate and handle input properly in real apps
โFAQs โ Adding Two Numbers in Java
โ How do I add two numbers in Java?
Use the +
operator: int sum = a + b;
.
โ Can I add float or double values?
Yes, use double
or float
types instead of int
.
โ How do I read user input in Java?
Use Scanner
class with methods like nextInt()
or nextDouble()
.
โ What if I want to add more than two numbers?
You can extend the logic by declaring more variables or using arrays and loops.
Share Now :