Previous
Index

Next


Chapter 2 Syntax and data types

2.1) Origins of Java syntax

The syntax of Java is strongly based on that of C++. This was partly because there were so many C and C++ programmers in the world that Sun thought the language would be more likely to become popular if plenty of existing programmers found it easy to learn. One of the problems with C/C++ is that many important details are "vendor implemented". Although the languages have internationally accepted standards, there are areas within the standard that are left to the compiler creators. This means that a feature that will work in one version of a compiler will break in another due to subtle incompatibilities.

This has resulted in situations if you want to write meaningful GUI application you need to learn an entire separate programming library. So you might chose to use Microsoft MFC, .NET the QT Toolkit or wxWidgets. Learning these is a big task and there no single standard to learn. By contrast Java has had two main toolkits for GUI applications, the AWT and the fairly similar but more advanced Swing toolkit.

Two of the ways that Sun produced a simplified language is the removal of the direct manipulation of pointers and only allowing single inheritance. Direct manipulation of pointer as in the use of the * operator in C/C++ is a major source of bugs in programs. Java does use pointers, but they are hidden behind references and cannot be directly manipulated. If you are from a Visual Basic background this may be meaningless, but for C/C++ programmers it is an interesting departure.

Flow Control

Flow control is the ability to dynamically change the path of execution a program takes. Thus when you start a program you might give it a file name to process. If the file exists it will open the file, if it cannot find the program it might put up a dialog asking you to type in the file name. As well as making a decision about what line of code to run after a decision, flow control means you can branch to an entirely different chunk of code by calling a method, depending on the result of some test.

There are several standard types of flow control common to most programming languages that only vary in the details of syntax. Thus in the past I have had familiarity with C/C++, Pascal, Perl. Visual Basic and now Java and all of those languages have more in common in their flow control statements than they differ. For example most languages support variations on the theme of if/else while and do loops.

if/else

The control structure that is probably most common between languages is the if and the if/else construct.

Example of how if can be used


As you might expect the if statement tests if something is true. Although what Java considers to be "true" can be subtly different from some other languages. For Java true is always a boolean test. It does not have any concept of true being zero, one or minus one, it is always a boolean comparison.

An if test must always evaluate to a boolean value, you cannot test if it returns 1, zero or -1 or anything but a boolean

If the test is true the lines of code immediately afterwards are executed, otherwise different lines get run.

To give a typical example

int i=0;
if (i==1){
        System.out.println("Good morning");
}

The curly braces create a block of code, which means if the test is true it will execute multiple lines of code. You can use the if statement without the braces so it is only the next line that is executed conditionally, using this format the previous example would appear as

int i=0;
if (i==1)
        System.out.println(" Good morning");

However, many people consider this to be bad style as it is too easy to get confused as to where the impact of the if statement starts and stops.

The if/else construct is a close relation of the lone if statement. It adds a block of code that will execute only if the test of the if statement was false. Thus

int i=0;
if (i==1){
        System.out.println("Good morning");
}else{
     System.out.println("Good afternoon");

}

This is an either/or construct. If the value of i is equal to one then "Good morning" is output, if it is not then "Good afternoon" is output.

The final variation on the if construct is else/if. If you have a situation with more than two alternatives you can have an arbitrary number of else ifs before the final else.

if(i==0){
                System.out.println("Good morning");
        }else if (i==1){
                System.out.println("Good afternoon");
        }else{
                System.out.println("Good night");
        }

This is really just an extension of the if/else construct with additional if statements after the else.

Note that whatever is tested between the parenthesis must evaluate to a boolean value. Thus the test in the example if(i==0) is either true or false, it is not a number. This is in contrast to the C/C++ languages (and possibly some others) where there is a convention that an evaluation that returns zero is false and any other value is true.

In C/C++ you can test with syntax such as

int i=1;

if(i){
//do something
}

In Java an if clause must be a boolean test. Thus you can re-state that example as

if(i==1){
//do something
}

Also note that the test is performed with the == operator and not the assignment operator =. Sooner or later everyone tries to compile code with a test like this

if(i=1){
        //do something
}

This simply assigns the value of 1 to the variable i, rather than testing the condition. Luckily Java will flag this type of error at compile time.


Exercise ForDemo

Create a Java program calld MyIf that accepts a command line parameter of the words bash or cmd.

Within your program write code that examines the parameters passed to the command line command line. To do this you need to pass the parameters to main to your method. Thus if your method was called go instead of empty parameters it needs to accept a String array as in public void go(String argv[]). If you are using NetBeans you can set the parameters by right clicking on the project and selecting the run option. Within that screen there is an arguments field.

If the command string is “bash” the program outputs “Linux” and if it is “cmd” it outputs “Microsoft”. Once that is working, extend your program so that if the input is neither bash or cmd it outputs a string saying it does not recognise either option.

