Friday, May 27, 2005

class body

This is a class body.

class MyClass {
}
ClassMemberDeclaration =
FieldDeclaration | MethodDeclaration | ClassDeclaration | InterfaceDeclaration | ';' ;

Class bodies are used to group class members, such as methods that belong together.

Objects

"Programmer: A red-eyed, mumbling mammal capable of conversing with inanimate objects."
(Anonymous)

An object is a class instance (JLS3 2005).

You can create your own objects from your own class like this:

package animalfarm;

class Dog {
}

public class Main {
    public static void main(String[] args) {
        new Dog();
    }
}

The statement that creates the object is new Dog();.

Well, actually, the object may get garbage collected almost before it is created, so we need a pointer for it.

package animalfarm;

class Dog {
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
    }
}

The statement Dog dog = new Dog(); creates the dog pointer and the Dog object. Then the memory location of the object is assigned to the pointer.

The cool thing about OOP is that you can create as many objects as you like from the class! What will happen if you print the objects after they are created?

package bloggingjava;

public class Main {
    public static void main(String[] args) {
        Dog dog1 = new Dog();
        Dog dog2 = new Dog();
        Dog dog3 = new Dog();
        
        System.out.println(dog1 == dog2);
        System.out.println(dog1 == dog3);
        System.out.println(dog2 == dog3);
    }
}
false
false
false

The program compares the references (or pointers) to the objects using the reference equality operator ==. Obviously, each reference points to an unique object, because each comparison is false.

toString

Program

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Source: Object.java (Sun Microsystems 2006).

Applications

"Real Programmers don't write application programs, they program right down on the bare metal. Application programming is for feebs who can't do system programming."
(Vleck 1982).

Introduction

Here you will learn what an application is, and about the different parts of an application. Later you will learn how to write and save an application using a text editor, how to compile an application and how to run an application.

Program

Any Java application must follow this structure:

// declare package after this line

// import classes or packages after this line

class JavaApplication {
    public static void main(String[] args) {
        // enter code after this line
    }
}

An application that follows this structure is the HelloWorld application, a typical "first program" printed in most text books:

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Output

This program is supposed to print "Hello World" to the screen, but does nothing much yet, because it has to be compiled and executed first.

Discussion

Now, you will get a quick tour of the code.

Also remember that Java is case-sensitive!

Types of Applications

Such Java applications are running in a terminal window in text mode. It is possible to extend this application to build much more sophisticated applications, such as GUI applications and applets, by importing parts of the Java library. Read about Swing for GUI applications (reference needed).

class

class HelloWorld {
}

This part of the code is called a class declaration, and contains the parts of the class called the class members which is actually the rest of the program code. Be aware that a program can have many classes.

Now, consider the HelloWorld application. Java programs seems impossible to apprehend at first sight. You should always do the simplest thing that works, right? Would it not be much simpler just to write:

println("Hello World!");

Why do we have to write all that other stuff? The main reason for the extra code in Java, is that Java forces us to use object-oriented programming (OOP). This program isn't much OOP-ish, but even so OOP dictates that all code should go inside classes.

main

The method main is where the Java interpreter will start the program execution. The Java Virtual Machine assumes that the class contains a method called main, where execution will begin, and that will take the program parameters called args.

public static void main(String[] args) {
}

