Addition Of Two Numbers In Java With Program Examples

In this article, we will learn about Addition Of Two Numbers In Java. This article also has the best program examples for finding the sum or addition of two numbers by using the method and command-line arguments.

Addition Of Two Numbers In Java
Addition Of Two Numbers In Java

One of the four basic math operations is addition. The others are subtraction, multiplication, and division. When you add two whole numbers together, you get the total amount, also called the sum of the numbers.

Addition of two numbers

In Java, it’s very easy to find the sum of two or more numbers. First, name and set the values of two variables in sum.

Another place to store the total number of things. Apply the (+) operator between the variables that have been declared and store the result.

For Example:

class Main {

    public static void main(String[] args) {

        System.out.println("Enter two numbers");

        // declares a numbers int

        int first = 20;

        int second = 30;

        System.out.println(first + " " + second);

        // add two numbers

        int sum = first + second;

        System.out.println("The sum is: " + sum);

    }

}

Output:

50

Addition of Two Numbers Using Command Line Arguments

In Java, command-line arguments are passed to the Java program to add when it runs. Using command-line arguments in a program is very easy. They are kept in the String array that is passed to the args[] parameter of the main() method.

public class SumOfNumbers4

{

    public static void main(String args[])

    {

        int x = Integer.parseInt(args[0]); //first arguments   

        int y = Integer.parseInt(args[1]); //second arguments  

        int num1 = x + y;

        System.out.println("The sum of x and y is: " + num1);

    }

}

Output:

The sum of x and y is: 101

Addition of two numbers using java scanner class

In Java, the scanner class allows the program to read what the user inputs. We ask for two numbers as num1 and send them to the user-defined sum method().

For Example:

//declared a string args scanner

import java.util.Scanner;
public class SumOfNumbers2

{

    public static void main(String args[])

    {

        int x, y, sum;

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the first number: ");

        x = sc.nextInt();

        System.out.print("Enter the second number: ");

        y = sc.nextInt();

        sum = sum(x, y);

        System.out.println("The sum of two numbers x and y is: " + sum);

    }

    //method that calculates the sum and prints the sum

    public static int sum(int a, int b)

    {

        int sum = a + b;

        return sum;

    }

}

Output:

Enter the first number: 26

Enter the second number: 34

The sum of two numbers x and y is: 60

Conclusion

I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.

Modern Java file I/O patterns

  • Files.readString / writeString. Java 11+ one-liners for whole-file text.
  • Files.readAllLines / lines. readAllLines loads everything into memory. lines returns a Stream for large-file streaming.
  • Files.newBufferedReader / Writer. Modern replacement for FileReader/FileWriter with encoding control.
  • Path vs File. Prefer Path (java.nio.file) , richer API, better error handling.
  • StandardCharsets.UTF_8. Explicit encoding avoids platform-dependent bugs.

Working code example

import java.nio.file.*;
import java.io.*;
import java.util.stream.*;

public class FileIOPatterns {
    // Read whole file (small files)
    public String readAll(String path) throws IOException {
        return Files.readString(Paths.get(path));
    }

    // Stream lines (large files)
    public long countErrorLines(String path) throws IOException {
        try (Stream<String> lines = Files.lines(Paths.get(path))) {
            return lines.filter(l -> l.contains("ERROR")).count();
        }
    }

    // Write text
    public void writeReport(String path, String data) throws IOException {
        Files.writeString(Paths.get(path), data,
            StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    }
}

Common pitfalls

  • Forgetting to close streams. Use try-with-resources , never rely on garbage collection.
  • Loading huge files with readAllLines. Use Files.lines with a Stream for anything large.
  • Assuming platform default encoding. Windows may default to windows-1252, Linux to UTF-8 , explicit encoding avoids surprises.

Best practices

  • Path.of / Paths.get. Preferred over new File() , the entire nio.file API works with Path.
  • Use StandardCharsets.UTF_8. Explicit charset in every read/write.
  • Use Files.walk for directory traversal. Streaming API , cleaner than recursive listFiles().

Debugging Java code in 2026

