FAQs in Java: Add Two Numbers in Java
FAQs in Java: Add Two Numbers in Java

FAQs in Java: Add Two Numbers in Java

Program 1: Add Two Numbers in Java

A Java program to add two numbers using two different methods: using a simple method and using user input. This program demonstrates basic arithmetic operations and user interaction in Java.

Method 1: Using a Simple Method

Algorithm

Plaintext
Step 1: Start
Step 2: Define a public class named AddNumbers.

Step 3: Define the main method with the signature public static void 
        main(String[] args).

Step 4: Declare and initialize two integer variables num1 and num2.
Step 5: Call the add method with num1 and num2 as arguments and store the 
        result in the variable sum.
        
Step 6: Print the value of sum to the console.
Step 7: Define the add method that takes two integer parameters           
        and returns their sum.

Step 8: Exit

Program in Java

Java
public class AddNumbers {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        int sum = add(num1, num2);
        System.out.println("The sum is: " + sum);
    }

    public static int add(int a, int b) {
        return a + b;
    }
}

Step-by-Step Explanation:

Define the Class:

Java
public class AddNumbers {

  • The program starts by defining a public class named AddNumbers. In Java, every application begins with a class definition. The public keyword means this class is accessible by any other class.

Main Method Declaration:

Java
public static void main(String[] args) {

  • The main method is the entry point of any Java application. The public keyword means that the method is accessible from outside the class. static means that this method belongs to the class, not instances of the class. void means that this method does not return any value. String[] args is an array of strings that can store command-line arguments.

Declare and Initialize Variables:

Java
int num1 = 10;
int num2 = 20;

  • Two integer variables, num1 and num2, initialize with the values 10 and 20, respectively. They serve as operands in the addition operation.

Call the add Method:

Java
int sum = add(num1, num2);

  • The add method is called with num1 and num2 as arguments. The result of the addition is stored in the variable sum.

Print the Result:

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

The System.out.println method is used to print the result to the console. The + operator is used to concatenate the string “The sum is: “ with the value of sum.

Define the add Method:

Java
public static int add(int a, int b) {
    return a + b;
}

  • The add method is defined as public so it can be called from outside the class. static means it belongs to the class itself. int is the return type, meaning this method will return an integer value. The method takes two parameters, a and b, both of type int. The method returns the sum of a and b.

Summary:

This Java program demonstrates the following key concepts:

  • Class Definition: The program starts with a class definition, which is the blueprint for creating objects.
  • Main Method: The main method serves as the entry point of the program.
  • Variables: Integer variables are declared and initialized to store the numbers to be added.
  • Method Call: The add method is called to perform the addition operation.
  • Output: The result is printed to the console using System.out.println.
  • Method Definition: The add method is defined to encapsulate the addition logic, demonstrating how to create and use methods in Java.

By following these steps, the program effectively adds two numbers and displays the result, showcasing the basics of method definition and usage in Java.

Method 2: Using User Input

Algorithm

Plaintext
Step 1: Start
Step 2: Import the Scanner class from java.util.
Step 3: Define a public class named AddNumbersUserInput.

Step 4: Define the main method with the signature public static   void 
        main(String[] args).

Step 5: Create a Scanner object to read user input.
        
Step 6: Prompt the user to enter the first number and store the input in 
        num1.
Step 7: Prompt the user to enter the second number and store the input in 
        num2.
        
Step 8: Call the add method with num1 and num2 as arguments and store the 
        result in the variable sum.

Step 9: Print the value of sum to the console.
Step 10: Define the add method that takes two integer parameters          
         and returns their sum.

Step 11: Exit

Program in Java

Java
import java.util.Scanner;

public class AddNumbersUserInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter first number:");
        int num1 = scanner.nextInt();

        System.out.println("Enter second number:");
        int num2 = scanner.nextInt();

        int sum = add(num1, num2);
        System.out.println("The sum is: " + sum);
    }

