Skip to content

General

This is meant to be a quick refresh course of the chapters in the java book and various tutorials. It is meant to be complete yet terse. No numbers here because there are two sources i tried to divide as best as possible.

Two links to refresh your java memory :

'Tutorialspoint visit which is nice an terse and the basis for this page. 'And this one visit The Java® Language Specification, which is less terse but of course very detailed

detailed

In order of size :

  • Use the second link more as a reference for when you have a specific java issue.
  • I would advice the first if you have to do a fresh-up course.
  • Or the rest of this page, where i left out all things that hardly differ from c
  • And if you want a REAL terse description : just focus on the titles and framed parts and only look at the surrounding text if it is unclear.

Installation

jdk

You could take the oracle version if you need to use oracle db's. You would be better of then, and also if you install centos!.

I chose for the complete default :

install
apt-get install openjdk-6-jdk

note that you can install multiple versions of java, but only one will be de default, and thus the one called when you call java or javac. You can switch this behavior with :

change version
update-alternatives --config java

eclipse

Now here the simplest would be

install eclipse
apt-get install eclipse

But you get a version 3.8 (Indigo) while there are 3 newer versions available

  • 4.2 : Juno
  • 4.3 : Kepler
  • 4.4 : Luna

But installing luna crashes with a gdk_display_open error so i stick with Indigo.

compilation

Java programs get compiled into intermediate code that than can be run on the virtual machines of various platforms. A simple source file :

example
1
2
3
4
5
6
class HelloWorld
{
    public static final void main(String args[]) {
        System.out.println("Hello, world");
    }
}

Can be compiled with :

compiling
javac HelloWorld.java

This makes an object code file called HelloWorld.class runnable on multiple platforms. To run it on the local one :

execute
1
2
3
java HelloWorld

Hello, world

Running

class resolution

In the previous example all files where in the same directory, hence classes could be found easily. But if you try this in eclipse, just creating a single class will cause the directory to be split in :

class resolution
1
2
3
4
5
Chapter
    src
        Hello.java
    bin
        Hello.class

To get this result with Scons, create as Sconstruct file with :

scons
env = Environment()
env.Java("bin", "src");

And of course move HelloWorld.java into the src directory. After running scons, the class file will be bin/HelloWorld.class, and you cannot run it with java HelloWorld anymore :

in subdirectory
1
2
3
4
5
6
7
8
java HelloWorld 
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld


java bin.HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: bin/HelloWorld (wrong name: HelloWorld)
java bin/HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: bin/HelloWorld (wrong name: HelloWorld)

Both of the above notations are the same, in fact bash will make it a dot for you.The class can be found, but it is the wrong name. This would work :

specify classpath
java -cp bin HelloWorld
Hello, world.

Because you set the classpath to bin, like cd into bin and then run HelloWorld. If you want it to be run from the top directory with setting the classpath, you will have to make the name fit, which can be done with packages

debug class resolution

You can quickly find out where java looks for classes by using the -verbose option :

verbose
java -verbose classname

It will put a LOT of information but it is very clarifying :

output
1
2
3
4
5
java -verbose postgres
[Opened /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar]
[Loaded java.lang.Object from /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar]
... much MUCH more

installed extensions

Java loads classes in the following order:

  • Bootstrap classes - Classes that comprise the Java platform, including the classes in rt.jar and several other important jar files.
  • Extension classes - Classes that use the Java Extension mechanism. These are bundled as .jar files located in the extensions directory.
  • User classes - Classes defined by developers and third parties that do not take advantage of the extension mechanism. You identify the location of these classes using the -classpath option on the command line (the preferred method) or by using the CLASSPATH environment variable. (See Setting the Classpath for Windows or Unix.)

So you need the second one if you need to install some library system-wide. Now to find the extensions directory the output of java -verbose as explained in the previous chapter is very handy. In this case the extensions should be put in :

extensions
cp *.jar /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext

If you want to do this without knowing the exact java version (blind installs) , this would be your best option (tested on debian only) :

blind install
cp *.jar /usr/lib/jvm/default-java/jre/lib/ext

Warning

Update debian9 : this seems to have changed

The last time I had to install an extension (json-simple) this did not work.

jvm directory
ls -l /usr/lib/jvm 

