Java Math Operators and Math Class

Java Math Operators and Math Class Java contains a set of built-in math operators for performing simple math operations on Java var...

Java Math Operators and Math Class


Java contains a set of built-in math operators for performing simple math operations on Java variables. The Java math operators are reasonably simple. Therefore Java also contains the Java Math class which contains methods for performing more advanced math calculations in Java. This Java math tutorial will take a closer look at both Java's math operators as well as the Java Math class.

Java Math Operators

Let me first explain you the four basic math operators in Java. The Java math operators are:
Math OperatorDescription
+Performs addition
-Performs subtraction
*Performs multiplication
/Performs division
Each of these math operators will be explained in more detail in the following sections.

Addition

The + operator performs an addition of two values. This can be an addition of two constants, a constant and a variable, or a variable and a variable. Here are a few Java addition examples:
int sum1 = 10 + 20;      // adding two constant values
int sum2 = sum1 + 33;    // adding a variable and a constant
int sum3 = sum2 + sum2;  // adding two variables
The + operator will replace the two values with the sum of the two values at runtime. So at the place where the expression sum1 + 33 is written, at runtime this will be replaced with the sum of the value of sum1 and the constant value 33.
You can of course create longer chains of additions and thus add more than two numbers. Here is a en example of adding 3 or more values together:
int sum1 = 10 + 20 + 30;
int sum3 = sum2 + 99 + 123 + 1191;
A commonly used math operation on variables is to set the variable equal to its own value plus another value. Here is how that looks:
int result = 10;
result = result + 20;
The second line of this example sets the sum variable equals to its own value (before being assigned the new value) + 20. Which means 10 + 20.
Since adding a value to a variable is a very common operation, Java contains a built-in operator for that specific purpose. It is the += operator. Here is the example above rewritten to use the += operator:
int result = 10;
result += 20;
The second line in this example adds 20 to the variable result. This equivalent to the code result = result + 20;

Subtraction

The - operator performs subtraction of one value from another. This can be a subtraction of a constant value from another constant value, a constant value from a variable, or a variable from a variable. Here are a few Java subtraction examples:
int diff1 = 200 - 10;
int diff2 = diff1 - 5;
int diff3 = diff1 - diff2;
The - operator will replace the two values with the difference between the two values, just like with the +operator.
You can create longer chains of subtractions and thus subtract more values from each other. Here is an example of subtracting two values from another in a single Java statement:
int diff = 200 - 10 - 20;
This works for variables too.
Remember, minus minus equals plus, just like in normal math. Here is an example of that:
int diff = 200 - (-10);
After executing this math expression the diff variable will contain the value 210 because - (-10) is equal to+10 according to standard math rules.
Just like with addition, Java contains an operator specifically targeted at subtracting a value from a variable, and assigning the result to the variable. Here is first how that would look in Java without this operator:
int result = 200;
result = result - 10;
Here is how the same math operation looks with the -= operator:
int result = 200;
result -= 10;

Multiplication

The * operator performs multiplication of two values. The values can be either two constant values, a variable and a constant value, or two variables. Here are a few Java multiplication examples:
int prod1 = 10 * 20;
int prod2 = prod1 * 5;
int prod3 = prod1 * prod2;
The * operator will replace the multiplication math expression with the product of the two values at runtime.
You can create longer chains of multiplication using the * operator. Here is an example of multiplying 3 values with each other:
int prod = 10 * 20 * 30;
Multiplying a variable with a value and assigning the value back to the variable is a common math operation in Java applications. Therefore Java contains an explicit operator for this operation. The *= operator. Here is first how the calculation would look without the *= operator:
int result = 10;
result = result * 20;
The second line of this example multiplies the value of the result variable (before being assigned the result of this calculation) with 20 and assigns the value back to the result variable.
Here is how the same math operation looks with the += operator:
int result = 10;
result *= 20;

Division

The / operator performs division of one value by another. This can be dividing one constant with another, dividing a variable with a constant, or dividing one variable by another variable. Here are a few Java division examples:
int division1 = 100 / 10;
int division2 = division1 / 2;
int division3 = division1 / division2;
You can chain multiple values for division, but because of the Java math operator precedence (explained later) you have to pay attention to how you chain the values. Look at this division example:
int division = 100 / 10 / 2;
After executing this math expression the division variable will contain the value 5. That is the result because the math expression was calculated by first dividing 100 by 10 (= 10) and then 10 by 2 (=5). But, what if you had wanted to first divide the 10 by 2 (=5), and then divide the 100 by 5 (=20) ? You would have had to use parentheses to achieve that, like this:
int division = 100 / (10 / 2)
You will learn more about operator precedence and parentheses later in this Java math tutorial.
Java also contains a shortcut operator for dividing the value of a variable by another value, and assigning that value back to the variable. The /= operator. Here is first how that math operation looks in Java without the /=operator:
int result = 100;
result = result / 5;
The second line of this example divides the value of the result variable (the value it had before being assigned the result of this calculation) by 5, and assigns the result back to the result variable.
Here is how the same math operation looks with the /= operator:
int result = 100;
result /= 5;

Remainder / Modulo

