Hello guys, continuing the tradition of this week, where I have mostly published articles about coding exercises for Java beginners, today also I am going to share an interesting coding problem, many of you have solved in your college or school days. Yes, it's about writing a Java program to transpose a matrix. In the last couple of tutorials, we have learned to how to add and subtract two matrices in Java (see here) and how to multiply two matrices in Java (see here). In this tutorial, I'll show you how to transpose a matrix in Java. The transpose of a matrix is a new matrix whose rows are the columns of the original. This means when you transpose a matrix the columns of the new matrix becomes the rows of the original matrix and vice-versa. In short, to transpose a matrix, just swap the rows and columns of the matrix. For example, if you have a matrix with 2 rows and 3 columns then transpose of that matrix will contain 3 rows and two columns.

# How to Add and Subtract Two Matrices in Java

This is the second program in the series of matrices related programming exercises in Java. In the last program, you have learned matrix multiplication and in this program, you will learn how to perform addition and subtraction of two matrices in Java. We'll create methods to calculate both sum and difference of two matrices in Java program. In Mathematics, a matrix is a rectangular array with two dimensions known as rows and columns. In Java, your can use a two-dimensional array to represent a matrix because it also has two dimensions rows and columns. Since a 2D array is nothing but an array of the array in Java, the length of the outer array is equal to the number of rows and length of sub-array is equal to the number of columns.

# How to calculate sum and difference of two complex numbers in Java

From the last couple of articles, I am writing about coding exercises for beginners e.g. yesterday you learned how to write a program from matrix multiplication in Java (see here) and a couple of days back, you have learned recursive binary search algorithm. To continue that tradition today I am going to show you how to write a program for calculating sum and difference of two complex numbers in Java. If you remember the complex number from you maths classes, it has two part real and imaginary and to add a complex number we add their real and imaginary part separately, similar to subtract complex number we minus their real and imaginary part separately. For example, if first complex number is A + iB and the second complex number is X + iY then the addition of these two complex number will be equal to (A +X ) + i(B + Y).

# How to Multiply Two Matrices in Java

I first learned about matrix in class 12th and I first wrote the program to multiply two matrices on my first semester of engineering, so, when I thought about this program, It brings a lot of memories from the past. It's actually a beginner exercise to develop coding logic, much like Fibonacci, prime, and palindrome check, but what make this program interesting is the use of the two-dimensional array to represent a matrix in Java. Since matrix has both rows and columns, two-dimensional array just naturally fits into the requirement. Another important thing to solve this problem is to remember the rule of matrix multiplication in mathematics. If you don't remember the rule, just forget about how to solve this problem, unless you have access to Google. So, first, we'll refresh the rules of multiplication and then we'll look into coding aspect.

# java.lang.OutOfMemoryError: unable to create new native thread - Cause and Solution

There are several types of OutOfMemoryError in Java e.g. OutOfMemoryError related to Java heap space and permgen space, and a new one coming in Java 8, Java.lang.OutOfMemoryError: MetaSpace. Each and every OutOfMemoryError has their own unique reason and corresponding unique solution. For example, java.langOutOfMemoryError: Java Heap Space comes when the application has exhausted all heap memory and tries to create an object which requires further memory allocation, that time JVM throws this error to tell the application that it's not possible to create any object. Similarly java.lang.OutOfMemoryError: PermGen Space comes when there is no more memory in permgen space and application tries to load more classes (as class metadata is stored in this area) or tries to create new String (because prior to Java 7 String pool has also existed on permgen space).

# 5 Difference between StringBuffer, StringBuilder and String in Java

Though all three classes StringBuffer, StringBuilder and String are used for representing text data in Java there are some significant differences between them. One of the most notable differences between StringBuilder, StringBuffer, and String in Java is that both StringBuffer and StrinBuilder are

**Mutable**class but String is Immutable in Java. What this means is, you can add, remove or replace characters from StringBuffer and StringBuilder object but any change on String object e.g. converting uppercase to lowercase or appending a new character using String concatenation will always result in a new String object. Another key difference between them is that both StringBuffer and String are**thread-safe**but StringBuilder is not thread-safe in Java. String achieves its thread-safety from Immutability but StringBuffer achieves it via synchronization, which is also the main difference between the StringBuffer and StringBuilder in Java.# JDBC - How to solve java.sql.BatchUpdateException: String or binary data would be truncated.

Recently I was working in Java application which uses Microsoft SQL Server at its backend. The architecture of Java application was old i.e. even though there was heavy database communication back and forth there was no ORM used e.g. no Hibernate, JPA, or Apache iBatis. The Java application was using old DAO design pattern, where the DB related classes which are responsible for loading and storing data from database was calling stored procedure to do their Job. These stored procedure takes data from Java application and insert into SQL Server tables. One day, one of my collegue called me to troubleshoot

**"java.sql.BatchUpdateException: String or binary data would be truncated"**, which it's application was throwing and he has no clue whatsoever that what is wrong with the data he is getting from other system and trying to store.# How to calculate average of all numbers of array in Java