lrwxrwxrwx 1 root root 39 Jul 30 09:18 java -> /usr/lib/jvm/java-8-oracle/jre/bin/java
kees@hoek:/etc/alternatives$ ls -l /usr/lib/jvm/
total 12
lrwxrwxrwx  1 root root   24 May  6  2014 default-java -> java-1.7.0-openjdk-amd64
lrwxrwxrwx  1 root root   20 Aug 24  2017 java-1.7.0-openjdk-amd64 -> java-7-openjdk-amd64
drwxr-xr-x  7 root root 4096 Jun 12 13:25 java-7-openjdk-amd64
drwxr-xr-x  7 root root 4096 Jul 30 09:16 java-8-oracle
drwxr-xr-x 10 kees kees 4096 Sep  6  2017 jdk1.8.0_151

This gives some mixed information :

  • default-java seems to be java-1.7.0-openjdk-amd64
  • the java executable seems to be /usr/lib/jvm/java-8-oracle/jre/bin/java

It seems best to do these steps to find out what gets used :

links
1
2
3
4
5
6
7
8
javac -version # to know which version is used
javac 1.8.0_181
which javac
/usr/bin/javac
ls -l /usr/bin/java*
lrwxrwxrwx 1 root root 22 Nov 10  2017 /usr/bin/java -> /etc/alternatives/java
lrwxrwxrwx 1 root root 29 Nov 10  2017 /usr/bin/java2groovy -> /etc/alternatives/java2groovy
lrwxrwxrwx 1 root root 23 Nov 10  2017 /usr/bin/javac -> /etc/alternatives/javac

These last executables seems to all agree on /etc/alternatives, and /etc/alternatives contains another link to the correct directory, so :

find ext dir
1
2
3
ls -l /etc/alternatives/javac
/etc/alternatives/javac -> /usr/lib/jvm/java-8-oracle/bin/javac
cp json-simple.jar /usr/lib/jvm/java-8-oracle/jre/lib/ext/

Now you extension works.

directory structure :

Source directory structure is directly equivalent to package structure, and that's essentially built into Java. Everything else is a bit less clear-cut.

A lot of simple projects are organized by hand, so people get to pick a structure they feel OK with. What's often done (and this is also reflected by the structure of projects in Eclipse, a very dominant Java tool) is to have your source tree begin in a directory called src. Your package-less source files would sit directly in src, and your package hierarchy, typically starting with a com directory, would likewise be contained in src. If you CD to the src directory before firing up the javac compiler, your compiled .class files will end up in the same directory structure, with each .class file sitting in the same directory and next to its .java file.

If you have a lot of source and class files, you'll want to separate them out from each other to reduce clutter. Manual and Eclipse organization often place a bin or classes directory parallel to src so the .class files end up in a hierarchy that mirrors that of src.

If your project has a set of .jar files to deliver capability from third-party libraries, then a third directory, typically lib, is placed parallel to src and bin. Everything in lib needs to be put on the classpath for compilation and execution.

Finally, there's a bunch of this and that which is more or less optional:

docs in doc resources in resources data in data configuration in conf... You get the idea. The compiler doesn't care about these directories, they're just ways for you to organize (or confuse) yourself.

Basic syntax

identifiers

  • start character is a 'java letter' (Character.isJavaIdentifierStart()), which can be _, $ or any unicode character that is not digit or punctuation character (or of course a whitespace)
  • rest of the characters are 'javaletter-or-digits' (Character.isJavaIdentifierPart()), same as javaletter but with the digits added.
  • all keywords are forbidden as identifier
  • identifiers are case sensitive
  • no limit to the length imposed
identifiers
1
2
3
4
5
6
7
8
9
int MyVariable
int myvariable
int _myvariable
int $myvariable
int _9pins
int andros
int ανδρος
int OReilly
int This_is_an_insanely_long_variable_name_that_just_keeps_going_and_going_and_going_and_well_you_get_the_idea

modifiers

  • access modifiers : default, public, private, protected
  • non access modifiers : final, abstract, strictfp

variable

  • local variables
  • class variables (static)
  • instance variables (object)

enums

classes and interfaces

