Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Mehdi Daoudi

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
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
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.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...