It is a convention to write method main as public static void main(String[] args) {, but you could also write:

  public static void main(String args[]) {
  public static void main(String[] arguments) {
  static public void main(String[] args) {

Note: Many classes in a Java application may contain a main method. This means that a Java application may have more than one possible starting point.

public

Consider the code:
public class JavaApplication { // unusual
    public static void main(String[] args) {
        // enter code after this line
    }
}

You don't normally need to use access modifiers like public for the class containing the main method. However, Netbeans IDE 5.0 declare its Main classes as public. It is not necessary to declare the the class public. The Java environment executes the main method anyway.

static

static is used so that main can be called without first making an instance of the class. That is, main is a class method.

void

The keyword void simply means that the method main does not return anything.

String[] args

Consider the code:
    public static void main(String args[]) { // not so good

This code works, but you should write String[] args and not String args[], because it is easier to see that args is a String array.

println

System.out.println("Hello World!");

This is the statement that prints "Hello World!".

References

Constants

"The primary purpose of the DATA statement is to give names to constants; instead of referring to pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant. This also simplifies modifying the program, should the value of pi change." (Wikipedia 2006)
FORTRAN manual for Xerox computers

Introduction

Constants are called final variables in Java. Variables that should never change value should be declared final Constants are usually declared public static final. PI is for example declared as public static final double PI = 3.14159265358979323846; (and as you may have observed, the value of PI did actually change since the FORTRAN days...)

Program

package bloggingjava;

class Main {
    public static void main(String[] args) {
        final int MONTHS;
        MONTHS = 12;
        // MONTHS = 13; // error, already assigned
        System.out.println("MONTHS: " + MONTHS);
    }
}

Output

MONTHS: 12

References

Static Factory Methods

Static factory methods is sometimes used instead of constructors (Bloch 2001).

Problem with constructors is that constructors do not have their own name, but same name as its class (Bloch 2001):

  • the name does not describe what the constructor returns (Bloch 2001).
  • must create a new object when invoked/called (Bloch 2001)
  • only one constructor with a given signature (Bloch 2001)
  • constructors can't return subclasses of class (Bloch 2001)

Definition: A static factory method is a public method that returns an instance of its class.

Naming Conventions

Bloch (2001) argues that adhering to standard naming conventions for static factory methods will make them readily distinguishable from other static methods, and says that the two names valueOf and getInstance are becoming common, the idea beeing that valueOf should return an instance that has the same value as its parameters and getInstance should return an instance described by its parameters.

However, it seems that both names are not much in use as of j2se 1.5.0. valueOf seems currently to be used mostly for type wrappers, and getInstance does not seem to be used that much. Perhaps a problem with standard naming conventions for static factory methods is that the name no longer really reflects what the method does. And after all, there already is a standard naming convention for constructors.

Examples of static factory methods

  • the public static Integer valueOf(int i) { method of class Integer
  • Conclusion

    * static factory methods have names (Bloch)
    * can return existing objects (Bloch)
    * can return subtypes (Bloch)
    * new is the standard way of creating objects (Bloch)
    * valueOf should return an instance with the same value as the parameters (Bloch)
    * getInstance should return an instance described by the parameters (Bloch)
    

    Thursday, May 19, 2005

    Explicit and Implicit Code

    Introduction

    There is basically two methods of writing program code. You could write all the code yourself explicitly, or you could let the compiler write some of the code for you implicitly.

    Discussion

    The words explicit and implicit are used extensively in most Java books and web pages. Obviously, it is important to know and understand the meaning of these words, so let's take a closer look at them.

    Implicit Code

    Introduction

    Wouldn't it be great if the compiler could write a lot of code for you automatically? Especially the boring, tedious stuff that always must be there, but that you would rather not write until absolutely necessary...

    Well, the compiler does just that, and often without the programmer even knowing. It's called implicit code, and is source code that is implied rather than directly expressed. The idea behind implicit code is that you do not have to do all the work yourself, because the compiler will write the code for you. Since the source code is implied, it does not actually show up in your program. But implicit code certainly end up as a part of the compiled code.

    Concept: Implicit code is source code that is implied rather than directly expressed.

    Program

    Consider the program:
    class Compute {
        public static void main(String[] args) {
            System.out.println(3 + 2 * 2);
        }
    }
    

    Output

    [user]$ javac Compute.java
    [user]$ java Compute
    7
    

    The application writes 7, not 10, because the compiler implicitly adds paranthesis around the operator with the highest precedence, 3 + (2 * 2).

    Discussion

    The compiler fills in the missing code implicitly for you, when needed, without actually changing the source code itself. Only the compiled code is affected. As a result, the source code look simpler, less cluttered and possibly you will also avoid a few bugs. On the other hand, you can always explicitly write the code yourself, if you want to.

    The code production is not totally random or uncontrollable. The compiler applies certain rules in order to discover implicit code when compiling source code. The rules will be discussed later at various places in the tutorial.

    Concept: Following certain rules, implicit code is added implicitly by the compiler.

    Note: There's a lot of implicit stuff going on in Java. The reason is that many programmers usually view implicit features as a convenience. However, the rules for implicit code must be clearly understood and always be remembered, actually making programming less comfortable or easy in many situations.

    Explicit Code

    Introduction

    Usually, you will write explicit code in order to avoid ambiguous code or simply because there is no implicit alternative.

    Concept: Explicit code is source code that must be expressed completely.

    Program

    Consider the program:
    class Compute {
        public static void main(String[] args) {
            System.out.println(3 + 2 * 2);
        }
    }
    

    Output

    7
    

    Discussion

    Imagine that the programmer thinks that it is unclear which operation, + or *, is performed first.

    class Compute {
        public static void main(String[] args) {
            System.out.println((3 + 2) * 2);
        }
    }
    

    Parenthesis has been explicitly added around 3 + 2 in order to avoid any ambiguity.

    Sunday, May 15, 2005

    Louden 1997

    Author Louden, Kenneth C.
    Year 1997
    Title Compiler Construction, Principles and Practice
    Place
    Publisher

    Saturday, May 14, 2005

    Cho 2004

    References

    Wednesday, May 11, 2005

    Memoization

    Introduction

    Instead of recomputing results for each function call, the results of function calls can be stored for later reuse. This technique is called memoization (Wikipedia 2007).

    Program

    class Fib {
        static long[] fibarray;
        
        public static void main(String[] args) {
            int n = Integer.parseInt(args[0]);
            
            fibarray = new long[n + 1];
            fibarray[1] = 1;
            fibarray[2] = 1;
            
            for (int i = 1; i <= n; i++) {
                System.out.print(memoizedFib(i) + " ");
            }
            System.out.println();
        }
        
        public static long memoizedFib(final int n) {
            return fibarray[n] == 0 ? fibarray[n] = memoizedFib(n - 1) + memoizedFib(n - 2) : fibarray[n];
        }
    }
    

    Output

    [user]$ javac Fib.java
    [user]$ java Fib 92
    1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881
    6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393 1304969544928657 2111485077978050 3416454622906707 5527939700884757 8944394323791464 14472334024676221 23416728348467685 37889062373143906 61305790721611591 99194853094755497 160500643816367088 259695496911122585 420196140727489673 679891637638612258 1100087778366101931 1779979416004714189 2880067194370816120
    4660046610375530309 7540113804746346429
    

    References

    Monday, May 09, 2005

    Barron 1977

    Author David William Barron
    Year 1977
    Title An Introduction to the Study of Programming Languages
    Place Cambridge
    Publisher Cambridge University Press

    Friday, May 06, 2005

    Cleaveland 1986

    (Cleaveland 1986).

    References

    • Cleaveland, J. Craig. (1986). An introduction to data types. London: Addison-Wesley.

    Wednesday, May 04, 2005

    Syntactic Salt

    Introduction

    Syntactic salt is a feature designed to make it harder to write bad code. An example of syntactic salt in Java is Generics. The need for adding a semicolon, ;, after each and every statement could be viewed as syntactic salt.

    Concept: Syntactic salt are constructs added to a language in order to make it harder for programmers to write bad source code.

    Resources

    Sunday, May 01, 2005

    Varargs

    Introduction

    Varargs are methods with variable number of arguments (Schubart 2004).

    Discussion

    The format method takes varargs: public static String format(String pattern, Object... arguments)

    import java.text.MessageFormat;
    
    class JavaApplication {
        public static void main(String[] args) {
            String pattern = "{0} weigh {1} kg.";
            String message = MessageFormat.format(pattern, "Polar bears", new Integer(800));
            System.out.println(message);
        }
    }
    
    [user]$ javac JavaApplication.java
    [user]$ java JavaApplication
    Polar bears weigh 800 kg.
    

    What happens is that the compiler write this code implicitly: String message = MessageFormat.format("{0} weigh {1} kg.", new Object[] {"Polar bears", new Integer(800)});

    Conclusion

    Varargs is a case of syntactic sugar. The compiler treats public static String format(String pattern, Object... arguments) like public static String format(String pattern, Object[] arguments)

    References

    Resources