Java IoT Authors: Zakia Bouachraoui, Liz McMillan, Kevin Benedict, Elizabeth White, Yeshim Deniz

Related Topics: Java IoT

Java IoT: Article

How To Build a Matrix Calculator for Java-Enabled Mobile Phones

Implementing a Matrix Calculator on the J2ME Platform

The matrix is an indispensable tool for engineers and mathematicians. Matrices are used in many engineering applications for solving linear equations, differential equations of n-order, and so on.

Mathematicians have developed matrix arithmetic to help engineers in solving their engineering problems. It is generally very easy to understand and perform. However, due to the mere size of the computations involved, it's prone to errors. Even at the school level, students want to use a calculator to solve (or at least verify the results of) their school assignments on matrices. Some of the scientific calculators support Matrix Arithmetic. These scientific calculators are not always handy.

In recent days, mobile phones have become abundant and one may dare to say that virtually every literate person in this world possesses a mobile handset. Many of the present-day mobile handsets are Java-enabled. Thus, we decided to develop a simple application for performing Matrix Arithmetic that would run on such Java-Enabled mobile devices.

Due to the restrictive user-interface of a mobile device, the application interface development poses several challenges. The application discussed in this article has overcome some of these challenges to implement an elegant user interface for the application.

The Matrix Calculator application allows users to perform operations such as Add, Subtract, Multiply and Transpose. These operations may be cascaded on multiple Matrices. The cascaded operations on Matrices may be done in any order subject to the rules of Matrix arithmetic. For example, you may multiply two Matrices and add the resultant matrix to the third matrix. We restrict the matrix dimensions to a limit of 5 x 5 to provide a decent output on the limited screen area. However, the application may be extended to higher dimensions easily.

There are several difficulties encountered when you try to implement such applications on slow processing devices with limited resources. Some of the factors one may need to consider are speed, compatibility and limited memory. Mobile devices have very limited processing power. Due to limited processing power, the floating point computations must be carefully restricted. Another important factor to consider is limited memory resource. RAM available for Java Midlets running on J2ME mobile platform is typically of the order of 500KB. This requires careful selection of data structures and careful allocation of resources in order to optimize memory usage. Even displaying a large Matrix on screen has its own problems due to the limited screen area available on mobile devices. To meet this limitation, the current application restricts the use of matrix having maximum dimension of 5 x.5. Finally and most importantly, the code needs to be highly optimized to meet all the above requirements.

Before we discuss the implementation of Matrix calculator, we will briefly discuss Matrix Arithmetic for the benefit of those who may need to refresh their knowledge of what they learned way back in schools.

Definition of Matrix

Matrix is an arrangement of elements into rows and columns where number of rows and number of columns are real numbers.

Consider the following Example of a Matrix


This is a 4 x 2 matrix with 4 rows and 2 columns.

Matrix Addition:

Two matrices of same dimensions can be added by adding their corresponding elements.

Consider the following example of addition.


Matrix Subtraction

Two matrices of equal dimension can be subtracted by subtracting their corresponding elements. The resultant matrix formed has same dimensions as that of input matrix.


Matrix Multiplication:

Matrix multiplication involves more calculations as compared to matrix addition and subtraction. Rules for multiplication are:

  • Two matrices of different dimensions can be multiplied provided number of columns of first matrix equals to number of rows of second matrix.
  • Dimensions of Resultant matrix are dependent on the dimensions of operand matrices.

Matrix Transpose:

Transpose of a matrix is calculated by turning rows into columns and vice-versa.


To understand the capabilities of our matrix calculator consider the following example.


This operation involves many calculations. It involves successive addition, multiplication, transpose, addition and a subtraction in the sequence specified by the expression. Such computations can be performed very easily by using our matrix calculator.


The matrix calculator is developed for J2ME platform supporting CLDC1.0. Figure 1 illustrates the program flow.

Implementation overview:


Diagram Convention:
Dotted Lines: Conditional Flow
Bold Lines: Non Conditional Flow

