08: Write code to add, subtract, multiply, and divide given numbers?

A trivial coding example (i.e. a Calculator) tackled using the following programming paradigms in Java not only to perform well in coding interviews, but also to learn these programming paradigms.

Approach 1: Procedural Programming
Approaches 2 – 4: Object Oriented Programming
Approach 5: Functional Programming (Java 8)

Approach 1: Procedural

Output: result=13

Approach 2: OOP

When you have more mathematical operations, add more command classes. In OOP, switch statements are unsightly and hard to maintain. The above OOP approach eliminates the need for switches. This is also a good example of the “Open-Close design principle”.

Output: result=13

Approach 3: OOP

This extends approach-2 to make the client code more elegant to use with “*”, “+”, etc.

Output: result=13

Approach 4: OOP

This extends approach-2 & approach-3 to make the client code more elegant “.” notations [e.g. blah.calc(‘+’, 6).calc(‘*’, 6).calc(‘-‘, 1).blah] with the help of “Builder” design pattern.

Output: result=13

Approach 5: FP

Java 8 functional programming. You can see Lambdas, functional interfaces, default methods, and static methods in action.

Output: result=13

This is a very trivial example, and some solutions could be bit of an over kill.

Q. Which one would you favor, and why?
Q. Would you provide a different solution?

Java & Big Data Interview FAQs

Java Key Areas Interview Q&As

800+ Java Interview Q&As

Java & Big Data Tutorials