  • IntelliJ IDEA debugger. Set breakpoints, inspect variable state, step through call stacks. Use conditional breakpoints (right-click) to break only on specific values.
  • System.out.println. Fastest to write, useful for quick sanity checks. Prefer a logger (SLF4J + Logback) for anything that lives longer than 5 minutes.
  • Logger.info / debug. Use SLF4J parameterized messages: log.info("Processed rows in ms", count, elapsed); , avoids the string-concat cost when the log level is off.
  • Assertions. Enable with java -ea MyProgram. Guard programming invariants , never used for user-input validation.
  • JVM flags. -XshowSettings, -verbose:class, -verbose:gc for runtime diagnostics.

Modern Java tooling

  • Maven / Gradle. Standard build tools. Maven uses XML, Gradle uses Groovy or Kotlin DSL. Gradle is faster on incremental builds.
  • JUnit 5. The go-to test framework. Use annotations, assertions, and parameterized tests.
  • SpotBugs / Error Prone. Static analyzers that catch real bugs.
  • JMH. The right way to microbenchmark on the JVM.
  • JDK Mission Control + Flight Recorder. Production profiling with low overhead.

Where to go next

  • Spring Boot. Most common Java web framework.
  • Quarkus. Faster startup, lower memory , ideal for serverless.
  • Micronaut. Excellent GraalVM native-image support.
  • Hibernate / JPA. Standard ORM for database access.
  • Project Loom (Java 21+ stable). Virtual threads make blocking I/O practically free.

Frequently asked questions

What is the best way to read a file in modern Java?

For small text files, use Files.readString(Path) (Java 11+) or Files.readAllLines(Path). For large files, use Files.lines(Path) with try-with-resources for line-by-line streaming. Both are in java.nio.file and are safer and shorter than the old FileReader + BufferedReader pattern.

Should you use FileReader or BufferedReader in Java?

Use BufferedReader wrapped around FileReader for performance , BufferedReader reads a chunk at a time instead of one byte at a time. Better yet, use java.nio.file methods (Files.readAllLines, Files.lines) which handle the buffering for you.

What tools should you use to write Java in 2026?

IntelliJ IDEA Community Edition (free) is the top pick , excellent auto-complete, refactoring, and debugging. Eclipse and VS Code with the Java extension pack are strong alternatives. Use Maven or Gradle for dependency management, JUnit 5 for testing, and SpotBugs or Error Prone for static analysis.

What is the difference between JDK and JRE?

JDK (Java Development Kit) includes the compiler (javac), development tools, and the JRE. JRE (Java Runtime Environment) contains only what is needed to run compiled Java , the JVM and standard library. As of Java 11, Oracle stopped shipping a standalone JRE , you install a JDK for both.

How does Java compare to other JVM languages like Kotlin or Scala?

Java is the most widely adopted, has the largest ecosystem, and gets the newest LTS features (Loom, Panama, Valhalla). Kotlin is more concise and popular for Android. Scala focuses on functional programming and big-data (Spark). All three interoperate on the JVM.

Glenn Azuelo

Programmer & Technical Writer at PIES IT Solution

Glenn Azuelo is a programmer and writer at PIES IT Solution, author of 40+ PHP tutorials, Java capstone projects, and Python game guides at itsourcecode.com. Specializes in PHP built-in functions (string manipulation, arrays, filesystem, magic methods), Java Windows Forms projects for BSIT capstone (chat application, POS, faculty management, memory game), and Python game programming with Pygame (chess, blackjack, dice).

Expertise: PHP, PHP Tutorials, PHP Built-in Functions, PHP String Functions, PHP Array Functions, PHP Magic Methods, Java, Java Swing, Windows Forms, Python, Pygame, Capstone Projects  ·  View all posts by Glenn Azuelo →

Leave a Comment