In the last article, I teach you how to calculate the sum of all numbers in a given array and in this article, we'll go one more step. This time, you need to

**write a program to calculate the average of all numbers from a given array**, for example, you will be passed salaries of Java developers in different states in the USA and you need to calculate the average salary of Java developer in the USA. The example of average salaries of Java developer is more interesting because everybody wants to know how much Java developers make, isn't it? Anyway, coming back to the requirement of the program, The array will contain integers, which can be both positive and negative, so you must handle them. Your program should also be robust e.g. it should not break if you pass empty array or null. In these case either you can throw IllegalArgumentException as returning any other number will be ambiguous.# How to calculate sum of array elements in Java

In today's coding problem, we'll see how to write a program to calculate the sum of array elements in Java. You need to write a method which will accept an integer array and it should return total sum of all the elements. The array could contain both positive and negative numbers but only decimal numbers are allowed. The array can also be null or empty so make sure your solution handle those as well. In the case of a null or empty array, your program can throw IllegalArgumentException. The empty array means, an array whose length is zero or there is no element inside it. Well, that's enough for the requirement of this simple coding problem. The solution is really simple, just loop through the array and keep adding elements into sum until you process all the elements.

# 10 Reasons of java.lang.NumberFormatException in Java - Solution

The

**NumberFormatException**is one of the most common errors in Java application along with NullPointerException. This error comes when you try to convert a String into numeric data types e.g. int, float, double, long, short, char or byte. The data type conversion methods like Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), and Long.parseLong() throws NumberFormatException to signal that input String is not valid numeric value. Even though the root cause is always something which cannot be converted into a number, there are many reasons and input due to which NumberFormatException occurs in Java application. Most of the time I have faced this error while converting a String to int or Integer in Java, but there are other scenarios as well when this error occurs. In this article, I am sharing 10 of the most common reasons of java.lang.NumberFormatException in Java programs.# How to calculate area of triangle in Java - Program

Writing a Java program to calculate the area of a triangle is one of the basic programming exercises to develop coding sense on beginner programmers. Like many mathematical conceptual programs e.g. square root, factorial, or prime number this also serves a good exercise for beginners. Now, if you remember in maths you might have seen two main ways to calculate the area of a triangle, using vertices and using base and height. In this program, I have created two methods to calculate the area of a triangle using both ways. In the first method area(Point a, Point b, Point c) we expect coordinates of three vertices of triangle and then we calculate area of triangle using the formula (Ax(By -Cy) + Bx(Cy -Ay) + Cx(Ay - By))/2, while in second method, area(int base, int height) we expect value of base and height and then we calculate are of triangle using formula (base * height) / 2.

# Top 5 Design Patterns Books for Java Developers

Design patterns is an important topic for object-oriented programmers e.g. Java and C++ developers. It becomes even more important as your experience grows because everybody starts expecting a lot more from you in terms of writing quality code. I often receive emails from intermediate and senior Java developers about progressing to next level e.g. how to become Tech Lead, Team Lead or a software architect, knowledge of design pattern plays an important role in taking more technical responsibility. While the GoF book is the bible for object-oriented design patterns, in my opinion, it is a bit too dry and academic. Many of you might have already read it but I doubt you have enjoyed it a lot. The first real book I read on design pattern was the head first book. It's full of interesting stories, cartoons, UML diagrams, fireside chats to analyze the pros and cons of each design pattern, fill in the blanks, exercise, and most importantly some non-trivial code examples. Another good thing is that it focuses on a good set of core patterns e.g. Decorator, Observer, Factory, Command, Strategy, and Facade patterns.

# 3 ways to convert String to JSON object in Java?

It's very common nowadays to receive JSON String from a Java web service instead of XML, but unfortunately, JDK doesn't yet support conversion between JSON String to JSON object. Keeping JSON as String always is not a good option because you cannot operate on it easily, you need to convert it into JSON object before you do anything else e.g. retrieve any field or set different values. Fortunately, there are many open source library which allows you to create JSON object from JSON formatted String e.g. Gson from Google, Jackson, and json-simple. In this tutorial, you will learn how to use these 3 main libraries to do this conversion with step by step examples.

# 3 Ways to Reverse an Array in Java - Coding Interview Question

One of the common coding questions is,

**how do you reverse an array in Java?**Well, there are multiple ways to solve this problem. You can reverse array by writing your own function, which loops through the array and swaps elements until the array is sorted. That's actually should you be your first approach on interviews. Later you can impress the interviewer by a couple of other tricks, which is specific to Java development world. For example, you can reverse an array by converting array to ArrayList and then use this code to reverse the ArrayList. You can also use Apache Commons ArrayUtils.reverse() method to reverse any array in Java. This method is overloaded to reverse byte, short, long, int, float, double and String array. You can use any of the method depending upon your array type.
Subscribe to:
Posts (Atom)