X Tutup
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Ron McLeod
Saloon Keepers:
  • Tim Holloway
Bartenders:

Simple Java program to calculate sum of two numbers

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everyone,
I am learning Java basics and practicing simple programs.
Below is a basic Java program that takes two numbers from the user and prints their sum.
This example helps beginners understand:
User input using Scanner
Variable declaration
Basic arithmetic operation
Output using System.out.println()
Please review the code and let me know if there are better practices or improvements.
Thank you.

import java.util.Scanner;

public class SumOfTwoNumbers {

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);

       System.out.print("Enter first number: ");
       int num1 = sc.nextInt();

       System.out.print("Enter second number: ");
       int num2 = sc.nextInt();

       int sum = num1 + num2;

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

       sc.close();
   }
}
 
Marshal
Posts: 82158
593
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use the code button.
Your code includes the potentially dangerous mistake of closing a Scanner reading System.in. You should close Scanners reading everything except System.in. But you should use the technique described here, not the close() method.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic
X Tutup