Java Program to Add Two Numbers using Pointers

This post covers a program in Java, that adds two numbers using pointer.

Add Two Numbers using Pointer in Java

The question is, write a Java program to find the sum of two numbers using pointer. The program given below is its answer:

import java.util.Scanner;

class IntegerObject
{
   public int value;
}

public class fresherearth
{
   public static void main(String[] args)
   {
      int a, b, sum;
      IntegerObject pointerOne = new IntegerObject();
      IntegerObject pointerTwo = new IntegerObject();
      
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the First Number: ");
      a = scan.nextInt();
      System.out.print("Enter the Second Number: ");
      b = scan.nextInt();
      
      pointerOne.value = a;
      pointerTwo.value = b;
      
      sum = pointerOne.value + pointerTwo.value;
      System.out.println("\nSum = " +sum);
   }
}

The sample run of above Java program on finding the addition of two numbers using pointer, with user input 100 and 200 as two numbers, is shown in the snapshot given below:

Java Program add two numbers using pointer

The above program can also be written as:

import java.util.Scanner;

public class fresherearth
{
   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the First Number: ");
      int numOne = scan.nextInt();
      System.out.print("Enter the Second Number: ");
      int numTwo = scan.nextInt();
      
      IOb pOne = new IOb();
      IOb pTwo = new IOb();
      
      pOne.val = numOne;
      pTwo.val = numTwo;
      
      System.out.println("\nSum = " +(pOne.val + pTwo.val));
   }
}
class IOb
{
   public int val;
}

You'll get same output as of previous program. This program is created to avoid misunderstanding about any variable used in both the program.

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »