Cup of coffee for dolphins. Part I

Abstract: Java for Delphi programmers. This part describes basic Java instructions compared to Delphi.

Basic instructions

Introduction

As you very well know instructions are the most basic elements of program. Instructions can create more complex constructions as functions, classes, methods and a program as a final result. Compiler translates program from a text written in a programming language into a machine laguage which can be understood by a specified machine. For many languages it is a native code of a processor (such as x86 family) or virtual machine as in Java example. The main subject of this part is to compare basic instructions of Delphi and Java. Here I assume that you are familiar with Object Pascal language - its instructions, structure. I will underline part where some misunderstaings could appear. Instructions whoch appear inly in one language are marked.

Comments

The most important part of computer program - some people even says that software cannot run without them. Well... Lets compare what type of comments are available in Object Pascal and Java:

Single line

Both langauages allow for creating single line comments. Such comment is created using two slashes. The ar very often used for quickly commenting out single lines of code. Let see the example below:

// This line is fully commented
// This comment looks the same in Java and Pascal
// Writeln('This line is commented out in Pascal');
// System.out.println("This line is commented out in Java");

Multiline

For writing comments which extends on several lines you can use curly brackets in Object Pascal - { } and /* */ in Java. For new Java programmers who are used to Pascal all code is commented out :-) : Java:

/*
 *  Here is multiline comment
 *  This is in Java
 */

Delphi:

{
 *  Here is multiline comment
 *  This is in Delphi
}

Javadoc comment [Java only]

Java introduces one type of comment which helps in creating the source code documentation. It starts with '/**' and ends with '*/'. All text included in this comment can be extracted using javadoc tool to javadoc help. There are several keywords which describes code that follows - @param for method parameter, @return for comment on return value and much more. Here is an example of comment which generates Java documentation for a method setCurrency in NumberFormat class:

/**
  * Sets the currency used by this number format when formatting
  * currency values. This does not update the minimum or maximum
  * number of fraction digits used by the number format.
  * <p>
  * The default implementation throws
  * <code>UnsupportedOperationException</code>.
  *
  * @param currency the new currency to be used by this number format
  * @exception UnsupportedOperationException if the number format class
  * doesn't implement currency formatting
  * @exception NullPointerException if <code>currency</code> is null
  * @since 1.4
  */
  public void setCurrency(Currency currency)

For output generated by a javadoc see documentation in JDK directory jdk/docs/api/java/text/NumberFormat.html#setCurrency(java.util.Currency).

Assignment

Assignment instruction in both languages looks the same. The only difference is in the assignment operator. In Delphi it is ':=' when in Java it is a simply '='. So, if in Delphi we have:

i := 7;
object := Edit1;
isEqual := true;
object := TObject.Create;

then in Java it looks like this:

i = 7;
object = Edit1;
isEqual = true;
object = new Object();

Remember that assignment does not create a new object but only copies a reference to it.

Comparison and if

Ok. Now about comparing values...The most often we compare values in when we need a condtion in if statement or loops. We all know very good comparing operators in Object Pascal. Following table lists those operators with matching Java ones:
Object Pascal operators     Java operators     Description
a = b a == b Returns true if values are the same on both sides of the operator
a <> b a != b Returns true if values are different
a > b a > b Returns true if a is greater then b
a < b a < b Returns true if a is smaller then b
a and b a && b Returns true if both a and b are true.
a or b a || b Returns true if a or b is true.
Looks very simply but there is a small hook.When you try to compare two objects - especielly String objects (they are often confusing for Pascal programmers). Operators above are comparing values - objects variabls contain a reference to the object, String object contain a value which is string. Let's consider following Object Pascal code:

Begin
  If ParamCount <> 2 then begin
    Writeln('Run program with two parameters');
  End else begin
    Writeln(ParamStr(1) = ParamStr(2));
  End;
End.

Compile and execute this program. First run with two the same parameters - for example "object", "object". Then with different - "one", "two". First run will return TRUE and the seconde one FALSE.
true
false
Now let's examine the same looking Java code:

public class TestCompare1 {
  public static void main(String[] args){
    if (args.length < 2)
      System.out.println("Run program with two parameters");
    else
      System.out.println(args[0] == args[1]);
  }
}

What sould we do to compare values instead of references ? All Java objects inherit (extend) java.lang.Object class which intoduces equals method which compares tw!j objects. Method equals in String class does exactly the same as "=" operator in Delphi. Example below does what we need:

public class TestCompare2 {
  public static void main(String[] args){
    if (args.length < 2)
      System.out.println("Run program with two parameters");
    else
      System.out.println(args[0].equals(args[1]));
  }
}

So... Why the code below prints "true" ?

public class TestCompare3 {
  public static void main(String[] args) {
    String s1 = "STRING";
    String s2 = "STRING";
    System.out.println(s1 == s2);
  }
}

that's exactly the way we would do in Delphi. Because both "STRING" values are constants the compiler optimizes the code and creates only one "STRING" constant - try examining TestCompare3.class file with some kind of binary viewer. You will see only one "STRING". Now a few more words about if. Let's compare general syntax:

if condition then   
  instruction;

if condition then   
  instruction
else
  instruction;


if (condition)   
  instruction;

if (condition)
  instruction;
else
  instruction;
