Saturday, April 23, 2005

Halfon 2003

Author Halfon, Amir
Year 2003
Title New Java Language Features in JDK 1.5
Place
Publisher Sun Microsystems
Retrieved Saturday, April 23, 2005
URL http://www.javasig.com/Archive/lectures/JavaSIG-Tiger.pdf

Wednesday, April 20, 2005

Parameters and Arguments

Introduction

A parameter is a variable named inside the parentheses of a method definition (Kernighan & Ritchie 1988).

An argument is the value for a parameter used when calling the method (Kernighan & Ritchie 1988).

Discussion

formal argument == parameter
actual argument == argument
(Kernighan & Ritchie 1988).

References

  • Kernighan, Brian W. & Dennis M. Ritchie. (1988). The C programming language. New Jersey: Prentice Hall.

Tuesday, April 19, 2005

JLS3 2005

The Java Language Specification, Third Edition is now available in a pre-publication PDF release.

You may find a clickable version of the grammar here: The Java JLS3 Grammar.

ID JLS3
Author Gosling, J., B. Joy, G. Steele & G. Bracha
Year 2005
Title The Java Language Specification, Third Edition
Place Boston
Publisher Addison-Wesley
Retrieved March 4, 2006
URL http://java.sun.com/docs/books/jls/

Saturday, April 16, 2005

Quote of the Day

"If a program is useful, it must be changed."
(Anonymous).

Friday, April 15, 2005

How to add Button Color

Program

Basic idea

JButton colorButton = new JButton("Color Button");
colorButton.setBackground(Color.red);
colorButton.setForeground(Color.white);

Complete program

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingApplication extends JFrame {
    public static void main(String[] args) {
        new SwingApplication().createFrame();
    }

    void createFrame() {
        setTitle(getClass().getName());
        createContentPane();

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        pack();
        setVisible(true);
    }

    void createContentPane() {
        JPanel jPanel = new JPanel();

        JButton grayButton = new JButton("Gray Button");
        JButton colorButton = new JButton("Color Button");
        colorButton.setBackground(Color.red);
        colorButton.setForeground(Color.white);

        jPanel.add(grayButton);
        jPanel.add(colorButton);
        getContentPane().add(jPanel);
    }
}

Output

[user]$ javac SwingApplication.java
[user]$ java SwingApplication

Quote of the Day

"Real Programmers don't eat quiche. They eat Twinkies. And Szechwan food. (Do not go to eat Szechwan food with a group of Real Programmers unless you are prepared to argue bitterly over the last spring roll.)"
(Vleck 1982).

References

Thursday, April 14, 2005

Iteration

"Q: How do you keep a programmer in the shower all day? A: Give him a bottle of shampoo which says "lather, rinse, repeat.""

Introduction

Iteration is also known as loop or repetition. A statement or a block of statements are executed repeatedly as long as a specified condition is true.

Infinite loop

Program

public class Loop {
    public static void main(String[] args) {
        for(; ; ) {
            System.out.println("Java is cool");
        }
    }
}

Output

Java is cool
Java is cool
Java is cool
Java is cool
Java is cool
...

Infinite counting

Program

public class Loop {
    public static void main(String[] args) {
        for(int i = 0; ; i++) {
            System.out.println(i);
        }
    }
}

Output

0
1
2
3
...

Counting to "ten"

Program

This program counts 10 numbers, from 0 to 9.

public class Loop {
    public static void main(String[] args) {
        for(int i = 0; i < 10; i++) {
            System.out.print(i + " ");
        }
    }
}

Output

0 1 2 3 4 5 6 7 8 9 

Resources

Conditional

Introduction

Conditional is also known as decision, selection or alternation.

Control Structures

Introduction

Structured programming is about getting rid of goto statements. In order to do so, we need to abstract away from goto statements, and replace gotos with control structures. Actually, Java programmers do not have a choice, since Java do not have the goto statement.

Discussion

Even if Java does not have a goto statement, the keyword goto is reserved. The idea is that the Java compiler may produce better error messages if the keyword goto is used (JLS3 2005).

It has been shown that any program can be written, without the goto statement, using only the control structures sequence, conditional and iteration.

Note: In 1964 Corrado Bohm and Guiseppe Jacopini proved the Structure Theorem. The theorem states that any algorithm can be expressed using only three basic control structures Sequence, Conditional and Iteration.

References

Resources

Quote of the Day

"Real Programmers don't comment their code. If it was hard to write, it should be hard to understand."
(Vleck 1982).

References

Wednesday, April 13, 2005

Quote of the Day

"Real Programmers don't write specs — users should consider themselves lucky to get any programs at all, and take what they get."
(Vleck 1982).

References

