Saturday, 16 March 2013

Basic Calculator program in Java

I guess we are ready to write some good quality basic Java programs. One thing i would like to state here is that even if you are finding Java a bit new, you will eventually master it only by practice and hence it is essential to keep writing codes and not just understanding the theory.

        Let write a very basic Java program for calculator. There is no GUI involved since we have not covered Swing yet. This program will just take two numbers as input and perform the required operations like addition, subtraction etc.  Though it is basic it will cover most of the topics we have learned till now. I am writing and running Java programs on Eclipse and hence you may find it's snapshots here but you can even write codes and execute using command line or use other IDE's like Netbeans. So lets get started.

Java code for Calculator

      Lets first create a class where we implement the calculator logic.Create a new Java project in Eclipse called Calculator. Next create a package in it called basicCalculator. In this package make two new classes
class Calculation where we would implement the calculator logic and class ProgramLauncher which will have the main() function from which we will create class Calculation object and execute it.

Create class Calculation and insert the code below.

package basicCalculator;

import java.util.Scanner;

public class Calculation {

    private float firstOperannd;
    private float secondOperannd;
    private float result;
    private int operator;
    private Scanner input = new Scanner(System.in);
    private boolean exitCalculator = false;

    public void startCalculator() {
        while (!exitCalculator) {

            System.out.println("Enter 1 for addition \n"
                    + "Enter 2 for subtraction \n"
                    + "Enter 3 for multiplication \n"
                    + "Enter 4 for division \n" + "Enter 0 for Exit : ");
            operator = input.nextInt();

            switch (operator) {
            case 1:
                result = add();
                System.out.println("Result is " + result);
                break;

            case 2:
                result = subtract();
                System.out.println("Result is " + result);
                break;

            case 3:
                result = multiply();
                System.out.println("Result is " + result);
                break;

            case 4:
                result = divide();
                System.out.println("Result is " + result);
                break;

            case 0:
                exitCalculator = true;
                System.out.println("Calculator program Terminated \n");
                break;

            default:
                System.out.println("Please provide proper input \n");

            }
        }
    }

    private float add() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd + secondOperannd;
    }

    private float subtract() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd - secondOperannd;
    }

    private float multiply() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd * secondOperannd;
    }

    private float divide() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd / secondOperannd;
    }

}
  There are many point that need to be explained here so be patient. First lets get our code up and running.
So create next class class ProgramLauncher and insert the code below.


package basicCalculator;

public class ProgramLauncher {

    public static void main(String[] args) {

        Calculation calculator = new Calculation();
        calculator.startCalculator();

    }

}

    Just execute the program and try check the output for various test cases. For how to create a project, package , class, how to see standard output in eclipse please go through our post on Hello World.

When you execute this program you will see output something like below - 


 It clearly says what you need to input and what are the corresponding operations. If you press 0 program will terminate. Go ahead and try out various cases.More importantly try division by 0 or something like 0/0. I will explain these but you can go ahead and try it now.


Sample outputs


Understanding the Code

      Launcher code is very simple. All we do is create a Calculation class object and call the startCalculator() method. Just for the record we could call the method like calculator.startCalculator(); because the method is defined to be public. You can't do the same with other functions like add() as they are private. We will explain why we have taken such a decision but till then understand the program behavior.

    Lets go to our calculator logic code now.


Initializations



         We have defined two float operands firstOperannd and secondOperand.Similarly we have defined float result to store result, int operator to store values corresponding to various opearations and finally a scanner object to take use input. Again note that all these are instance variables and are private.So at any point of time you cannot access them using class Calculation object. They can only be manipulated using public functions provided. We also have exitCalculator to keep track whether to exit our program or not. Default value is set to false which means do not close the program unless user says so.

startCalculator() function

     Inside this function we have a while loop which keeps on executing unless exitCalculator is set to true.
Inside the loop we ask user to choose which operation he is interested in. He must input one of the available options i.e 0,1,2,3 or 4. We then have the switch statement which has operator as the argument. 

   Note : Switch statement supports String as argument only in JSE 7 . So i have used int to make the program run for everyone but if you are using  Java SE 7 you can go ahead and use String as input directly.

     Inside the switch statements we have cases each corresponding to different operations.We have defined separate functions for each operation i.e add(),subtract() etc and all we do in each case in switch statement is call these functions. Note the usage of break statement. We are computing the result in each case and printing the same on standard output.Each function computes the result and returns it back. Note that if user enters 0 then exitCalculator is set to true and the program terminates. For all other inputs default statement is executed which says you must provide correct input. Execution will continue unless user enter 0.

