Java Reference
In-Depth Information
Element at row 2 and column 1 is: 20.
Element at row 1 and column 0 is: 2.
Note that the matrix variable is an array of equal size arrays, each having three elements. This does
not necessarily need to be the case. You can also create arrays of unequal sized arrays, as follows:
public class MatrixExample {
// declare and initialize the matrix
static int[][] weirdMatrix={{1, 2},{2, 6, 8},{10}};
// This is our main method.
public static void main(String[] args){
// print some of the matrix numbers to the screen
System.out.println("Element at row 0 and column 1 is: " +
weirdMatrix[0][1] + ".");
System.out.println("Element at row 2 and column 2 is: " +
weirdMatrix[2][0] + ".");
System.out.println("Element at row 2 and column 1 is: " +
weirdMatrix[1][2] + ".");
}
}
The output of this program is now:
Element at row 0 and column 1 is: 2.
Element at row 2 and column 2 is: 10.
Element at row 2 and column 1 is: 8.
Here, you are accessing each element directly using the weirdMatrix [1][2] notation, but there are
also loop structures that are often used to iterate through the elements of an array somewhat auto-
matically. These are discussed in Chapter 5, and arrays will be revisited there.
type casting
Type casting refers to converting a value from a specific type to a variable of another type. Booleans
cannot be converted to numeric types. For the other data types, two types of conversion can be con-
sidered: widening conversion (implicit casting) and narrowing conversion (explicit casting). Before
we discuss these further, remember the hierarchy of primitive data types as follows (from high preci-
sion to low precision): double , float , long , int , short , and byte .
A widening conversion is when a value of a narrower (lower precision) data type is converted to a
value of a broader (higher precision) data type. This causes no loss of information and will be per-
formed by the JVM implicitly. An example is as follows:
static int a = 4;
double x = a;
In this example, an integer variable a with value 4 is promoted to a higher-order double data type
without loss of information. Although this code will successfully compile, it is good programming
practice to explicitly mention the casting as follows:
 
Search WWH ::




Custom Search