The remainder math operation performs an integer division of one value by another and returns the remained of that division. The remainder operation is also called the modulo operation. The operator for the remainder / modulo operation is the % (percentage) character. Here is a module operation example:
int value    = 100;
int remainder = value % 9;
100 divided by 9 is 11 with a remainder of 1 (11 times 9 is 99). Thus, the remainder variable is assigned the value 1.
Java also contains a shortcut operator for dividing a variable by another value and assigning the remainder of that division to the variable. The %= operator. Here is an example:
int result = 100;
result %= 9;
The second line of this example will assign the value 1 to the result variable. 1 is the result of 100 % 9.

Java Math Operator Precedence

Once you start combining the Java math operators in math expressions it becomes important to control what calculations are to be executed when, in order to get the desired result. The Java math operators have a natural operator precedence which is similar to the precedence of standard math operators.
The math operators * and / for multiplication and division takes precedence over the + and - operators. That means, that multiplications and divisions are evaluated before addition and subtraction in math expressions. In case there are multiple * and / operators they will be calculated from left to right. Look at this Java math expression:
int result = 100 * 100 / 5 + 200 * 3 / 2;
First the multiplications and divisions are executed. There are two groups of three multiplications and divisions. Each group is executed from left to right:
100 * 100 = 10000;
10000 / 5 = 2000;
200 * 3 = 600;
600 / 2 = 300;
After calculating the multiplications and divisions the math expression looks like this:
int result = 2000 + 600;
Now the additions and subtractions are executed. The value assigned to the result variable is thus 2000 + 600 = 2600 .
You can control the operator precedence and sequence of calculations in math expressions in Java using parentheses. Math expressions inside parentheses have higher precedence than any other operator. Therefore expressions inside parentheses are calculated first. Inside parentheses the normal operator precedence applies. Here is the math expression from earlier, but with parentheses inserted which change the calculation:
int result = 100 * 100 / (5 + 200) * 3 / 2;
The value 100 is still multiplied by 100 (= 10,000), but now it is divided by 5 + 200 (=205) instead of 5. After this division the result is multiplied by 3 and then divided by 2. The result of executing this math expression in Java is 72 (rounding of calculations affect the result).

Java Integer Math

Math operations performed on Java integer types (byteshortint and long) behaves slightly different from how normal math operations work. Since Java integer types cannot contain fractions, each calculation involving one or more integer types have all fractions in the result cut off. Look at this math expression:
int result = 100 / 8;
The result of this division would be 12.5 , but since the two numbers are integers, the .5 fraction is cut off. The result is therefore just 12.
The rounding also occurs in subresults of larger calculations, as you will learn in the next section about Java floating point math.

Java Floating Point Math

Java contains the two floating point data types float and double. These floating point types are capable of containing fractions in the numbers. If you need fractions in your math expressions you should use one of these data types. Here is a Java floating point math expression example:
double result = 100 / 8;
Even though the result variable is now a floating point type (double), the final result is still just 12 instead of 12.5 . The reason for that is that the two values in the math expression (100 and 8) are both integers. Thus, the result of dividing one by the other is first converted to an integer (12) before being assigned to the resultvariable.
To avoid rounding of calculations in math expressions in Java you must make sure that all data types involved in the math expression are floating point types. For instance, you could first assign the values to floating point variables like this:
double no1 = 100;
double no2 = 8;

double result = no1 / no2;
Now the result variable would end up with the value 12.5.
Java has a way to force all numbers in a calculation to be floating point variables. You suffix the numbers with either a capital F or D. Here is an example:
double result = 100D / 8D;
Notice the uppercase Ds after each number. This uppercase D tells Java that these numbers are to be interpreted as floating point numbers, and thus the division is supposed to be a floating point division which keeps fractions instead of cutting them off.
You can actually also force a number to be a long by suffixing the number with an uppercase L, but long is still an integer type, so it will still not keep the fractions in calculations.

Floating Point Precision

Java floating point data types are not 100% precise. You can experience situations where numbers with many fractions on do not add up to the number you expected. If a floating point calculation results in a number with more fractions than a float or a double can handle, fractions may be cut off. Granted, the given precision may still more than enough for many types of calculations, but keep in mind that fractions may actually get cut off.
Look at this Java floating point math code:
double resultDbl3 = 0D;
System.out.println("resultDbl3 = " + resultDbl3);

for(int i=0; i<100; i++){
    resultDbl3 += 0.01D;
}
System.out.println("resultDbl3 = " + resultDbl3);
The output printed when executing this code with Java 8 is:
resultDbl3 = 0.0
resultDbl3 = 1.0000000000000007
The first System.out.println() statement correctly prints the value 0.0 , which is the start value of the theresultDbl3 variable.
The second System.out.println() statement however prints a somewhat strange result. Adding the value 0.01 to 0 a total of 100 times should result in the value 1.0, right? But somehow the final result is1.0000000000000007 . As you can see, somehow something goes wrong way down in the fractions.
Usually the Java floating point imprecision is insignificant, but it is still important to be aware of it.

The Java Math Class

The Java Math class provides more advanced mathematical calculations than what the basic Java math operators provide. The Math class contains methods for finding the maximum or minimum of two values, rounding values, logarithmic functions, square root, and trigonometric functions (sin, cos, tan etc.).
The Math is located in the java.lang package, and not in the java.math package. Thus, the fully qualified class name of the Math class is java.lang.Math .
Since many of the functions of the Math class are independent from each other, each method will be explained in its own section below.