Tuesday, April 12, 2005

Quote of the Day

"Real Programmers innovate, others litigate!"
Anonymous

Monday, April 11, 2005

Quote of the Day

"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).

References

Wednesday, April 06, 2005

How to Write, Compile and Run an Applet

How to Write an Applet

Note: Unless you are a programmer, you will never need to know how to write, compile or run Java applets. Java applets are compiled in the same way as Java applications, but run inside a browser.

Program

import java.applet.Applet;
import java.awt.*;

public class JavaApplet extends Applet  {
    public void init() {
    }

    public void start() {
    }

    public void stop() {
    }

    public void destroy() {
    }

    public void paint(Graphics g) {
        showStatus("status");

        g.setColor(Color.blue);
        g.drawString("Hello World!", 100, 80);

        // Draw a Rectangle around the applet's display area.
        g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
    }
}

HTML

<applet code="JavaApplet.class" width="300" height="200"></applet>

How to Compile an Applet

javac JavaApplet.java

How to Run an Applet

Usually applets run inside a browser. But when developing applets, it may be more efficient to use the appletviewer program.

appletviewer JavaApplet.java

Note: The JavaApplet class must be public, so that browsers can get access to the class.

How to Write, Compile and Run an Application

How to Write an Application

Now that you know what a program should look like, it's time to add code that does something "useful", like writing "Hello World!". You may use a simple editor to write the program below. Make sure that you save the file as HelloWorld.java. See Getting Started for a few editors you could use.

How to Compile an Application

The Java compiler is called javac.

Open a Linux terminal window or MS-DOS window and compile the HelloWorld.java file with the javac compiler:

[user]$ javac HelloWorld.java

The program still doesn't produce output, because it must run first.

How to Run an Application

Finally, you may run the HelloWorld.class file with the Java interpreter called java. Type the following commands (and do not use the .java file extension):

[user]$ java HelloWorld
Hello World!

Watch the terminal window, and observe that your program just wrote Hello World!

Discussion

When you tell the Java Virtual Machine to run your application, you must specify the class where execution should start, HelloWorld, and you may also pass some parameters to the application. (No parameters are passed in this example.)

Think of HelloWorld as the title of the program. The program must be saved in a file named HelloWorld.java, because HelloWorld is the name of the class containing the main method and because the file extension .java must be used for all Java programs.

Conclusion

Now, you know how to write a program that prints something to the screen. You also know how to compile and run it. This is about all you need to know in order to follow the rest of the tutorial. In addition you should read about Swing applications when needed.

Exercise: Write a Java application that writes your name to the screen.

Tuesday, April 05, 2005

SIMULA 67

Introduction

SIMULA 67 introduced Object-Oriented Programming ().

Resources

"SIMULA 67 introduced the concept of classes, including instancing and coroutine. This was the beginning of data abstraction."
See: http://www.cs.iastate.edu/~leavens/ComS541Fall97/hw-pages/history/simula.html

FORTRAN

Discussion

Almost all programs was written in machine language or assembly language before 1954 (Backus 1978).

Unfortunately, Backus and his team did not know the work of Konrad Zuse. The programming language "Plankalkül" invented by Zuse, and completed in 1945, was an elegant and advanced programming language more than fifteen years ahead of its time (Backus 1978).

