User Tools

Site Tools


java_faq

Installing Java

Installing Oracle's Java on Linux may be done in different ways.

  • APT compatible
  • manual

APT Compatible

the package is provided by duinsoft.nl Add to sources.list

### Duinsoft Oracle Java ###
# http://www.duinsoft.nl/packages.php?t=en
deb [arch=amd64,i386] http://www.duinsoft.nl/pkg/ debs all

Manual Install

Following this instructions. The necessary steps are only:

  • download the jdk package from Oracle
  • install it manually
  • update alternatives

Once unpacked and installed launch the following commands:

update-alternatives --install /usr/bin/java java /opt/java/jdk1.8.0_101/bin/java 1100
update-alternatives --install /usr/bin/javac javac /opt/java/jdk1.8.0_101/bin/javac 1100

where the path should link to the actual java and javac files on your hard drive.

Java Basics

Arrays

In Java there are primitive types boolean, byte, short, int, long, float, double, char arrays and Java Objects. Arrays are exactly what one expects them to be: an ordered group of elements of the same type; the elements may be accessed singularly. Arrays are declared and initialized similarly to C/C++.

How do I create an array ?

double[] array = new double[10]; //create a new array of double with 10 elements, initialized to the default value 0
double element = array[0]; // this would return 0

To access the elements of an array one uses the standard “slicing” operator as in C/C++/Python.

Multidimensional arrays are declared in this way:

int[][] myarray = new int[3][2];
//or
int[] myarray[] = new int[3][2];
//or
int myarray[][] = new int[3][];

It is important that at least the first dimension of the array to be declared, i.e. Java wants to know how much memory to allocate. However this is not allocation of memory on the heap to store the actual data, but the memory to contain the references to the elements. I would say that Java wants to know how many pointers to other things it has to allocate!

int[][] md = new int[3][];
int[][] md = new int[][]; // DOESN'T COMPILE array dimension missing
 
int[] first = new int[1];
int[] second = new int[2];
int[] third = new int[3];
 
md[0] = first;
md[1] = second;
md[2] = third;

Arrays are Java Objects!!!

However arrays in Java are actually Java Objects! As a matter of facts they inherit from java.lang.Object. The output of the following code

int [] ia = {1,2,3};
// testing methods of Object
System.out.println("toString() " + ia.toString());
System.out.println("hashCode() " + ia.hashCode());
System.out.println("getClass().getCanonicalName() " + ia.getClass().getCanonicalName());
 
int [] ia2 = ia.clone();
int [] ia3 = ia;		
System.out.println("x.equals(x) " + ia.equals(ia)); // reflexive
System.out.println("original.equals(clone) " + ia.equals(ia2));  // clone and original have the same elements
		        					 // but are not considered equal because they point to different
	         						 // memory areas
System.out.println("original.equals(same) " + ia.equals(ia3));   // ia3 points to the same memory as ia => 
							         // they are equal for Object equals
System.out.println("clone() " + ia2.toString());
for(int i=0;i<ia.length;i++){
	System.out.println("original " + ia[i] + " clone " + Array.get(ia2, i)); //notice that the second array is accessed with the static
                                                                                 //method of the Array class
}

is