While/do while

The while construct allows a program to loop for a number of times depending on some test. The difference between a simple while and a do-while can easily be overlooked. Essentially a while loop will execute zero or more times and a do-while loop will execute one or more times. If you think of the implicit logic the words do-while imply

"do this while something is true", indicating that the test will come after the loop has executed at least once. A while construct by contrast does the test before performing the first loop.

In actual Java code a while code looks like this

int i=1;
while(i <1){
        System.out.println(i);  
}

The line i++ will add one to the variable i (also known as incrementing). This loop will execute zero times. The while test (i <1) will return false as 1 is not smaller than 1. The code will then continue executing after the closing brace.

The following code will however loop once and output the value of i to the console.

int i=1;
do{
        System.out.println(i);  
}while(i<1);

The for loop

The for loop is very popular with programmers as it combines the creation of counting variables and performing a test on a value all in one neat package. The general structure of the for loop is

for(Create counter variable; test counter; modify counter){
        Body of for loop
}

You can think of these three parts separated by the semi colon as initialise, test and modify.

In actual Java code this typically translates to

for(int i=0; i <3; i ++){
        //Do something in the body of the code
}

In this example the counter variable i was created within the body of the for loop with the statement

int i=0;

The test part simply matches against the number 3, in a real program you would probably testing against some other variable. The modify counter adds one to value of i on each loop around.

Exercise ForDemo

a program called ForDemo that uses a for loop to count from zero to 5 and outputs the current value of the counter index each time around the loop. When the loop has finished execution make the program output the string "Finished".

The foreach loop

The for-each loop was introduced with JDK1.5 (Java 5) and offers a simplified notation for looping the elements of data structures with multiple elements. Thus for example java arrays use a single variable name for a structure that contains multiple values. The following code shows how to traverse each element of an array using the original for loop.

public class ForType{
	public static void main(String argv[]){
			new ForType();
	}
	ForType(){
		int myar[] = new int[]{1,2,3,4};
		for(int i = 0; i < myar.length; i ++){
			System.out.print(myar[i]);
		}
	}
}	



Note how it is necessary to declare the counter value i, set it to zero and increment it by one for each time around the loop. Other languages such as php and perl have an explicit foreach keyword that simply says for each element loop go around the loop. Rather than having a new foreach keyword JDK1.5 introduces a variation of the original for loop as follows.

int myar[] = new int[]{1,2,3,4};
for(int i : myar){
	System.out.print(i);
	}

Exercise MyForEach

Create a program called MyForEach. Write code in the main method that creates an instance of the class and get that instance to call a method you create called go. The go method should take a parameter of the argv that comes from the main method (e.g. go(argv)

Within the body of the go method write a foreach style loop that loops over each element of the argv method and prints it out. Use the previous code example, so instead of myar your code will use argv.

Switch statements

The distinguished Java Author Peter van der Lindens opinion of the switch statement is summed up when he says

"death to the switch statement"

I suspect I will go to my grave without voluntarily writing a Java switch statement. Most languages have some kind of switch statement and I have generally avoided using them in all the languages I have used. Java adds to my dislike of the structure by having some of its own peculiarities. The main one is the use of the break statement in the process of falling through a switch statement. Here is an example of this issue.

int k=10; 
switch(k){
        case 10: 
                System.out.println("ten"); 
        case 20: 
                System.out.println("twenty"); 
        } 



Common sense would indicate that after executing the instructions following a case statement, and having come across another case statement the compiler would then finish falling through the switch statement. However, for reasons best known to the designers of the language case statements only stop falling through when they come across a break statement. As a result, in the above example both the strings ten and twenty will be sent to the output. The argument to a switch statement must be a byte, char, short or int.

The package statement

Java packages work in a very similar way to the file system directory. A package is effectively a name space. Do not think of the package statement as anything to do with library loading, it merely says this class resides in this package and if you substitute the word directory for package you will have some idea of the implication. Because pacakges are about distinct name spaces it is important that the names are unique, and to ensure this there is a convention that packages are named after internet domains. Because no two domain names are the same you can be confident that no to packages will be the same. The domains are used in reverse order, thus for myself I might creata a package called.

package com.examulator;

If I then create a class called Vector within this package I know that there can be no name clash with the official Java class called vector because that exists in the package java.util; Of course it would be a spectacularly bad idea to create a class that used the same name as the well known Sun utility, but the use of packages does make it possible.


Other sources

Packages according to the Sun tutorial http://java.sun.com/docs/books/tutorial/java/interpack/packages.html

Switch according to Eliotte Rusty Harold
http://www.cafeaulait.org/course/week2/42.html




Previous
Index

Next