FORTRAN introduced expressions (http://www.cs.bris.ac.uk/Teaching/Resources/COMS11200/notes/notes9.html).

References

Author Backus, John
Year 1978
Title The History of FORTRAN I, II, and III.
Place San Jose, California
Publisher IBM Research Laboratory
Retrieved April 13, 2006
URL http://community.computerhistory.org/scc/projects/FORTRAN/paper/p165-backus.pdf

ALGOL 60

Discussion

  • ALGOL introduced structured programming (http://www.cs.bris.ac.uk/Teaching/Resources/COMS11200/notes/notes9.html).
  • ALGOL 60 introduced BNF notation ().
  • ALGOL 60 introduced recursion ().
  • ALGOL 60 introduced blocks ().

The idea of using bold type for keywords, indicating that they are reserved, comes from Algol 60 (Barron 1977).

Block

"ALGOL 60, introduced block structure and scope, pass-by-value, and pass-by-name."
See: http://www.cs.iastate.edu/~leavens/ComS541Fall97/hw-pages/history/algol.html

References

Monday, April 04, 2005

The JLS2 Grammar

Introduction

The JLS2 grammar is "borrowed" from The Java Language Specification, Second Edition (JLS2 2000).

  • The JLS2 grammar (JLS2 2000) is presented piecemeal from chapter 3 to chapter 17 in the JLS.
  • The JLS2 grammar is written in ISO/IEC 14977:1996 EBNF notation.
  • The JLS2 grammar is independent of font color and type. It is possible to try out rules by substituting with copy and paste.
  • The JLS2 grammar should be a useful tool when reading for the SCJP exam.

Why another Java grammar?

I wanted the whole grammar in one HTML page, making it easier to find a rule.

I wanted all nonterminal symbols to be clickable, making the browser automatically search for the correct rule.

I also wanted an index of all terminal symbols and nonterminal symbols, with clickable references to all rules that the symbol occur within. If you click a rule name, the browser will even take you to the index of that rule.

I wanted a grammar with color coding. Terminal symbols are shown in blue, plain type. Nonterminal symbols are shown in black, italic type. Parenthesis are shown in red, italic type. Operators are shown in purple, italic type.

Errata

  • "ISO/IEC 14977 : 1996(E)" states that - except-symbol (Java: "but not") should have higher precedence than | definition-separator-symbol (Java: a separate line), but this is clearly not the case in the rules NotStar, NotStarNotSlash, and Identifier, perhaps because of readability. i.e. the rule "Identifier: IdentifierChars but not Keyword or BooleanLiteral or NullLiteral" should be written "Identifier: IdentifierChars but not (Keyword or BooleanLiteral or NullLiteral)"
  • Rules with nonmatching italic parenthesis or terminals written in italic have been corrected. Examples are the rules "IdentifierSuffix", "MoreStatementExpressions", "TypeDeclaration".
  • The "Expression" rule contains one too many ']'.
  • The "Expression3" rule references the "Expr" rule that does not exist. The reference is replaced by the "Expression" rule because of similar use in the "Primary" rule.
  • The "Statement" rule references the "ForInitOpt" rule that does not exist. The reference is replaced by "[ForInit]".
  • The "Statement" rule references the "ForUpdateOpt" rule that does not exist. The reference is replaced by "[ForUpdate]".
  • The "Statement" rule references the "ExpressionStatement" rule that does not exist. The reference is replaced by "StatementExpression".
  • The terminals ".class" and "void.class" is replaced by ". class" and "void . class", the terminal "default:" is replaced by "default :", and the terminal "[]" is replaced by "[ ]" This is done for clarity. The characters '.', ':', '[' and ']' are separators that generally allows white space.

References

  • JLS2. (2000). The Java Language Specification, Second Edition. California: Sun Microsystems, Inc. Retrieved Monday, Monday, April 04, 2005 from http://java.sun.com/docs/books/jls/.

Saturday, April 02, 2005

Primitive Types

Introduction

A primitive type is also called a

  • elemental type
  • atomic type

A type has a set of values associated with the type.

Discussion

Concept: Types provides meaning and readability. Types can be checked automatically at compile time, saving you a lot of time debugging.

For programming, we need primitive types that are suitable to the programming task.

Grammar:
PrimitiveType =
    NumericType | 'boolean' ;
NumericType =
    IntegralType | FloatingPointType ;
IntegralType =
    'byte' | 'short' | 'int' | 'long' | 'char' ;
FloatingPointType =
    'float' | 'double' ;

Note: A variable has one of 8 primitive types;
boolean, char, byte, short, int, long, float or double

Note: Not everything in Java is objects. Variables declared with the primitive types in Java are not OOP-objects.

Primitive Types
Type Name Bits Group Value Range (Inclusive) Example
boolean 8, unsigned bool true and false boolean n = true;
byte 8 integral from -128 to 127 byte b = -128;
short 16 integral from -32768 to 32767 short s = 32767;
int (default) 32 integral from -2147483648 to 2147483647 int i = 2147483647;
long 64 integral from -9223372036854775808 to 9223372036854775807 long l = 21L;
char 16, unsigned integral from 0 to 65535 char c = 'A';
float 32 floating point from 1.4E-45 to 3.4028235E38 float f = 1.41f
double (default) 64 floating point from 4.9E-324 to 1.7976931348623157E308 double d = 3.14;

Types

"Real Programmers don't write in PASCAL, or BLISS, or ADA, or any of those pinko computer science languages. Strong typing is for people with weak memories."
(Vleck 1982)

Introduction

Types are important because they limit what a programmer can do with values and operators. If operators and values used in expressions are incompatible, then the compiler may automatically warn the programmer about the mistake. Such warnings could help the programmer to avoid some serious errors.

Clearly, values such as 42, 'a' and true are somehow different from one another.

Also, an operator should not be compatible with all types of values. The following program is illegal:

public class Main {
    public static void main(String[] args) {
        System.out.println(42 / true); // error
    }
}

because the / operator does not make sense with these values.

Concept: A type defines a set of values and a set of operators.

Concept: Every value is of a type.

Concept: Every expression has a type.