Basic Math Functions

The java.lang.Math contains a set of basic math functions for obtaining the absolute value, highest and lowest of two values, rounding of values, random values etc. These basic math functions of the Java Math class will be covered in the following sections.

Math.abs()

The Math.abs() function returns the absolute value of the parameter passed to it. The absolute value is the positive value of the parameter. If the parameter value is negative, the negative sign is removed and the positive value corresponding to the negative value without sign is returned. Here are two Math.abs() method examples:
int abs1 = Math.abs(10);  // abs1 = 10

int abs2 = Math.abs(-20); // abs2 = 20
The absolute value of 10 is 10. The absolute value of -20 is 20.
The Math.abs() method is overloaded in 4 versions:
Math.abs(int)
Math.abs(long)
Math.abs(float)
Math.abs(double)
Which of these methods are called depends on the type of the parameter passed to the Math.abs() method.

Math.ceil()

The Math.ceil() function rounds a floating point value up to the nearest integer value. The rounded value is returned as a double. Here is a Math.ceil() Java example:
double ceil = Math.ceil(7.343);  // ceil = 8.0
After executing this Java code the ceil variable will contain the value 8.0 .

Math.floor()

The Math.floor() function rounds a floating point value down to the nearest integer value. The rounded value is returned as a double. Here is a Math.floor() Java example:
double floor = Math.floor(7.343);  // floor = 7.0
After executing this Java code the ceil variable will contain the value 8.0 .

Math.floorDiv()

The Math.floorDiv() method divides one integer (int or long) by another, and rounds the result down to the nearest integer value. If the result is positive, the effect is the same as using the Java / division operator described earlier in this text.
If the result is negative, however, the result is not the same. With the / division operator the fractions are simply truncated. For positive numbers this corresponds to rounding down. For negative numbers though, truncating the fractions correspond to rounding up. The floorDiv() method rounds down to the nearest negative integer, instead of the rounding up that would occur with fraction truncation.
Here is a Math.floorDiv() Java example:
double result3 = Math.floorDiv(-100,9);
System.out.println("result3: " + result3);

double result4 = -100 / 9;
System.out.println("result4: " + result4);
The output printed from this Java code is:
result3: -12.0
result4: -11.0
This shows the difference between the / division operator and Math.floorDiv() .

Math.min()

The Math.min() method returns the smallest of two values passed to it as parameter. Here is a Math.min()Java example:
int min = Math.min(10, 20);
After executing this code the min variable will contain the value 10.

Math.max()

The Math.max() method returns the largest of two values passed to it as parameter. Here is a Math.max()Java example:
int max = Math.max(10, 20);
After executing this code the max variable will contain the value 20.

Math.round()

The Math.round() method rounds a float or double to the nearest integer using normal math round rules (either up or down). Here is a Java Math.round() example:
double roundedDown = Math.round(23.445);
double roundedUp   = Math.round(23.545);
After executing these two Java statements the roundedDown variable will contain the value 23.0 , and theroundedUp variable will contain the value 24.0.

Math.random()

The Math.random() method returns a random floating point number between 0 and 1. Of course the number is not fully random, but the result of some calculation which is supposed to make it as unpredictable as possible. Here is a Java Math.random() example:

To get a random value between 0 and e.g. 100, multiply the value returned by Math.random() with the maximum number (e.g. 100). Here is an example of how that might look:
double random = Math.random() * 100D;
If you need an integer value, use the round()floor() or ceil() method.

Exponential and Logarithmic Math Functions

The Java Math class also contains a set of functions intended for exponential and logarithmic calculations. I will cover some of these math functions in the following sections.

Math.exp()