The Matrix Calculator application consists of several Forms which are displayed to the user in the sequence shown in Figure 1.

When you start the Calculator Midlet, it displays a welcome note briefly describing the application. This is followed by the form that accepts the dimensions for the first operand matrix from the user. The user may enter the matrix dimensions upto 5 x 5. The application can be easily extended to accept dimensions higher than this, by simply changing the constant MAX_DIMENSION in the program code. We restrict the dimension size to 5 x 5 to avoid the screen cluttering for higher dimensions.

After the dimensions are input, the program accepts the element data from the user. The user is prompted for each cell value. The entered cell values are displayed on the same screen below the user input.

Once the complete data for the first matrix is accepted, the user is presented with another Form that displays the list of operations that the user may opt to perform on the matrix. The defined operations are add, subtract, multiply and transpose.

In case of transpose, the input matrix is transposed and the result is displayed to the user. In case of other operations, the user is requested to enter the data for the second operand matrix. In case, of add and subtract operations, the dimensions for the second matrix are determined from the dimensions of the first matrix and the user is simply prompted to enter the element values for the second matrix. In case of multiply operation, the number of rows for the second matrix is taken to be the same as the number of columns of the first matrix. The user is then prompted for the second dimension (number of columns) for the second matrix. Once the dimensions for the second matrix are determined, the application accepts the element values from the user as in the earlier case. The application then performs the selected operation on the two matrices and replaces the contents of the first matrix with the resultant matrix. The user may now perform another operation on the resultant matrix. At the end, the user selects Done operation, to display the resultant matrix on the screen.

We shall now discuss the implementation of the Midlet class and each of the classes used by the application.

When you load the application in the mobile device, the application is displayed with the name Calculator as shown in the screen shot below:


The MatrixCalc class