    public static int add(int a, int b) {
        return a + b;
    }
}

Step-by-Step Explanation:

Import the Scanner Class:

Java
import java.util.Scanner;

  • The Scanner class is imported from the java.util package. This class is used to read input from various input sources, including the console.

Define the Class:

Java
public class AddNumbersUserInput {

  • The program defines a public class named AddNumbersUserInput. In Java, every application begins with a class definition. The public keyword means this class is accessible by any other class.

Main Method Declaration:

Java
public static void main(String[] args) {

  • The main method is the entry point of any Java application. The public keyword means that the method is accessible from outside the class. static means that this method belongs to the class, not instances of the class. void means that this method does not return any value. String[] args is an array of strings that can store command-line arguments.

Create a Scanner Object:

Java
Scanner scanner = new Scanner(System.in);

  • A Scanner object is created to read input from the standard input stream (the console). This allows the program to read user input.

Prompt User for First Number:

Java
System.out.println("Enter first number:");
int num1 = scanner.nextInt();

  • The program prints the message “Enter first number:” to the console.
  • The nextInt method of the Scanner object is called to read an integer input from the user. This input is stored in the variable num1.

Prompt User for Second Number:

Java
System.out.println("Enter second number:");
int num2 = scanner.nextInt();

  • Similarly, the program prints the message “Enter second number:” to the console.
  • The nextInt method of the Scanner object is called again to read another integer input from the user. This input is stored in the variable num2.

Call the add Method:

Java
int sum = add(num1, num2);

  • The add method is called with num1 and num2 as arguments.
  • The method returns the sum of num1 and num2, which is stored in the variable sum.

Print the Result:

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

  • The System.out.println method is used to print the result to the console.
  • The + operator concatenates the string “The sum is: ” with the value of sum, resulting in a complete message that is displayed in the console.

Define the add Method:

Java
public static int add(int a, int b) {
    return a + b;
}

  • The add method is defined as public so it can be called from outside the class. static means it belongs to the class itself. int is the return type, meaning this method will return an integer value. The method takes two parameters, a and b, both of type int.
  • The method returns the sum of a and b using the return statement.

Summary:

This Java program demonstrates the following key concepts:

  • Class Definition: The program starts with a class definition, which is the blueprint for creating objects.
  • Main Method: The main method serves as the entry point of the program.
  • Variables: Integer variables are declared and initialized to store the numbers to be added.
  • Method Call: The add method is called to perform the addition operation.
  • Output: The result is printed to the console using System.out.println.
  • Method Definition: The add method is defined to encapsulate the addition logic, demonstrating how to create and use methods in Java.

By following these steps, the program effectively adds two numbers and displays the result, showcasing the basics of method definition and usage in Java.

Program 2: Add Two Numbers in JavaScript

A JavaScript program to add two numbers using two different methods: using predefined values and using user input from prompt dialogs. This program demonstrates basic arithmetic operations and user interaction in JavaScript.

Method 1: Using Predefined Values

Algorithm

Plaintext
Step 1: Start
Step 2: Define a function add that takes two parameters                   
        and returns their sum.

Step 3: Call the add function with num1 and num2 as arguments and       
        store the result in the variable sum.

Step 4: Print the value of sum to the console using console.log
Step 5: Exit

Program in JavaScript

Java
function add(a, b) {
    return a + b;
}

let num1 = 10;
let num2 = 20;
let sum = add(num1, num2);

console.log("The sum is: " + sum);

Step-by-Step Explanation:

Define the add Function:

Java
function add(a, b) {
    return a + b;
}

  • The program starts by defining a function named add. Functions in JavaScript are declared using the function keyword followed by the function name.
  • The function takes two parameters, a and b, which are expected to be numbers.
  • The function returns the sum of a and b using the return statement.

Declare and Initialize Variables:

Java
let num1 = 10;
let num2 = 20;

  • Two variables, num1 and num2, are declared and initialized with the values 10 and 20, respectively. The let keyword is used to declare these variables, which means they are block-scoped and can be reassigned.

Call the add Function:

Java
let sum = add(num1, num2);

  • The add method is called with num1 and num2 as arguments. The result of the addition is stored in the variable sum.
  • The function returns the sum of num1 and num2, which is stored in the variable sum.

Print the Result to the Console:

Java
console.log("The sum is: " + sum);

  • The console.log function is used to print the result to the console.
  • The + operator concatenates the string “The sum is: “ with the value of sum, resulting in a complete message that is displayed in the console.

Summary:

This JavaScript program demonstrates the following key concepts:

  • Function Definition: The program defines a function add to encapsulate the addition logic.
  • Variable Declaration: The let keyword is used to declare and initialize variables.
  • Function Call: The add function is called to perform the addition operation with user-provided inputs.
  • Output: The result of the addition is printed to the console using console.log.

By following these steps, the program effectively adds two predefined numbers and displays the result, showcasing basic function definition and usage, variable declaration, arithmetic operations, and console output in JavaScript.

Method 2: Using User Input

Algorithm

Plaintext
Step 1: Start
Step 2: Define a function add that takes two parameters                   
        and returns their sum.

Step 3: Use the prompt function to get user input for the first        
        number and convert it to an integer using parseInt.             
        Store the result in num1.

Step 4: Use the prompt function to get user input for the second       
        number and convert it to an integer using parseInt.             
        Store the result in num2.
Step 5: Call the add method with num1 and num2 as arguments and         
        store the result in the variable sum.
        
Step 6: Call the add function with num1 and num2 as arguments and       
        store the result in the variable sum.
        
Step 7: Print the value of sum to the console using console.log.

Step 8: Exit

Program in JavaScript

Java
function add(a, b) {
    return a + b;
}

let num1 = parseInt(prompt("Enter first number:"));
let num2 = parseInt(prompt("Enter second number:"));
let sum = add(num1, num2);

console.log("The sum is: " + sum);

Step-by-Step Explanation:

Define the add Function:

Java
function add(a, b) {
    return a + b;
}

  • A function named add is defined. Functions in JavaScript are declared using the function keyword followed by the function name.
  • The function takes two parameters, a and b, which are expected to be numbers.
  • The function returns the sum of a and b using the return statement.

Prompt for User Input and Parse to Integer:

Java
let num1 = parseInt(prompt("Enter first number:"));

  • The prompt function displays a dialog box that prompts the user to enter a value. This value is returned as a string.
  • The parseInt function converts the string returned by prompt to an integer. This ensures that the user input is treated as a number.
  • The result is stored in the variable num1.

Prompt for Second User Input and Parse to Integer:

Java
let num2 = parseInt(prompt("Enter second number:"));

  • Similarly, the user is prompted to enter the second number. The input is converted to an integer using parseInt and stored in the variable num2.

Call the add Function:

Java
let sum = add(num1, num2);

  • The add method is called with num1 and num2 as arguments. The result of the addition is stored in the variable sum.
  • The function returns the sum of num1 and num2, which is stored in the variable sum.

Print the Result to the Console:

Java
console.log("The sum is: " + sum);

  • The console.log function is used to print the result to the console.
  • The + operator concatenates the string “The sum is: “ with the value of sum, resulting in a complete message that is displayed in the console.

Summary:

This JavaScript program demonstrates the following key concepts:

  • Function Definition: The program defines a function add to encapsulate the addition logic.
  • User Interaction: The prompt function is used to collect user input, and parseInt ensures that the input is treated as an integer.
  • Function Call: The add function is called to perform the addition operation with user-provided inputs.
  • Output: The result of the addition is printed to the console using console.log.

By following these steps, the program effectively collects two numbers from the user, adds them, and displays the result, showcasing basic input handling, arithmetic operations, and output in JavaScript.


Discover more from lounge coder

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from lounge coder

Subscribe now to keep reading and get access to the full archive.

Continue reading