The Math.exp() function returns e (Euler's number) raised to the power of the value provided as parameter. Here is a Java Math.exp() example:
double exp1 = Math.exp(1);
System.out.println("exp1 = " + exp1);

double exp2 = Math.exp(2);
System.out.println("exp2 = " + exp2);
When this Java math code is executed it will print this output:
exp1 = 2.718281828459045
exp2 = 7.38905609893065

Math.log()

The Math.log() method provides the logarithm of the given parameter. The base for the logarithm is i (Euler's number). Thus, Math.log() provides the reverse function of Math.exp(). Here is a Java Math.log()example:
double log1  = Math.log(1);
System.out.println("log1 = " + log1);

double log10 = Math.log(10);
System.out.println("log10 = " + log10);
The output from this Math.log() example is:
log1 = 0.0
log10 = 2.302585092994046

Math.log10()

The Math.log10 method works like the Math.log() method except is uses 10 as is base for calculating the logarithm instead of e (Euler's Number). Here is a Math.log10() Java example:
double log10_1   = Math.log10(1);
System.out.println("log10_1 = " + log10_1);

double log10_100 = Math.log10(100);
System.out.println("log10_100 = " + log10_100);
The output printed from this Java Math.log10() example would be:
log10_1 = 0.0
log10_100 = 2.0

Math.pow()

The Math.pow() function takes two parameters. The method returns the value of the first parameter raised to the power of the second parameter. Here is a Math.pow() Java example:
double pow2 = Math.pow(2,2);
System.out.println("pow2 = " + pow2);

double pow8 = Math.pow(2,8);
System.out.println("pow8 = " + pow8);
The output from this Math.pow() example would be:
pow2 = 4.0
pow8 = 256.0
In other words, the Math.pow() example calculate the values of 22 and 28 which are 4 and 256.

Math.sqrt()

The Math.sqrt() method calculates the square root of the parameter given to it. Here are a few JavaMath.sqrt() example:
double sqrt4 = Math.sqrt(4);
System.out.println("sqrt4 = " + sqrt4);

double sqrt9 = Math.sqrt(9);
System.out.println("sqrt9 = " + sqrt9);
The output printed from these Java Math.sqrt() examples would be:
sqrt4 = 2.0
sqrt9 = 3.0

Trigonometric Math Functions

The Java Math class contains a set of trigonometric functions. These functions can calculate values used in trigonometry, like sine, cosine, tangens etc. I will cover the most used trigonometry functions in the following sections. If you are looking for a trigonometric function and you cannot find it here, check the JavaDoc for the Java Math class. The Math class just might have the function you are looking for, even if I have not described it here.

Math.PI

The Math.PI constant is a double with a value that is very close to the value of PI - the mathematical definition of PI. You will often need the Math.PI field when making trigonometric calculations.

Math.sin()

The Math.sin() method calculates the sine value of some angle value in radians. Here is a JavaMath.sin() example:
double sin = Math.sin(Math.PI);
System.out.println("sin = " + sin);

Math.cos()

The Math.cos() method calculates the cosine value of some angle value in radians. Here is a JavaMath.cos() example:
double cos = Math.cos(Math.PI);
System.out.println("cos = " + cos);

Math.tan()

The Math.tan() method calculates the tangens value of some angle value in radians. Here is a JavaMath.tan() example:
double tan = Math.tan(Math.PI);
System.out.println("tan = " + tan);

Math.asin()

The Math.asin() method calculates the arc sine value of a value between 1 and -1. Here is a JavaMath.asin() example:
double asin = Math.asin(1.0);
System.out.println("asin = " + asin);

Math.acos()

The Math.acos() method calculates the arc cosine value of a value between 1 and -1. Here is a JavaMath.acos() example:
double acos = Math.acos(1.0);
System.out.println("acos = " + acos);

Math.atan()

The Math.atan() method calculates the arc tangens value of a value between 1 and -1. Here is a JavaMath.atan() example:
double atan = Math.atan(1.0);
System.out.println("atan = " + atan);

Math.atan2()

I am not exactly sure what Math.atan2() method does mathematically. Here is what the JavaDoc says:
"Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta)".
If you need this method, please read the JavaDoc. But now you know at least that it exists.

Math.sinh()

The Math.sinh() method calculates the hyperbolic sine value of a value between 1 and -1. Here is a JavaMath.sinh() example:
double sinh = Math.sinh(1.0);
System.out.println("sinh = " + sinh);

Math.cosh()

The Math.cosh() method calculates the hyperbolic cosine value of a value between 1 and -1. Here is a JavaMath.cosh() example:
double cosh = Math.cosh(1.0);
System.out.println("cosh = " + cosh);

Math.tanh()

The Math.tanh() method calculates the hyperbolic tangens value of a value between 1 and -1. Here is a JavaMath.tanh() example:
double tanh = Math.tanh(1.0);
System.out.println("tanh = " + tanhprintln("tanh = " + tanh);

Math.toDegrees()

The Math.toDegrees() method converts an angle in radians to degrees. Here is a JavaMath.toDegrees() example:
double degrees = Math.toDegrees(Math.PI);
System.out.println("degrees = " + degrees);

Math.toRadians()

The Math.toRadians() method converts an angle in degrees to radians. Here is a JavaMath.toRadians() example:
double radians = Math.toRadians(180);
System.out.println("radians = " + radians);


Java Arrays

  Java Arrays An  array  is a collection of variables of the same type. For instance, an array of  int  is a collection of variables o...

  Java Arrays


An array is a collection of variables of the same type. For instance, an array of int is a collection of variables of the type int. The variables in the array are ordered and each have an index. You will see how to index into an array later in this text. Here is an illustration of Java arrays:
Java arrays are collections of variables of the same type, ordered with an index.

Declaring an Array Variable in Java

A Java array variable is declared just like you would declare a variable of the desired type, except you add []after the type. Here is a simple Java array declaration example:
int[] intArray;
You can use a Java array as a field, static field, a local variable, or parameter, just like any other variable. An array is simply a variation of the data type. Instead of being a single variable of that type, it is a collection of variables of that type.
Here are a few more Java array declaration examples:
String[]  stringArray;

MyClass[] myClassArray;
The first line declares an array of String references. The second line declares an array of references to objects of the class MyClass, which symbolizes a class you have created yourself.
You actually have a choice about where to place the square brackets [] when you declare an array in Java. The first location you have already seen. That is behind the name of the data type (e.g. String[]). The second location is after the variable name. The following Java array declarations are actually all valid:
int[] intArray;
int   intArray[];

String[] stringArray;
String   stringArray[];

MyClass[] myClassArray;
MyClass   myClassArray[];
Personally I prefer to locate the square brackets [] after the data type (e.g. String[]) and not after the variable name. After all, an array is a special kind of data type, so I feel it is easier to read the code when the square brackets are placed right after the data type in the array declaration.

Instantiating an Array in Java

When you declare a Java array variable you only declare the variable (reference) to the array itself. The declaration does not actually create an array. You create an array like this:
int[] intArray;

intArray = new int[10];
This example creates an array of type int with space for 10 int variables inside.
Once an array has been created its size cannot be changed. In some languages arrays can change their size after creation, but in Java an array cannot change its size once it is created. If you need an array-like data structure that can change its size, you should use a List.
The previous Java array example created an array of int which is a primitive data type. You can also create an array of object references. For instance:
String[] stringArray = new String[10];
Java allows you to create an array of references to any type of object (to instances of any class).

Java Array Literals

The Java programming language contains a shortcut for instantiating arrays of primitive types and strings. If you already know what values to insert into the array, you can use an array literal. Here is how how an array literal looks in Java code:
int[]   ints2 = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
Notice how the values to be inserted into the array are listed inside the { ... } block. The length of this list also determines the length of the created array.
Actually, you don't have to write the new int[] part in the latest versions of Java. You can just write:
int[]   ints2 = { 1,2,3,4,5,6,7,8,9,10 };
It is the part inside the curly brackets that is called an array literal.
This style works for arrays of all primitive types, as well as arrays of strings. Here is a string array example:
 String[] strings = {"one", "two", "three"};

Accessing Java Array Elements

Each variable in an Java array is also called an "element". Thus, the example shown earlier created an array with space for 10 elements, and each element is a variable of type int.
Each element in the array has an index (a number). You can access each element in the array via its index. Here is an example:
intArray[0] = 0;

int firstInt = intArray[0];
This example first sets the value of the element (int) with index 0, and second it reads the value of the element with index 0 into an int variable.
You can use the elements in a Java array just like if they were ordinary variables. You can read their value, assign values to them, use the elements in calculations and pass specific elements as parameters to method calls.
The indexes of elements in a Java array always start with 0 and continue to the number 1 below the size of the array. Thus, in the example above with an array with 10 elements the indexes go from 0 to 9.

Array Length

You can access the length of an array via its length field. Here is an example:
int[] intArray = new int[10];

int arrayLength = intArray.length;
In this example the variable named arrayLength will contain the value 10 after the second line of code has been executed.

Iterating Arrays

You can loop through all the elements of an array using the Java for loop. Here is an example of iterating an array with a for loop in Java:
String[] stringArray = new String[10];

for(int i=0; i < stringArray.length; i++) {
    stringArray[i] = "String no " + i;
}

for(int i=0; i < stringArray.length; i++) {
    System.out.println( stringArray[i] );
}
This example first creates an array of String references. When you first create an array of object references, each of the cells in the array points to null - no object.
The first of the two for loops iterate through the String array, creates a String and makes the cell reference that String.
The second of the two for loops iterate through the String array and prints out all of the strings that the cells reference.
If this had been an array of int (primitive values), it could have looked like this:
int[] intArray = new int[10];

for(int i=0; i < intArray.length; i++) {
    intArray[i] = i;
}

for(int i=0; i < intArray.length; i++) {
    System.out.println( intArray[i] );
}
The variable i is initialized to 0 and runs up until the length of the array minus 1. In this case, i takes the values 0 through 9, each time repeating the code inside the for loop one time, and for each iteration i has a different value.
You can also iterate an array using the "for-each" loop in Java. Here is how that looks:
int[] intArray = new int[10];

for(int theInt : intArray) {
    System.out.println(theInt);
}
The for-each loop gives you access to each element in the array, one at a time, but gives you no information about the index of each element. Additionally, you only have access to the value. You cannot change the value of the element at that position. If you need that, use a normal for-loop as shown earlier.
For for-each loop also works with arrays of objects. Here is an example showing you how to iterate an array ofString objects:
String[] stringArray = {"one", "two", "three"};

for(String theString : stringArray) {
    System.out.println(theString);
}

Multidimensional Java Arrays

The examples shown above all created arrays with a single dimension, meaning elements with indexes going from 0 and up. It is, however, possible to create arrays where each element has two or more indexes which identify (locate) it in the array.
You create a multidimensional array in Java by appending one set of square brackets ([]) per dimension you want to add. Here is an example that creates a two-dimensional array:
int[][] intArray = new int[10][20];
This example creates a two-dimensional array of int elements. The array contains 10 elements in the first dimension, and 20 elements in the second dimension. In other words, this examples creates an array of arrays of int elements. The array of arrays has space for 10 int arrays, and each int array has space for 20 intelements.
You access the elements in a multidimensional array with one index per dimension. In the example above you would have to use two indexes. Here is an example:
int[][] intArray = new int[10][20];

intArray[0][2] = 129;

int oneInt = intArray[0][2];
The variable named oneInt will contain the value 129 after the last line of Java code has executed.

Iterating Multidimensional Arrays

When you iterate a multidimensional array in Java you need to iterate each dimension of the array separately. Here is is how iterating a multidimensional looks in Java:
int[][] intArray = new int[10][20];

for(int i=0; i < intArrays.length; i++){
    for(int j=0; j < intArrays[i].length; j++){
        System.out.println("i: " + i + ", j: " + j);
    }
}

Inserting Elements Into an Array

Sometimes you need to insert elements into a Java array somewhere. Here is how you insert a new value into an array in Java:
int[] ints   = new int[20];

int insertIndex = 10;
int newValue    = 123;

//move elements below insertion point.
for(int i=ints.length-1; i > insertIndex; i--){
    ints[i] = ints[i-1];
}

//insert new value
ints[insertIndex] = newValue;

System.out.println(Arrays.toString(ints));
The example first creates an array. Then it defines an insert index and a new value to insert. Then all elements from the insertion index and to the end of the array are shifted one index down in the array. Note that this will shift the last value in the array out of the array (it will simply be deleted).
The above array insertion code could be embedded in a Java method. Here is how that could look:
public void insertIntoArray(
        int[] array, int insertIndex, int newValue){

    //move elements below insertion point.
    for(int i=array.length-1; i > insertIndex; i--){
        array[i] = array[i-1];
    }

    //insert new value
    array[insertIndex] = newValue;
}
This method takes an int[] array as parameter as well as the index to insert the new value, and the new value. You can insert elements into an array by calling this method like this:
int[] ints   = new int[20];

insertIntoArray(ints, 0, 10);
insertIntoArray(ints, 1, 23);
insertIntoArray(ints, 9, 67);
Of course, if the insertIntoArray() method is located in a different class than the above code, you would need an object of that class in order to be able to call the method. Or, if the insertIntoArray() method wasstatic, you would need to put the class name and a dot in front of the method name.

Removing Elements From an Array

Sometimes you have want to remove an element from a Java array. Here is the code for removing an element from an array in Java:
int[] ints   = new int[20];

ints[10] = 123;

int removeIndex = 10;

for(int i = removeIndex; i < ints.length -1; i++){
    ints[i] = ints[i + 1];
}
This example first creates an int array. Then it sets the value of the element with index 10 to 123. Then the example removes the element with index 10. It removes the element by shifting all elements below index 10 one position up in the array. After the removal, the last element in the array will exist twice. Both in the last and second last element.
The above code could be embedded in a Java method. Here is how such an array removal Java method could look:
public void removeFromArray(
    int[] array, int removeIndex){

    for(int i = removeIndex; i < array.length -1; i++){
        array[i] = array[i + 1];
    }
}
This removeFromArray() method takes two parameters: The array to remove the element from, and the index of the element to remove.
Of course, if the removeFromArray() method is located in a different class than the above code, you would need an object of that class in order to be able to call the method. Or, if the removeFromArray() method wasstatic, you would need to put the class name and a dot in front of the method name.

Finding Min and Max Value in Arrays

Sometimes you may need to find the minimum or maximum value in a Java array. Java does not have any built-in functions for finding minimum and maximum value, so I will show you how to code that yourself.
Here is first how you find the minimum value in an array:
int[] ints = {0,2,4,6,8,10};

int minVal = Integer.MAX_VALUE;

for(int i=0; i < ints.length; i++){
    if(ints[i] < minVal){
        minVal = ints[i];
    }
}

System.out.println("minVal = " + minVal);
The example first sets the minVal to Integer.MAX_VALUE which is the highest possible value an int can take. This is done to make sure that the initial value is not by accident smaller than the smallest value in the array.
Second, the example iterates through the array and compares each value to minValue. If the element in the array is smaller than minVal then minVal is set to the value of the element.
Finally the minimum value found in the array is printed out. In the example above the minimum value is 0.
Here is how you find the maximum value in an array. It is pretty similar to finding the minimum value.
int[] ints = {0,2,4,6,8,10};

int maxVal = Integer.MIN_VALUE;
for(int i=0; i < ints.length; i++){
    if(ints[i] > maxVal){
        maxVal = ints[i];
    }
}
System.out.println("maxVal = " + maxVal);
This example will print out the value 10.
The major differences to finding the minimum value is the initialization of maxVal and the comparison ofmaxVal to the elements in the array.

The Arrays Class

Java contains a special utility class that makes it easier for you to perform many often used array operations like copying and sorting arrays, filling in data, searching in arrays etc. The utility class is called Arrays and is located in the standard Java package java.util. Thus, the fully qualified name of the class is:
java.util.Arrays
I will cover a few of the methods found in this class in the following sections. Remember, in order to usejava.util.Arrays in your Java classes you must import it. Here is how importing java.util.Arrayscould look in a Java class of your own:
package myjavaapp;

import java.util.Arrays;

public class MyClass{

    public static void main(String[] args) {

    }
}
Notice the import java.util.Arrays; statement in bold. It is this statement that imports the classjava.util.Arrays into your Java class.

Copying Arrays

You can copy an array into another array in Java in several ways.

Copying an Array by Iterating the Array

The first way to copy an array in Java is to iterate through the array and copy each value of the source array into the destination array. Here is how copying an array looks using that method:
int[] source = new int[10];
int[] dest   = new int[10];

for(int i=0; i < source.length; i++) {
    source[i] = i;
}

for(int i=0; i < source.length; i++) {
    dest[i] = source[i];
}
First two int arrays are created. Second, the source array is initialized with values from 0 to 9 (0 to the length of the array minus 1). Third, each element in the source array is copied into the destination array.

Copying an Array Using Arrays.copyOf()

The second method to copy a Java array is to use the Arrays.copyOf() method. Here is how copying an array using Arrays.copyOf() looks:
int[] source = new int[10];

for(int i=0; i < source.length; i++) {
    source[i] = i;
}

int[] dest = Arrays.copyOf(source, source.length);
The Arrays.copyOf() method takes 2 parameters. The first parameter is the array to copy. The second parameter is the length of the new array. This parameter can be used to specify how many elements from the source array to copy.

Copying an Array Using Arrays.copyOfRange()

The third method to copy a Java array is to use the Arrays.copyOfRange() method. TheArrays.copyOfRange() method copies a range of an array, not necessarily the full array. Here is how copying a full array using Arrays.copyOfRange() in Java looks:
int[] source = new int[10];

for(int i=0; i < source.length; i++) {
    source[i] = i;
}

int[] dest = Arrays.copyOfRange(source, 0, source.length);
The Arrays.copyOfRange() method takes 3 parameters. The first parameter is the array to copy. The second parameter is the first index in the source array to include in the copy. The third parameter is the last index in the source array to include in the copy (excluded - so passing 10 will copy until and including index 9).

Converting Arrays to Strings With Arrays.toString()

You can convert an Java array of primitive types to a String using the Arrays.toString() method. Here is an example of how to convert an array of int to a String using Arrays.toString():
int[]   ints = new int[10];

for(int i=0; i < ints.length; i++){
    ints[i] = 10 - i;
}

System.out.println(java.util.Arrays.toString(ints));
The first line creates an array of int with 10 elements. The for loop initializes the array with the values from 10 to 1. The last line prints out the value returned from Arrays.toString(). The returned String (which is printed) looks like this:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Sorting Arrays

You can sort the elements of an array using the Arrays.sort() method. Sorting the elements of an array rearranges the order of the elements according to their sort order. Here is an Arrays.sort() example:
int[]   ints = new int[10];

for(int i=0; i < ints.length; i++){
    ints[i] = 10 - i;
}

System.out.println(java.util.Arrays.toString(ints));

java.util.Arrays.sort(ints);

System.out.println(java.util.Arrays.toString(ints));
The first line declares and instantiates an array of int with a length of 10;
The for loop iterates over the array and inserts values into each element. The values inserted will go from 10 to 1 in descending order.
After the for loop the array is converted to a String using Arrays.toString() and printed out to the console (command line). At this point the output written to the console (the String version of the array) looks like this:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
The array is then sorted using Arrays.sort(). The elements will now be ordered in ascending order.
After sorting the array, it is again converted into a String and printed to the console. The output printed this time looks like this:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Sorting Arrays of Objects

The Arrays.sort() example shown earlier only works for Java arrays of primitive data types. Java's primitive data types have a natural ordering, either their numeric order, or the order of the characters in the ASCII table (the binary number representing the character).
If you want to sort an array of objects you need to use a different method. Objects may not have any natural sort order, so you need to provide another object which is capable of determining the order of your objects. Such an object is called a Comparator.
The Comparator is an interface. Interfaces are covered in my tutorial about Java interfaces. TheComparator interfaces is covered in more detail in my Java Collections tutorial, in the text about Java Collections - Sorting tutorial. If you don't understand Java interfaces or the Comparator interface, you may find it hard to understand the following code. But I will show it to you anyways.
Here is first the class for the objects we want to sort:
private static class Employee{
    public String name;
    public int    employeeId;

    public Employee(String name, int employeeId){
        this.name       = name;
        this.employeeId = employeeId;
    }
}
The class Employee is a simple model of an employee (I have created the Employee class). The employee has a name and an employee id. You could potentially sort an array of Employee objects by the name, or by their employee id. I will show you how to do both.
Here is first an example of sorting an array of Employee objects by their name using the Arrays.sort()method:
Employee[] employeeArray = new Employee[3];

employeeArray[0] = new Employee("Xander", 1);
employeeArray[1] = new Employee("John"  , 3);
employeeArray[2] = new Employee("Anna"  , 2);

java.util.Arrays.sort(employeeArray, new Comparator<Employee>() {
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.name.compareTo(e2.name);
    }
});


for(int i=0; i < employeeArray.length; i++) {
    System.out.println(employeeArray[i].name);
}
First a Java array is declared. The array is of type Employee - the class I showed you earlier. Second, threeEmployee objects are created and inserted into the array.
Third, the Arrays.sort() method is called to sort the array. As parameter to the Arrays.sort() method we pass the employee array, and a Comparator implementation which can determine the order of Employeeobjects. Don't worry if you don't fully understand this statement. It creates an anonymous implementation of theComparator interface. Anonymous implementations of interfaces are covered in my text about nested classes in Java. The implementation also use Java Generics, which may further make it hard to read.
What is important to catch in this example is the implementation of the compare() method of the anonymous inner implementation of the Comparator interface. This method returns a positive number if the first object is "bigger" (later in sort order) than the second object, 0 they are "equal" (in sort order), and a negative number if the first object is "smaller" (earlier in sort order) than the second object. In the example above we simply call theString.compare() method which does the comparison for us (compares the employee names).
After sorting the array we iterate through it and print out the employee names. This is how the output printed looks:
Anna
John
Xander
Notice how the order has been reversed compared to the order in which they were originally inserted into the array.
Let us now see how it looks to sort the Employee objects by their employee id instead. Here is the example from before, with a modified implementation of the compare() method of the anonymous implementation of theComparator interface:
Employee[] employeeArray = new Employee[3];

employeeArray[0] = new Employee("Xander", 1);
employeeArray[1] = new Employee("John"  , 3);
employeeArray[2] = new Employee("Anna"  , 2);

java.util.Arrays.sort(employeeArray, new Comparator<Employee>() {
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.employeeId - e2.employeeId;
    }
});

for(int i=0; i < employeeArray.length; i++) {
    System.out.println(employeeArray[i].name);
}
Notice how the compare() method returns the difference between the employee ids by subtracting one from the other. This is the easiest way to determine the natural order of number variables.
The output printed from this code would be:
Xander
Anna
John
To compare the Employee objects in the array first by their name, and if that is the same, then by their employee id, the compare() implementation would look like this:
java.util.Arrays.sort(employeeArray, new Comparator<Employee>() {
    @Override
    public int compare(Employee e1, Employee e2) {
        int nameDiff = e1.name.compareTo(e2.name);
        if(nameDiff != 0) { return nameDiff; }
    
        return e1.employeeId - e2.employeeId;
    }
});

Filling Arrays With Arrays.fill()

The Arrays class has set of methods called fill(). These Arrays.fill() methods can fill an array with a given value. This is easier than iterating through the array and inserting the value yourself. Here is an example of using Arrays.fill() to fill an int array:
int[] intArray = new int[10];

Arrays.fill(intArray, 123);

System.out.println(Arrays.toString(intArray));
This example creates an int array and fills the value 123 into all elements in the array. The last line of the example converts the array to a String and prints it out to the console. Here is what the output would look like:
[123, 123, 123, 123, 123, 123, 123, 123, 123, 123]
There is a version of the Arrays.fill() method which takes a from and to index, so only elements with indexes in this interval are filled with the given value. Here is an example of that Arrays.fill() method:
int[] intArray = new int[10];

Arrays.fill(ints2, 3, 5, 123) ;

System.out.println(Arrays.toString(intArray));
This example only fills the elements which have index 3 and 4 (3 to 5 without 5) with the value 123. Here is the output printed from this example:
0, 0, 0, 123, 123, 0, 0, 0, 0, 0]

Searching Arrays with Arrays.binarySearch()

The Arrays class contains a set of methods called binarySearch(). This method helps you perform a binary search in an array. The array must first be sorted. You can do so yourself, or via the Arrays.sort() method covered earlier in this text. Here is an Arrays.binarySearch() example:
int[] ints = {0,2,4,6,8,10};

int index = Arrays.binarySearch(ints, 6);

System.out.println(index);
The second line of this example searches in the array for the value 6. The binarySearch() method will return the index in the array in which the element was found. In the example above the binarySearch() method would return 3.
If more than one element exists in the array with the searched value, there is no guarantee about which element will be found.
If no element is found with the given value, a negative number will be returned. The negative number will be the index at which the searched element would be inserted, and then minus one. Look at this example:
int[] ints = {0,2,4,6,8,10};

int index = Arrays.binarySearch(ints, 7);

System.out.println(index);
The number 7 is not found in the array. The number 7 should have been inserted into the array at index 4, if 7 was to be inserted into the array (and the sort order kept). Therefore binarySearch() returns -4 - 1 = -5 .
If all elements in the array are smaller than the sought value, then binarySearch() will return - length of the array - 1. Look at this example:
int[] ints = {0,2,4,6,8,10};

int index = Arrays.binarySearch(ints, 12);

System.out.println(index);
In this example we search for 12 in the array, but all elements in the array are smaller than 12. ThereforebinarySearch() will return -length (-6) - 1 = -6 -1 = -7.
The Arrays.binarySearch() method also exists in a version where you just search part of the array. Here is how that looks:
int[] ints = {0,2,4,6,8,10};

int index = Arrays.binarySearch(ints, 0, 4, 2);

System.out.println(index);
This example searches the array for the value 2 but only between index 0 and 4 (without 4).
This version of binarySearch() works just like the other version, except in the cases where no matching element is found. If no element is found matching within the index interval, then binarySearch() will still return the index of where the value should have been inserted. But, if all values in the interval are smaller than the sought value, binarySearch() will return -toIndex -1 , and not -array length - 1. Thus, thisbinarySearch() example
int[] ints = {0,2,4,6,8,10};

int index = Arrays.binarySearch(ints, 0, 4, 12);
will return -5 and not -7 like binarySearch(ints, 12) would have.

Checking if Arrays are Equal with Arrays.equals()

The java.util.Arrays class contains a set of methods called equals() which can be used to check if two Java arrays are equal. Two arrays are considered equal if the arrays have the same length, and the elements are equal to each other in the order they are found in the array. Look at this Arrays.equals() example:
int[] ints1 = {0,2,4,6,8,10};
int[] ints2 = {0,2,4,6,8,10};
int[] ints3 = {10,8,6,4,2,0};

boolean ints1EqualsInts2 = Arrays.equals(ints1, ints2);
boolean ints1EqualsInts3 = Arrays.equals(ints1, ints3);

System.out.println(ints1EqualsInts2);
System.out.println(ints1EqualsInts3);

This example compares the array ints1 to the arrays ints2 and ints3. The first comparison will result in the value true since ints1 and ints2 contains the same elements in the same order. The second comparison will result in the value false. Array ints1 contains the same elements as ints3 but not in the same order. Therefore the two arrays are not considered equal.