Pascal to Java: Easy Transformation Part 1





Introduction

Hi, I'm back to write some tutorials. This time, I'd like to share on how Pascal programmers could easily learn Java. Note that the method I'm going to describe here is a shortcut, so that you, object oriented programming gurus, take this as a precaution as I won't teach a proper OOP here. I just want to share this tips so that Pascal programmers don't spend too much effort on OOP gimmicks on learning the fun part of Java. Of course my hope is that all of those Pascal freaks will eventually apply the real OOP when they do Java. Note also that you don't even have to understand OOP before learning Java although it's really useful if you do.

I'm writing this tutorials because there are so many talented programmers in Indonesia so hooked up with the Pascal. I loved it, but now no more since Pascal is no longer properly developed. I simply can't count on Delphi or other variations of 32-bit Pascals since they are NOT standardized. Hey, I don't hate Pascal. I just want that all of those guys keep up with the cutting-edge technology, namely Java. Those guys are not familiar with OOP. So, I write on this guide for those audience to quickly adopt Java.

I do assume that you, my dear reader, 100% familiar with Pascal or Turbo Pascal. I also assume that you have already installed Java SDK from Sun before started. I assume that you can use your text editor and be familiar on compiling Java program. I describe only a bit about compiling Java program here, but it's limited on DOS box on Windows.

I must admit that this article is far from perfect. I just provide you with the essentials so that you can get the valuable insights. You may have a lot of questions and want to read some more after you read this article. I will write the second part of this, but I'm not sure when. Stay tuned. I'll cover some more for you.

Simple Program Structure

Allright! Straight to the stuff. Pascal-style program will take on structure similar to this:

program blah;
var
 : { Global variables }

{procedures or functions}

begin
 : { main block }
end.

You should be familiar to this. Now, let's look at Java counterpart:

public class blah {
   : // Global variables

   // functions

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

Hmm... looks very familiar. Note that if you name your class blah, you MUST name your file blah.java. Be careful with its capitalization since Java is case sensitive.

Before going on, I remind you that Java is case sensitive. So: This, this, and tHiS are considered different. I know this is somehow annoying to you as this was to me. However, this can be a very useful feature when you're kinda lazy to spawn up bizzare names for a particular variable name by just differing its capital letters.

To compile it, just type javac blah.java and then type java blah to run it. Remember to specify .java extension while compiling and omit it to execute.

Rather than explaining programming structure differences one by one, I'd rather let you skim through this program in Pascal and then look for its equivalent in Java.

program MyProg1;
var
  x, y : integer;
  loong : longint;
  mystr : String;

{ Comment here }
(* This is a comment too! *)
procedure myProc;
var
  i : byte;
  b : boolean;
begin
  i := 5;
  b := i = 7;
end;

function myFunc: integer;
begin
  myFunc := x*y;
end;

begin
  writeln('How are you?');
  x:=4; y:=5;
  writeln('myFunc is ',myFunc);
end.

It's Java equivalent is below. You have to name the program MyProg1.java in order to compile.

public class MyProg1 {
   public static int x, y;
   public static long loong;
   public static String mystr;

   /* Comment here */
   // This is a comment too!
   public static void myProc()
   {
      byte i;
      boolean b;

      i = 5;
      b = i==7;
   }

   public static int myFunc()
   {
      return x*y;
   }

   public static void main(String[] args)
   {
      System.out.println("How are you?");
      x = 4; y = 5;
      System.out.println("myFunc is "+myFunc());
   }
}

Wow! The transformation is that easy!!! Yes it is. Can you notice the similarity? I'll explain it one by one. Firstly, the variable declarations. Basically the syntax is:

vartype  varname [= default_value] [, varname ...] ;

Then, you wonder: Why on earth should we put the terms public static thing when we declare global variables? Well, it's because at the initial run, Java will call off the main procedure, which is recognized as the main block of your program. This call requires the main procedure to be declared as public static. A static procedure can call other static procedures (at least at this point of understanding). That's why we should declare myProc and myFunc to be static. Note that the public in this case is optional. However, for now, let's leave it this way just to "uniformize" things.

Static procedures can use only static variables. That's why we -- again -- stick those words in declaring global variables. Declaring local variables, as inside myProc, do NOT require this. Even, you have to strip those terms off! Well, if you don't quite understand, just remember that you have to put public static when you declare global variables and you should not put them when you declare local variables.

Variable scope is just like Pascal: i.e. you can see variables after you declared them and inside the scope where you define them, EXCEPT global variables. Global variables are recognized throughout the program even at the point where you have not define them. So, let's take the above example. If you define the variable x and y after the closing brace of main procedure (i.e. before the last brace), myFunc will still recognize them.

Likewise the procedure/function declaration. Function or procedure declarations are recognized throughout the program. So, the order of how the procedures and functions are placed is no longer significant. In other words, in Pascal, the current procedure can only call the procedures and/or functions above them. This is no longer necessary in Java. You can call any procedures or functions below you. Ha! forward keyword is therefore made obsolete! You're right! ;-)

If you wonder what are the variable types, see this table:
PascalJava
shortintbyte
byteunsigned byte
integerint
wordunsigned int
longintlong
realfloat
doubledouble
booleanboolean
stringString

Note that Java's integer is 64-bit! So, you don't need a long integer any more for most of the cases :-)