This is the main application class that extends from MIDlet.

	public class MatrixCalc extends MIDlet {

The class declares two variables for holding two operand matrices.

	private int firstInputMatrix[][],secondInputMatrix[][];

It also declares variables for storing the dimensions for two matrices.

	private int Matrix1FirstDim, Matrix1SecondDim;
	private int Matrix2FirstDim, Matrix2SecondDim;

The class declares appropriate accessor/mutator methods for its private variables. When the Midlet loads, the startApp method of the Midlet gets called.

    public void startApp() throws MIDletStateChangeException {
        operation='\0'; // Initial Operation set to null.
        WelcomeForm frm=new WelcomeForm(this); // Create Welcome Note.
        Display.getDisplay(this).setCurrent(frm); // Attach welcome form

In the startApp method, we set the firstTime flag to true. This flag directs the application to store the two input matrices in appropriate variables. The startApp method creates an instance of WelcomeForm which displays itself on screen after its instantiation is done.

The MatrixCalc class also declares two methods called AllocateFirstMatrix and AllocateSecondMatrix for setting the dimensions for the two respective matrices and allocating the storage for its elements.

	public void AllocateFirstMatrix(int FirstDim,int SecondDim) {
        this.Matrix1FirstDim = FirstDim;
        this.Matrix1SecondDim = SecondDim;
        firstInputMatrix= new int[FirstDim][SecondDim];

The MatrixCalc class also declares a method called setFirstInputMatrix that reallocates the storage for the first matrix and copies the contents of the matrix received as the first argument to the method.

   public void setFirstInputMatrix(int[][] first,int nDimension,
			int mDimension) {
   	firstInputMatrix = new int[nDimension] [mDimension];
      for(int i=0;i<nDimension;i++) {
      	for(int j=0;j<mDimension;j++) {

The WelcomeForm class

The user interface for the welcome form is shown in the screen shot below:


The WelcomeForm class extends Form and implements CommandListener interface.

	public class WelcomeForm extends Form implements CommandListener

The CommandListener interface defines actions for the user commands. We create two Command objects as follows:

	Command cmdOK = new Command("OK", Command.OK, 1);
  	Command exit = new Command("Exit", Command.EXIT, 1);

In the init() method of the class, we add the two commands and set the command listener to the current object.


In the command action for OK command, we create an instance of DimInputForm. This form requests the user to enter dimensions for the first matrix.

  	public void commandAction(Command c, Displayable d) {
   	if (c == cmdOK) {
      	DimInputForm frm = new DimInputForm(calc);

The program calls the readTwoDimensions method of the DimInputForm and attaches the current form to the display.

		frm.readTwoDimensions(); // reads two dimensions for the matrix

The DimInputForm class

The screen shot of the DimInputForm is shown in following figure:


The DimInputForm extends Form and implements CommandListener.

	public class DimInputForm  extends Form implements CommandListener

The class declares a method called readTwoDimensions that displays two numeric TextFields to the user and sets the command listener for accepting the user input. In the action command, we validate the dimensions and in case of the error we display an appropriate message to the user. Once the dimensions input is validated, the application allocates memory for the matrix by calling AllocateFirstMatrix method of the MatrixCalc class.

	calc.AllocateFirstMatrix(FirstDim,SecondDim); // Allocate Size.

In case of matrix multiply operation, the user needs to input only one dimension for the second matrix. The program determines the first dimension of the second matrix from the dimensions of the first matrix. Thus, for matrix multiply operation, we present only one TextField to the user. This is shown in screen shot below.


The program calls readOneDimension method to create the above user interface.

In case of multiply operation, we call AllocateSecondMatrix method to set the dimensions and space for the second matrix.

	calc.AllocateSecondMatrix(calc.getMatrix1SecondDim(), ThirdDim);

After the matrix space is allocated, the application creates an instance of ReadMatrixForm and attaches it to the display.

	ReadMatrixForm frm = new ReadMatrixForm("Enter element values",
			calc, false);

The ReadMatrixForm class

Like earlier classes, the ReadMatrixForm too extends Form and implements CommandListener.

	public class ReadMatrixForm extends Form implements CommandListener

In the init() method of this class, we create the user interface for accepting the element values. This is illustrated in the screen shot below:


In the action command, we store the user input value into the appropriate element of the array. Depending on the value of the firstTime flag, either the first or the second matrix is populated. The user may use the Back button to overwrite the previously input elements.

After accepting all the elements of the matrix, the program presents a list of operations to the user by creating an instance of CreateList class.

	CreateList list=new CreateList(calc);

The CreateList class

The CreateList class does not extend any other class and implements the CommandListener interface.

	public class CreateList implements CommandListener

In the init() method, the program first checks the status of PerformOperation flag. This flag is set if the user has previously selected the operation (cascaded operations) to be performed on the input matrices. For the first input matrix, the flag is false. For the subsequent input matrices, the flag is always true.

	if (calc.getPerformOperation()) {

The init() method creates a List object and adds the desired commands to it.

	list = new List("select Operation",List.IMPLICIT);

The program then attaches the list to the display and sets the command listener.


The UI for the List is shown in the screen shot below:


In the PerformOperation method, the program creates an instance of Operations class and calls its appropriate method to perform the desired operation. The Operations class is discussed later.

	private void PerformOperation() {
		char operation = calc.getOperation();
		Operations op = new Operations(calc);
		switch (operation) {
			case 'A':
			case 'S':
			case 'M':

In the action command, the program first determines the user selection by calling getSelectedIndex method of the List class.

	String selection=list.getString(list.getSelectedIndex());

If the user selects Done operation, the program creates an instance of DoneForm and attaches it to the user display. The DoneForm class is discussed later.

			DoneForm doneForm = new DoneForm(calc);

In case of Transpose operation, the program creates an instance of TransposeForm and displays it to the user.

			TransposeForm transposeForm = new TransposeForm(calc);

In case of Multiply operation, the program creates an instance of DimInputForm and calls its readOneDimension method to accept the column dimension of the second matrix.

			DimInputForm dimInputForm = new DimInputForm(calc);

In case of Add/Subtract operations, the program allocates space for the second matrix and creates an instance of ReadMatrixForm for populating the second matrix. We will now look at the implementation of Operations class.

The Operations class

The Operations class defines methods that perform matrix arithmetic. The init() method obtains the dimensions and references to the two operand matrices from MatrixCalc class and allocates space for the resultant matrix. The add, subtract and multiply operations are defined by the appropriate methods that perform the desired arithmetic as described in the article earlier. The resultant matrix is copied to the first matrix stored in the MatrixCalc class.

We will now discuss TransposeForm class.

The TransposeForm class

Like earlier Form-derived classes, the TransposeForm class extends Form class and implements CommandListener interface.

	public class TransposeForm extends Form implements CommandListener

The init() method of the class first calls its ComputeTranspose method to compute the transpose of the first input matrix. The transpose is computed by using the logic discussed earlier. The call to ComputeTranspose method is followed by a call to DisplayTranspose method that displays the resultant matrix on the screen. Finally, the AssignResult method is called to copy the resultant matrix into the first matrix for cascading further operations. The screen shot of the TransposeForm is shown below:


We now discuss our last Form class, i.e. DoneForm.

The DoneForm class

Like earlier Form classes, the DoneForm too extends Form and implements CommandListener interface. The init() method calls the DisplayMatrix method that displays the contents of the first matrix on the screen. Remember that we had always stored the resultant matrix of matrix operations in the first matrix. In the action command, we take the user back to the opening screen by calling the startApp method of the Midlet. The screen shot of the DoneForm is shown below:



This article demonstrates the implementation of a matrix calculator on a J2ME platform. The calculator supports Add, Subtract, Multiply and Transpose operations on matrices. Such operations may be cascaded to solve an expression consisting of matrices. The application performs operations on integer elements. Developers can enhance the functionality of this calculator by providing operations on complex numbers, double numbers, etc. As the current application supports only integer data type, a multiplication operation on large element values may result in the overflow. The interested reader may provide further improvements for handling such overflow situations.


We will like to thank Ms. Priti Patil, Ms. Nalini Yadav, Ms. Purvi Vora, for their valuable contribution in testing the application and providing valuable suggestions in improving the application functionality.

More Stories By P.G. Sarang

Dr. Sarang in his long tenure of 20+ years has worked in various capacities in the IT industry. Dr. Sarang currently holds the position of Director (Architecture) with Kynetia, Spain and has been a Consultant to Sun Microsystems for last several years. He has previously worked as a Visiting Professor of Computer Engineering at University of Notre Dame, USA and is currently an adjunct faculty in the Univ. Dept. of Computer Science at University of Mumbai. Dr. Sarang has spoken in number of prestigious international conferences on Java/CORBA/XML/.NET and has authored several articles, research papers, courseware and books.

More Stories By Kanchan Waikar

Kanchan Waikar is a software professional working with an IT company. She is very much inclined toward mobile programming. Her hobbies include reading novels, painting, playing table tennis, and programming.

Comments (1)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
According to Forrester Research, every business will become either a digital predator or digital prey by 2020. To avoid demise, organizations must rapidly create new sources of value in their end-to-end customer experiences. True digital predators also must break down information and process silos and extend digital transformation initiatives to empower employees with the digital resources needed to win, serve, and retain customers.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, will provide an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life ...
Smart Cities are here to stay, but for their promise to be delivered, the data they produce must not be put in new siloes. In his session at @ThingsExpo, Mathias Herberts, Co-founder and CTO of Cityzen Data, discussed the best practices that will ensure a successful smart city journey.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
@CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...
Rafay enables developers to automate the distribution, operations, cross-region scaling and lifecycle management of containerized microservices across public and private clouds, and service provider networks. Rafay's platform is built around foundational elements that together deliver an optimal abstraction layer across disparate infrastructure, making it easy for developers to scale and operate applications across any number of locations or regions. Consumed as a service, Rafay's platform elimi...