Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, April 8, 2019

Sum of two numbers in Java

How To Find Sum of two numbers in Java:

This tutorial we will see how to find out sum of two numbers in Java. Everyone knows how to sum two number using plus(+) symbol in mathematical representation formula.

First we have to read the two number from user what values need to be summed. Scanner class is used to read input from user and have to pass System.in to the Scanner class.

Sum of two numbers in Java


System.in represents standard input from keyboard. Code semantic is given below.

Scanner scanner = new Scanner(System.in);


Now we have prepared scanner object to take input from keyboard and nextLine() method in scanner class to read line which is given by user as data type of String. But actually need input in the format of integer.

Below code to convert string to int.

int nummber1 = Integer.parseInt(num1);

Program Sum of two numbers in Java:

package org.java.w3schools.examples.programs;

import java.util.Scanner;

public class SumTwoNumbers {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter first number..");
        String num1 = scanner.nextLine();

        System.out.println("Enter second number..");
        String num2 = scanner.nextLine();

        int nummber1 = Integer.parseInt(num1);
        int nummber2 = Integer.parseInt(num2);

        int sum = nummber1 + nummber2;

        System.out.println("Sum of two numbers : " + sum);
    }
}


Interview Question: 

How to Swap two numbers in Java without using third variable.

4 Ways How to read a file in Java, CSV Example Programs


Output:


Enter first number..
10
Enter second number..
20
Sum of two numbers : 30

Please leave your questions in comments.

1 comment:

Please do not add any spam links in the comments section.