You can notice the comment declarations. Comments in Java are begun with /* and ended by */. There is a special kind of comment that begins with a double slash (//). Whatever behinds it is considered as comment.

Function Declarations

Note that in Java, just like C/C++, we don't have procedures. We have functions only. The declaration is as follows:

returnType funcName([paramType paramName[, ...]])
{
  : // Body
}

You can easily note that procedures are simply functions with no returns. So, we put the keyword void in place, as you notice in myProc. For the examples on how the functions with parameters look like, see below:

public static int exampleFunc(int param0, int param1)
{
    return param0+param1;
}

Note that parameters in Java are passed BY VALUE ONLY. There is no way for you to pass it by reference. You have work around this when you encounter these kinds of need. Don't be discouraged, though. Java's functions are more powerful than that of Pascal's. It can return arrays and structures!

Basic Structures

I try to summarize the basic structures below:
StructurePascalJava
if
if cond then
begin
  :
end else
begin
  :
end;
if (cond)
{
  :
} else
{
  :
}
for
for i:=x to y do
begin
  :
end;
for(i=x; i<=y; i++)
{
  :
}
while
while cond do
begin
  :
end;
while (cond)
{
  :
}
case/switch
case x of
  1: begin
       : { 1 body }
     end;
  2..4: begin
          :  { 2 to 4 body }
        end;
  else  begin
          :
        end;
end;
switch (x)
{
   case 1:  : // 1 body
            :
            break;
   case 2:
   case 3:
   case 4:  : // 2 to 4 body
            :
            break;
   default:
      : // else body
}
repeat
repeat
  :
until cond;
do {
  :
} while (!(cond));

Easy right? Notice that there are significant philosophy difference between the two. Ifs and whiles are similar. Of course the else block is optional, as usual. In the case of for, actually Java's for is more powerful. I'd rather not discuss it in depth. You should refer to my Java tutorial or other reading material. The Java's switch, you should enumerate the cases in case you want several choices into one block as shown above (i.e. 2, 3, and 4). Actually Pascal's repeat..until has no equivalent structure. I chose to match it with Java's do..while. The difference is that Pascal's repeat..until repeats its body until the condition is true, i.e. repeats while the condition is false -- whereas Java's do..while repeats its body until the condition is false, i.e. repeats while the condition is true. Thus, the condition part in do..while has to be negated by exclamation mark sign (!).

Operators

Most of the Pascal's keywords defining operators, such as and, or, and mod are replaced by symbols in Java. Here is the table of those operators:
OperatorPascalJava
Boolean andand&&
Bitwise andand&
Boolean oror||
Bitwise oror|
Boolean xorxor(none)
Bitwise xorxor^
Modulomod%
Shift leftshl<<
Shift rightshr>> or >>>

Boolean operators are used in conditions part of ifs and whiles whereas bitwise operators are used to obtain bitwise calculations. For example: x := y and 3 here, the operator and served as a bitwise operator. Whereas in if (y and 2)=2 then, the operator and served as a boolean operator.

Note also in shift right we have two versions. >> will retain negative signs if any, whereas >>> will not.

Arrays

To define arrays is as follows:

int[] x;

This will define x as an array of integers. The bound is not yet known. In order to use x, you have to define the dimension of it somewhere in your program. Such as:

x = new int[5];

This will define x as a one-dimension array with 5 containers. So, there are x[0], x[1], x[2], x[3], and x[4]. Note that array index always begin from 0. Of course, you can use an integer variable instead of the integer 5. This can be a great feature for you.

Accessing the array is similar. Use the square bracket to denote its index.

Java's array have a special property: .length, which tell you how many elements are in the array. So, for the example above, when you query x.length it will return 5.

You can of course redefine the array dimension by using the new statement shown above. However, you have to know that the old content will be erased.

There is a unique feature in Java in defining multi dimensional array. Look at the following example:

int[][] x;
x = new int[3];
x[0] = new int[4];
x[1] = new int[2];
x[2] = new int[1];

Hmm... In the above example, x is a two-dimensional array. At first, we define that x has 3 rows: 0, 1, and 2. Then, we can define how many columns EACH row may have by defining those in each row shown above. So, row 0 will have 4 elements, row 1 will have 2 elements, and row 2 will have only 1 element. Note that if you query x.length, it will return 3. x[0].length will return 4, and so on.

Constants

To define constants, you can define it just like defining variables with one extra keyword: final. For example:

public static final float pi = 3.1415926535;

Remember that you have to define it inside a class.

Structures

In Java, everything has to be defined inside a class. Thus, even a structure (or a record) has to be defined as a class. However, you have to omit the public keyword that is normally placed in front of the class. So:

type
   myrec = record
             name  : string;
             score : integer;
           end;

Will translate as:

class myrec {
   public String name;
   public int score;
}

Note that the static keyword also disappears in records. To use it in the program, you have to define a variable of that type just like you did in Pascal:

myrec mydata;

However, the difference is that you have to new it before use, just like in the array above:

mydata = new myrec();

Then, you can use it normally. For example:

mydata.name = "Blahblah";

String Accesses

See the table below for quick comparisons:
OperationsPascalJava
Comparison equals1 = s2s1.equals(s2)
Comparison less thans1 < s2s1.compareTo(s2) < 0
Comparison greater thans1 > s2s1.compareTo(s2) > 0
Concatenations := s1+s2;s = s1+s2;
Uppercasefor i:=0 to val(s[0]) do s[i] = upcase(s[i]); s = s.toUpperCase();
Lowercasefor i:=0 to val(s[0]) do s[i] = locase(s[i]); s = s.toLowerCase();
Lengthn := len(s);n = s.length();
Positionn := pos(s,c);n = s.indexOf(c);
Substrings := substr(s1,x,y);s = s1.substring(x,y);
Convert to Strings := str(n);s = String.valueOf(n);
Convert from String(none)n = Integer.parseInt(s);

Note that for convert from string, Pascal programmers have to do conversion on their own whereas there is a built-in function in Java. Of course you have to replace Integer.parseInt with the appropriate phrase, such as: Float.parseFloat or Long.parseLong.

Note that to work around for compilers complain about unhandled exception and stuffs in conversion, you have to surround the conversion lines with try..catch block, which has no Pascal equivalent. It will be explained below.

Exception Handling: The Practice You Should Do

To do exception handling in Java, do as follows:

try {
  : // try body
} catch(Exception e)
{
  : // catch body
}

The use of this structure is that whenever there is an error happenned within the statements of the try body, computer will directly jump to the catch body to inform you that there is an error. However after executing the catch body, it will not resume right after the error as you may expect, but fall through the statement below it.

This is kinda useful since you need not to write a bunch of ifs just to detect errors. The downside is that there is no resuming. You can get around with it of course: by setting a variable inside a catch body and put the try..catch block inside a while structure which repeats whenever there is an error.

For example:

do {
   error = false;
   try {
      n = Integer.parseInt(s);
   } catch(Exception e)
   {
      System.out.println("Conversion error!");
      error = true;
   }
} while (error == true); 

For more information on this, please read my upcoming tutorial. :-)

Bunch of Stuffs You'll Miss

Well, you have to sacrifice things to move. However, consider the following benefits:

Conclusion

I know that this article needs a lot of more elaborate work. However, it's 4am in the morning and I'm tired. I guess I'll continue writing next time. I hope that this article will motivate you to at least try on building some applications in Java. If you want some more, wait for the second part of this article. Ciao!


Where to go?

Back To Main
Transformation Part Two
Pascal Tutorial Index

© Roby Joehanes 2001 1