abstract class vs interface

  • a class can only inherit from one abstract class, but implement many interfaces (closest thing to multiple inheritance)
  • an abstract class can provide some default methods and leave other methods unimplemented (abstract), interfaces have no implementation.
  • abstract class inheritance is really meant for the 'is-a' relationship (square is-a shape), while an interface just enforces an interface to the class implementing them (apple implements list_of_things)
  • also.. an abstract class can have some private methods, in an interface all members must be public

operators

instanceof

Test if a variable is of some type:

instanceof
( Object reference variable ) instanceof  (class/interface type)

Like :

instanceof
1
2
3
String name = "James";
boolean result = name instanceof String;  
System.out.println( result );

true.. if you wonder. But this also traverse class hierarchy, so :

subclasses
1
2
3
4
5
6
7
8
9
class Vehicle {}

public class Car extends Vehicle {
    public static void main(String args[]){
        Vehicle a = new Car();
        boolean result =  a instanceof Car;
        System.out.println( result );
    }
}

also .. true

program control

Sorry, but i will only do the ones really differing from c ;)

Mainly for arrays.

for loop
1
2
3
4
for(declaration : expression)
{
     //Statements
}

So this resembles the construct for var in container which is the most common appearance for extended loops.

Declaration is the declaration of the loop variable and expression the array you need to loop through.

for loop
public class Test {
   public static void main(String args[]){
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names ={"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

wrapper classes

Number class

Wrapper classes are used when the basic types are better represented by an object instead of a base class. The base class is Number and the subclasses for each native type are :

  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double

The process of conversion between native and it's object equivalent is called 'boxing' and 'unboxing'.

Integer
1
2
3
4
5
6
7
8
9
public class Test{
    public static void main(String args[]){
        Integer x = 5; // boxes int to an Integer object
        x =  x + 10;   // unboxes the Integer to a int
        System.out.println(x); 
    }
}

15

You can use some neat methods on a Number, like

  • parseInt(), parseFloat(), ...
  • intValue(), floatValue(), ...
  • floor()
  • round()
  • etc...

Character class

Same idea as for Number, you could box the char classes in the Character class.

Character
Character ch = new Character('a');

The Character class provides some useful methods like :

  • isLetter()
  • isDigit()
  • toString()
  • ...

String

You would make your life hard to use arrays of characters in java since the String objects is so founded in the language. You can also see this as a wrapper object for string literals since :

String
String x = "Hi there";

Does a similar a similar thing and can be seen as the boxing operation for String. Though string has 11 different constructors like for String, character array, byte array etc.

String is immutable, so if you want to modify strings a lot you better use String builder or StringBuffer.

String formats can also be used like in the c printf function :

formatting
1
2
3
4
System.out.printf("The value of the float variable is " +
              "%f, while the value of the integer " +
              "variable is %d, and the string " +
              "is %s", floatVar, intVar, stringVar);

But you can also create a separate format like :

formatting
1
2
3
4
5
6
String fs;
fs = String.format("The value of the float variable is " +
               "%f, while the value of the integer " +
               "variable is %d, and the string " +
               "is %s", floatVar, intVar, stringVar);
System.out.println(fs);

Some string methods :

  • length()
  • compareTo()
  • charAt()
  • concat()
  • split()
  • etc...

Arrays

First of, there is a limit of 31 bits or 2,147,483,645 array members. Sorry but i have to stop and take a rest here..... Ok on with it...

Second Arrays are Objects, so you need to use new to instantiate them.

declaration

declare array
int [] var = new int[100];

This is the preferred way, so the type is (int []) and you cannot say : int x[100]; .. you HAVE to use new.

initialization

Alternatively initialization does not need new :

initialization
int [] var = { 1, 2, 3, 4};

Still the preferred ways is int[] var. As mentioned before you can loop through an array like this :

double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); }

Yields :

output
1
2
3
4
1.9
2.9
3.4
3.5

immutable objects

Integer is one example, and the principle is the same as a String. If you assign a new value to a String, you expect it's identity(ptr) to change:

immutability
1
2
3
4
5
String s = "Eerste";    // immutable 
s = "Tweede"
// s is now "Tweede" but it's a different string !!
Integer i = 1;
i = 2; // same principle!!

This means you cannot pass an Integer to a function and expect you can change it's value .