Why are functions like add() defined private?

         Before you define anything in Java or for that matter any programming language you must decide what is it going to be used for. Like in this case we know that add() function will only be used by

startCalculator() method and we don't want to allow any usage like objectName.add(). Hence functions are defined to be private. These functions can only be used in other functions of the same class.

Interesting cases

     Lets discuss some of the interesting cases that might arise in case of division.
  • 4/0 : What happens when i divide any number by 0. Technically you can't divide by 0 and you must get an error. You will get an error if you divide by zero in case on integers but in case of float you will get result as infinity. Note if you are using your firstOperand and secondOperand as int's you need to handle that divide by 0 runtime exception. Also if you use int and user types in something like 4.2 it will be truncated to 4.
  • 0/0: What happens when you divide 0 by a 0. Definitely not infinity in this case. Its a value called  NaN(not a number). Again if you use int you will get a runtime exception and program will terminate.These are some of the reasons why we have chosen float over int.


    Eclipse output snapshots



Output for 6/0 operation

Output for 0/0 operation


Do post any doubts you have in the comments sections.

Interview Question #4 What is immutable object? Can you write immutable object?

Immutable classes in java are classes whose object cannot be modified. Most instance variables and functions of immutable classes are also final in order from preventing subclasses to change the values by overriding methods which may compromise immutability. But there are other ways too, like declaring the members as private and changing it's value only in constructor.

For more details on how you can make your class immutable refer -

There can be more follow up questions like why would you make a class immutable? Well the answer is thread safety :) as immutable objects are inherently thread safe. More details in the linked answer above.

      For example in Java String is an immutable class. Once a string is created it cannot be modified.What happens when we call functions like .substring() one might ask. What it does is it simply creates and returns a new String object by taking the sub-string from the source string.

    Other example includes the wrapper classes for the primitive types: java.lang.Integer, java.lang.Byte, java.lang.Character, java.lang.Short, java.lang.Boolean, java.lang.Long, java.lang.Double, java.lang.Float etc.

Yo know why String was decided to be made immutable go through the following article -


Related Links

MCQ #10

Question) If you do not use curly braces for a while loop body , what will execute if the while condition is true?

Options)

  • Nothing
  • First statement of while
Answer) A copy of the value

Explanation)   If you do not provide braces to any loop statements then 1st statement is taken by default. Same is true even for if-else statement For more details refer the post on Loop Statements.

MCQ #9

Question) When you pass variable as an argument to a method call, what are you passing?

Options)
  • The actual value
  • A copy of the value
Answer) A copy of the value

Explanation)   Java works that way - pass by copy. For more details refer the post on Classes in Java.

MCQ #8

Question) Assume x = 0 and y = 3. What is the value of x after :  x = y++;

Options)

  • 0
  • 3
  • 4
Answer) 3

Explanation)   You must know the difference between pre-increment (++x) and post-increment(x++)  operators before you can answer this question.

Difference between ++x and x++

       Pre-increment operator(++x) will first increment the value of x and then carry out any operations that are due whereas in post-increment(x++) operator , operation is first carried out and then x in incremented.
     Sounds a bit hard to digest?
       Lets take an example to ensure we understand it completely.

int x = 0;
int y = 3;

Lets consider pre-increment operator first(++y)

x = ++y;

Result of above will be x = 4 and y = 4 because pre-increment operator first increments the value i.e value becomes 5 and then carries out the = operation.

Now lets see the post-increment operator(y++)

x = y++;

 Result of above will be x = 3 and y = 4 because post-increment operator first carries out the = operation i.e assigns value 3 to x and then increments the value of y to 4.

       Our question represents the second case(post-increment). So our answer is 3.

MCQ #7

Question) Can you compare boolean to an integer?

Options)

  • True
  • False
Answer) False

Explanation)   In Java boolean has value true or false and not 1 or 0 or anything else. So you just can't do it(Watch out C folks!).

MCQ #6

Question) x = false; y = true; What is the result of x && y

Options)
  • True
  • False
Answer) False

Explanation)  This is a straightforward question. Lets revise the entire table once -

x         y          x&&y
true    true      true
true    false     false
false   true      false
false  false      false

So basically in  expression1&&(and)expression2, entire expression is false if any one of the expressions or both are false. On the other hand this evaluates to be true only when both expressions are true.

Our question represents 3rd row of the above table.The answer is therefore False. 
t> UA-39527780-1 back to top