Java Virtual Machine Is An Abstract Computing Machine, or Virtual Machine, JVM Is A
Java Virtual Machine Is An Abstract Computing Machine, or Virtual Machine, JVM Is A
JVM
What is a Virtual Machine? Java Virtual Machine is an abstract computing machine, or virtual machine, JVM is a platform-independent execution environment that converts Java bytecode into machine-language and executes it. Most programming languages compile source code directly into machine code that is designed to run on a specific microprocessor architecture or operating system, such as Windows or UNIX. A JVM -- a software -- mimics a real Java processor, enabling Java bytecode to be executed as actions or operating system calls on any processor regardless of the operating system. For example, establishing a socket connection from a workstation to a remote machine involves an operating system call. Since different operating systems handle sockets in different ways, the JVM translates the programming code so that the two machines that may be on different platforms are able to connect. Java Byte-Code: when you compile your Java source code, the javac compiler produces platform independent 'byte code'. Unlike a C compiler for example which will produce code that is native to the hardware of the platform you compile on, the Java byte code is platform independent and can be executed on any platform where you have a JVM available/installed. The JVM interprets the byte code and executes it on that platform, in some cases (like with Sun HotSpot in the Sun JVMs) compiling the byte code at run time on the fly into native platform code as a performance optimization. A virtual machine (VM) is an abstract computer architecture Software on top of a real hardware Can run the same application on different machines where the VM is available
Arrays in Java
Declaring Arrays
Like all other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. One array cannot store both ints and Strings, for instance. Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:
int[] k; float[] yt; String[] names;
This says that k is an array of ints, yt is an array of floats and names is an array of Strings. In other words you declare an array like you declare any other variable except that you append brackets to the end of the type. You also have the option to append the brackets to the variable instead of the type.
int k[]; float yt[]; String names[];
However, unlike in C, you cannot include the length of the array in the declaration. The following is a syntax error:
int k[3]; float yt[7]; String names[100];
3 Each array element is accessed by its numerical index: System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]); Alternatively, you can use the shortcut syntax to create and initialize an array: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000}; Here the length of the array is determined by the number of values provided between { and }. You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values. In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program: class MultiDimArrayDemo { public static void main(String[] args) { String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; System.out.println(names[0][0] + names[1][0]); //Mr. Smith System.out.println(names[0][2] + names[1][1]); //Ms. Jones } } The output from this program is: Mr. Smith Ms. Jones Finally, you can use the built-in length property to determine the size of any array. The code
System.out.println(anArray.length);
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src,int srcPos, Object dest, int destPos, int length) The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy. The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array: class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } } The output from this program is: caffeine Sort a Java array Java API Arrays contains static methods for sorting. It is a best practice to use them always to sort an array. import java.util.Arrays; public class ArraySort { public static void main(String args[]) { int marks[] = { 98, 95, 91, 93, 97 }; System.out.println("Before sorting: " + Arrays.toString(marks)); Arrays.sort(marks); System.out.println("After sorting: " + Arrays.toString(marks)); } }
5 Static methods for manipulating arrays are available in the java.util.Arrays and java.System classes. Assume the following declarations, where T is the array element type, either a primitive, object or either kind of type depending on which method is being called. T T[] x, key; // This type T can be either a primitive or object type. a, a2; // This type T can be either a primitive or object type. // Only object types T.
Comparator<? super T> comp; // Only object types T. // Index returned from search. i1, i2; from; // Lower bound of subscript range. Includes this element. to; // Upper bound of subscript range. Does not include this element.
lst = Arrays.asList(a); s = Arrays.toString(a); s = Arrays.deepToString(a); b = Arrays.equals(a, a2); b = Arrays.deepEquals(a, a2); Arrays.fill(a, x); Arrays.fill(a, from, to, x);
List based on the array. String form surrounded by "[]", elements separated by ", ". String form by recursively converting subarrays. True if arrays are same size and all elements are equal (== or equals as appropriate). As above, recursively applied to subarrays. Fills array with a value. Fills subrange (from inclusive, to exclusive) with a value.
Making a copy of part of an array System.arraycopy(a, i1, a2, i2, len); Shallow copy len elements from a[i1] to a2[i2]. Case! a2 = Arrays.copyOf(a, newLength); New shallow copy of array with new length. If longer, uses default values. a2 = Arrays.copyOfRange(a, from, to); New shallow copy of portion of array. Searching i = Arrays.binarySearch(a, key);
A O(log N)search of array sorted in ascending order. If the key is not found, a negative number, -insertionPoint-1, is returned. i = Arrays.binarySearch(a, key, comp); Binary search of a sorted array of objects (not primitives).
Sorting. See Sorting Arrays for more on sorting and comparators. Arrays.sort(a); Sorts in "natural" order. If object type, elements must be comparable.
6 Arrays.sort(a, comp); Arrays.sort(a, from, to); Arrays.sort(a, from, to, comp); Sorts objects (not primitives) using comparator. Sorts subrange, including a[from] excluding a[to]. Sorts objects (not primitives) in subrange using comparator.
Java ArrayList
7 The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. ArrayList has the constructors shown here: ArrayList( ) ArrayList(Collection c) ArrayList(int capacity) The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list. The following program shows a simple use of ArrayList. An array list is created, and then objects of type String are added to it. (Recall that a quoted string is translated into a String object.) The list is then displayed. Some of the elements are removed and the list is displayed again. ArrayList class provides methods for basic array operations: add( Object o ) - puts reference to object into ArrayList get( int index ) - retrieves object reference from ArrayList index position size() - returns ArrayList size remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list. indexOf( Object o) - finds the index in this list of the first occurrence of the specified element clear() - removes all of the elements Following example ask user for his/her name, and suggests him/her a vacation place. ArrayList "myarr" is filled with resort names(add method). After user enters his name, we calculate residue of division of user's name length by myarr size -- operation result is a number from 0 to myarr.size()-1 -- which is suitable as array index.
warning
ArrayList stores only object references. That's why, it's impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead. For multi-theaded(synchronized) array class use Vector (java.lang.Vector)