First thing which you see (or rather don't see) is the missing word then in Java. Second - brackets around the condition. But one more thing is near the else - in Delphi there is no a semicolon before else. In Java semicolon is necessery if you put only one instruction:

If  k = 0 then   
  k := 1
else
  k := 0;

if  (k == 0)   
  k = 1;
else
  k = 0;
But when there is a set of instructions in begin...end block then semicolon is not needed (better word would be illegal:

If k = 0 then begin   
  k := 1
end else begin
  k := 0;
end;

if (k ==  0) {
  k = 1;
} else {
  k = 0;
}

Loops

Both languages have the same loops:
  • For
  • While
  • Repeat (or similar)
Below you can find a comparison of those loops.

For

Delphi for loop generaly looks like this:

for variable_counter := start to expresion do instruction;
for variable_counter := start downto expresion do instruction;

These loops rewritten in Java will look like this:

for (variable_counter = start; variable_counter <= expresion; variable_counter++)
  instruction;
or

for (variable_counter = start; variable_counter >= expresion; variable_counter--)
  instruction;
As you see - moving fromPascal to Java is easy but under some conditions they can work differently. Let's compare two following programs:

Program ForTest;
{$APPTYPE CONSOLE}
function loop : integer;
begin
  Writeln('Loop');
  Result := 10;
end;

Var
  I : integer;
Begin
  For i := 1 to loop do
    Writeln(i);
end.
And in Java:

public class ForTest {
  public static void main(String[] args) {
    for (int i = 1; i <= loop(); i++) 
      System.out.println(i);
  }

  public static int loop() {
    System.out.println("Loop");
    return 10;
  }
}
As yo very well know (but I bet sometimes forgot as some of my friends) final expression in Delphi is evaluated only once. So the output of Delphi program will be this:

Loop
1
2
3
4
5
6
7
8
9
10
But in Java this expression is evaluated in every iteration. So even those programs look the same the output of Java program will be:

Loop
0
Loop
1
Loop
2
Loop
3
Loop
4
Loop
5
Loop
6
Loop
7
Loop
8
Loop
9
Loop

So remember - when you are porting for loop check your final expression as it will be evaluated only once in Delphi but in every iteration in Java.

One more difference, quite comfortable in my opinion, is possibility to declare loop variable in a for statement like this:

for (int i = 0; i < 10; i++)
  System.out.println(i);

Variable i is only visible in instructions which are executed in the loop.

While

This loop hasn't got suprises like the previous one. Porting is easy - you only have to add parenthesis around the loop condition, remove do keyword and replace begin...end block with curly brackets:

while condition do   
  instruction;


while (condition)
  instruction;

For example:

Var
  K : integer;
Begin
  K := 10;
  While K > 0 do begin
    Writeln(K);
    Dec(K);
  End;
End;

In Java this code looks like this:

int k = 10;
while (k > 0) {
  System.out.println(k);
  k--;
}

Repeat

At first glance there is no such loop...but simply Java hasn't got such keyword: repeat. Pascal's repeat...until loop is simply a do...while in Java.

Repeat
  Instructions;
Until condition;  


do {
  instructions;
} while (!condition);

What are the differences between those loops ?
First thing which you see is that you must negate the condition and put it into parenthises (as all conditions in Java).
Second - remember that repeat...until acts also as begin...end block. So if you ant to put more than one instruction in this loop you don't have to use the begin...end. In Java for more than one instruction you must use curly brackets.

Case statement

Ok... again this boring syntax:

case selectorExpression of    
  caseList1: statement1;
  ...			
  caseListn: statementn;
else
  statement;
end;

switch (selectorExpression) {
  case caseList1Item1:
  case caseList1Item2: statement1;
    break;
  ...
  case ListnItem: statementn;
    break;
  default: statement;
}
So...what we have here ? Case word changes to switch and expresion goes into brackets. Next - as you already recognized else turned into default - instructions which follow this keyword are executed when no matching case is found:

Var
  K,M : integer;
Begin		
  ...  	
  case k of
    1 : Writeln(M*M);
    2 : Writeln(1 / M);
    3 : Writeln(M + M);
  else			
    Writeln(M);	
  End;			
End;


int k;
int m;
...
switch (k) {
  case 1: System.out.println(m*m);
    break;
  case 2: System.out.println(1 / m);
    break;
  case 3: System.out.println(m + m);
    break;
  default:
    System.out.println(m);
}	

These two pieces of code do the same thing - performs operation on an integer value depending on a parameter. As you noticed at the and of case statement in Java appeared a word break. If you change Java code to look like this:

case 1: System.out.println(m*m);
case 2: System.out.println(1 / m);
  break;

the output genereted would be :

<m>*<m>
1 / <m>

Why ? Think about switch as about a goto instruction and case value as about a label. Key word break jumps to the end of the switch. In Pascal each case value makes a discrete jumpt to end of case. So... if you forget about break the code will be executed line by line as written in a program. But... Pascal allows you to do this:

Var
  C : char;
Begin
...
case c of
'0'..'9' : writeln('Digit');
...
end;

In Java you must prepare a case of each value between '0' and '9':

switch (c) {
  case '0':
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9': System.out.println("Digit");
    break;
  ...
}

Goto and jumps

This chapter will be short and easy. Why ? Simply Java has no word for Pascal's goto. You must rewrite the code which uses goto instruction.

With

Unfortunatelly this chapter is short too. With statement is typical for Pascal. In Java it does not exist.
If you are interested in more articles about "Java for Delphi programmers" please let me know.

Server Response from: BDN9A

 
© Copyright 2008 Embarcadero Technologies, Inc. All Rights Reserved. Contact Us   Site Map   Legal Notices   Privacy Policy   Report Software Piracy