toString() [I@631e1aa5

hashCode() 1662917285
getClass().getCanonicalName() int[]
x.equals(x) true
original.equals(clone) false
original.equals(same) true
clone() [I@4d677979
original 1 clone 1
original 2 clone 2
original 3 clone 3

It is not surprising that the array can be sliced or declared as in many other programming languages, what is confusing is that an array is actually a class inheriting from java.lang.Object which does not allow slicing!

An array can be declared and initialized in a more object-like manner as

import java.lang.reflect.Array;
 
... 
 
int[] o = (int[]) Array.newInstance(int.class, 3); // declaration + initialization. It allocates the memory 
// elements can be set with a method-like manner
Array.set(o, 0 , 1); // set element 0 of o to 1
Array.setInt(o, 1, 2); // set element 1 of o to 2
// or with the array-special notation
o[2] = 3; // set element 2 of o to 3
 
try {
    Array.setBoolean(o, 2, false); // throws IllegalArgumentException
} catch (NullPointerException e0) {
    e0.printStackTrace();
} catch (IllegalArgumentException e1) {
    e1.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e2){
    e2.printStackTrace();
} finally {
 
}
 

Array Equality

The equality operator “==” checks for object equality, that is it checks whether two variable reference the same instance (same memory area). Using .equals operator does not change the things because the Array does not override the method .equals() from Object and therefore this is what happens:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

How do I create a matrix ?

double[][] matrix = new double[5][10];

How do I get the array size ?

int n = array.length;

ArrayList

Arrays are unflexible in the way that they cannot be resized once created. When you need more flexibility in this respect you use an ArrayList. An ArrayList implements the List interface.

A list is An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. … The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The Arrays class provides a number of convenience methods to operate on Arrays. It also contain the static method 'asList' to transform an array to a List.

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
 
public class ArrayExample{
 
    public static void main(String ... args){
 
        String[] array = new String[]{"abc" ,"def" , "ghi"}; // create an array of strings
        List list = Arrays.asList(array);                    // create a List from it
        System.out.println(list);                            // print the content list
 
        array[0] = "edo"; // changing the content of the array reflects on the list! Because they share the same data!
        System.out.println(list);                            // print the content of the list after changing the array
 
 
    }
}

outputs:

[abc, def, ghi]
[edo, def, ghi]

Great! However we don't have the flexibility we wanted because the asList method Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array. So if one tries to add an element to the list the compiler complains uses unchecked of unsafe operations and upon execution it throws a java.lang.UnsupportedOperationException

Not great!!! We need an ArrayList that is a Resizable-array implementation of the List interface.

We cannot create the ArrayList from the String[] because the constructor of the ArrayList takes only int or Collections as parameters. Continuing on the previous example:

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
 
public class ArrayExample{
 
    public static void main(String ... args){
 
        String[] array = new String[]{"abc" ,"def" , "ghi"};    // create an array of strings
        List<String> list = (List<String>)Arrays.asList(array); // create a List<String> from it; requires an explicit cast!
        System.out.println("list " + list);                     // print the content list
 
        ArrayList<String> alist = new ArrayList<String>(list); // creates the ArrayList from the List
                                                               // the data are duplicated now
 
        array[0] = "edo"; // changing the content of the array reflects on the list! Because they share the same data!
        System.out.println("list " + list);                    // print the content of the list after changing the array
 
        System.out.println("alist " + alist);                  // the data of the ArrayList is not the same as the one from Array and List
                                                               // and the first element is not changed
 
        alist.add("jkl");
        System.out.println("alist " + alist);
    }
}

outputs:

list [abc, def, ghi]
list [edo, def, ghi]
alist [abc, def, ghi]
alist [abc, def, ghi, jkl]

So far so good! The thing becomes interesting when we try to do a similar thing with a numeric array like 'int[]', 'double[]' etc.

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
 
public class ArrayExample{
 
    public static void main(String ... args){
        int[] b = new int[]{1,1,2,3,4,5,6,7,8,9};
        Integer[] c = new Integer[b.length];
 
	for (int i =0;i<c.length;i++){
	    c[i] = i ;
	}
 
 
	List list2 = Arrays.asList(c);
 
	List list1 = Arrays.asList(b);
 	System.out.println("list1 " + list1);    // print the content of the list converted directly from an array of primitives, int[]
        System.out.println("list2 " + list2);    // print the content of the list converted from an array of some object as Integer[]
    }
}

The output is kind of surprising:

list1 [[I@15db9742]
list2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

that means that list1 is a list which contains an int[], while the other is what we expected to find. This has to do with Java generics. Java generics is the analogous of templates in C++, but while in C++ anything can be a typename in Java a type variable can be any NON-PRIMITIVE type.

In our example I used an array of primitives, which is the only object in the matter and Java used it to perform the transformation to List, as it is a non-primitive object. Therefore list1 is a List containing one element of type int[].

java_faq.txt · Last modified: 2017/01/02 15:01 by 178.237.8.52